Skip to content

Payment Integration ​

This guide explains the complete payment flow for accepting testimony offers using Stripe integration.

Overview ​

The payment process involves three main steps:

  1. Checkout Initiation - Client initiates payment and receives a Stripe checkout URL
  2. Payment Processing - Client completes payment on Stripe's secure checkout page
  3. Payment Confirmation - Application confirms payment and accepts the offer

Prerequisites ​

Before You Start

Ensure these requirements are met before initiating payment:

Step-by-Step Flow ​

Step 1: Initiate Checkout ​

Endpoint: Checkout Offer

http
POST /api/v1/testimonies/offers/{offer}/checkout

Required Data:

  • {offer} - The id of the chosen offer
  • phone - Phone number in international format, not used by another user
  • firstName - Client's first name
  • lastName - Client's last name
  • billingAddress - Billing address object (all fields required, line2 included)
  • shippingAddress - Delivery address with the recipient's firstName and lastName (optional; leave it out when the appraisal goes to the billing address; not sent to Stripe)
  • company - Company details (optional; leave it out for an order placed as a private person)

The order keeps these details: the invoices and the delivery address shown to the expert come from this request. They also overwrite the client's profile, and a shippingAddress or company left out is removed from it — prefill the form from Show Current User and send it whole. See Checkout Offer.

Request Example:

json
{
  "phone": "+421902123456",
  "firstName": "Peter",
  "lastName": "Novák",
  "billingAddress": {
    "line1": "Hlavná 123",
    "line2": "Apartment 4B",
    "city": "Bratislava",
    "postalCode": "811 01",
    "country": "SK"
  },
  "shippingAddress": {
    "firstName": "Jana",
    "lastName": "Nováková",
    "line1": "Trieda SNP",
    "line2": "1",
    "city": "Košice",
    "postalCode": "040 01",
    "country": "SK"
  },
  "company": {
    "businessId": "12345678",
    "taxId": "2023456789",
    "vatId": "SK2023456789"
  }
}

Response:

json
{
  "data": {
    "url": "https://checkout.stripe.com/c/pay/cs_test_a1..."
  }
}

Step 2: Complete Payment on Stripe ​

  1. Redirect User - Redirect the client to the url returned in Step 1
  2. Stripe Checkout - Client completes payment on Stripe's secure page. Checkout accepts cards only (Apple Pay and Google Pay included), so a completed payment is confirmed at once
  3. Stripe Redirect - After payment (or cancellation) Stripe redirects the client to the success or cancel page of the app (FRONTEND_URL plus /posudky/platba/success or /posudky/platba/cancel on the backend). The backend appends testimonyId, offerId and sessionId to both, so your page receives the offer and the Stripe session id as query parameters

Example Redirect URLs:

Success: https://your-app.com/posudky/platba/success?testimonyId=01J...&offerId=01J...&sessionId=cs_test_a1...
Cancel:  https://your-app.com/posudky/platba/cancel?testimonyId=01J...&offerId=01J...&sessionId=cs_test_a1...

Calling Checkout Offer again for the same testimony returns a new URL and expires the previous, still-open Stripe session — always send the client to the URL from the latest response.

Step 3: Confirm Payment ​

Endpoint: Accept Offer

http
POST /api/v1/testimonies/offers/{offer}/accept

Required Data:

  • {offer} - The offerId query parameter of the success page
  • sessionId - The sessionId query parameter of the success page

Request Example:

json
{
  "sessionId": "cs_test_a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8s9T0"
}

Response:

204 No Content

Webhook race

The backend also accepts the offer when Stripe's checkout.session.completed webhook arrives, which can happen before the client reaches your success page. Confirming the same paid session again is then a no-op 204; 409 Conflict with Pre tento posudok už bola prijatá ponuka. is answered only for a different paid session of an already accepted testimony. Confirm with Step 4.

Step 4: Verify Acceptance ​

After successful payment confirmation, the testimony transitions to accepted state.

Verify State: Show Testimony

http
GET /api/v1/testimonies/{testimonyId}

Check for:

  • state should be "accepted"
  • acceptedOffer should contain the offer details
  • expert should be populated, now including the expert's email and phone
  • acceptedAt should be set
  • invoices lists the platform invoice and the expert's invoice once they have been generated (an empty array until then) — fetch each PDF with Download Invoice

State Transitions ​

The payment flow triggers the following state transitions:

pending → offered → accepted

See Testimony Workflow for complete state transition diagram.

Commission Calculation ​

The platform commission is added on top of what the expert asks for — the expert is paid exactly the amount they offered:

  • expertAmount - Amount set by the expert; this is what the expert is paid. Returned only to the expert who made the offer
  • price - expertAmount plus the commission; this is what the client sees and pays

The commission percentage and amount are not exposed as offer fields. The commission is configured on the backend (21% of the expert's amount by default) and fixed when the offer is created; its amount appears as the amount of the client's platform Invoice, and the expert's payout as the amount of the expert invoice.

Example:

Expert Amount (expert invoice):       €500
Commission (platform invoice, 21%):   €105
Price (client pays):                  €605

See Offer Object for field details.

Error Handling ​

Checkout Errors ​

If checkout initiation fails:

422 Unprocessable Content

json
{
  "message": "Telefónne číslo už existuje.",
  "errors": {
    "phone": [
      "Telefónne číslo už existuje."
    ]
  }
}

Common Issues:

  • Phone number used by another user
  • Invalid address data (line2 must be a non-empty string)
  • Invalid country code
  • firstName / lastName containing characters other than letters, spaces and ' ’ . , -

409 Conflict with a plain message (no errors object):

  • Platbu je možné začať len pri posudku s aktívnou ponukou. — the testimony is no longer offered
  • Táto ponuka už nie je dostupná. — the offer was withdrawn by its expert, or the expert is not approved or is suspended
  • Tento znalec momentálne nemôže prijímať platby. Vyberte inú ponuku alebo to skúste neskôr. — the expert's Stripe account cannot receive payments; offer the client another offer
  • Pre váš účet sa ešte pripravuje iná platba. Skúste to o chvíľu znova. — a concurrent checkout of the same client; retry in a moment

422 Unprocessable Content with a plain message — Pri spracovaní platby nastala chyba. Skúste to znova. (Stripe rejected the request)

502 Bad Gateway — the same message when Stripe is unreachable, rate-limiting or failing; retry later

403 Forbidden — the offer's testimony belongs to another client, or the email is not verified. 404 Not Found — unknown offer ID.

429 Too Many Requests — more than 3 checkout attempts per minute.

500 Internal Server Error

json
{
  "message": "An unexpected error occurred."
}

Payment Confirmation Errors ​

If payment confirmation fails:

422 Unprocessable Content

json
{
  "message": "Platba ešte nebola dokončená."
}

(A validation error with an errors object is returned when sessionId is missing or does not start with cs_.)

403 Forbidden — the offer's testimony belongs to another client (This action is unauthorized.; in production the generic Forbidden). 404 Not Found — unknown offer ID.

409 Conflict — one of:

  • Pre tento posudok už bola prijatá ponuka. — another session already won this testimony; verify with Step 4 (re-confirming the session the webhook already accepted is a no-op 204)
  • Platba nepatrí k tejto ponuke. — the session was paid for a different offer than the one in the URL
  • Táto ponuka už nie je dostupná. — the offer was withdrawn, its expert can no longer be booked, or the session's payment was already refunded
  • Prechod zo stavu „Zrušený“ do stavu „Prijatý“ nie je možný. — the testimony left the offered state
  • Záznam bol medzitým zmenený. Skúste to znova.

A paid session that can no longer be accepted (the testimony was cancelled or another offer won, or the offer became unavailable — for example because its expert was suspended while the client was paying) is refunded automatically when Stripe's checkout.session.completed webhook is processed. An expert cannot withdraw an offer from under a payment: the open session is expired first, and an offer already paid for stays.

422 Unprocessable Content — Pri spracovaní platby nastala chyba. Skúste to znova. (Stripe rejected the request, e.g. an unknown session id)

502 Bad Gateway — the same message when Stripe is unreachable, rate-limiting or failing; retry later

See Accept Offer for details.

Security Notes ​

Security Best Practices

  • All payment processing is handled by Stripe's PCI-compliant infrastructure
  • No credit card data is stored in the application
  • A paid session is accepted only for the offer it was created for, and only by the client who owns the testimony; confirming it again is a no-op
  • A refunded session can never be accepted

Testing ​

Testing Payments

For testing the payment flow:

  1. Use Stripe test mode credentials
  2. Use test card numbers from Stripe Testing Docs
  3. Common test cards:
    • Success: 4242 4242 4242 4242
    • Decline: 4000 0000 0000 0002

See Email Testing for viewing payment notification emails.

Integration Example ​

Frontend Flow (Pseudocode) ​

javascript
// Step 1: Initiate checkout
async function initiateCheckout(offerId, checkoutData) {
  const response = await fetch(`/api/v1/testimonies/offers/${offerId}/checkout`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(checkoutData)
  });

  const { data } = await response.json();

  // Step 2: Redirect to Stripe
  window.location.href = data.url;
}

// Step 3: Handle Stripe redirect (on your success page)
async function handlePaymentSuccess() {
  const urlParams = new URLSearchParams(window.location.search);
  const testimonyId = urlParams.get('testimonyId');
  const offerId = urlParams.get('offerId');
  const sessionId = urlParams.get('sessionId');

  if (!offerId || !sessionId) {
    throw new Error('No offer or session ID found');
  }

  // Confirm payment
  const response = await fetch(`/api/v1/testimonies/offers/${offerId}/accept`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ sessionId })
  });

  // 204 = accepted, either by this call or already by the Stripe webhook
  if (!response.ok) {
    throw new Error('Payment confirmation failed');
  }

  // Redirect to testimony details
  window.location.href = `/testimonies/${testimonyId}`;
}