Skip to content
Developers

Search the guides, the API reference and the changelog.

Payment Module

Add Briqpay's payment step to your own checkout. Your backend creates a session, your page shows it, and Briqpay handles every payment method behind it.

On this page

With the Payment Module, Briqpay is the payment step inside the checkout you already have. You keep your own cart, address forms and order handling. Briqpay shows the payment methods, talks to the payment providers and tells you the result.

Payment methods are switched on in the Merchant Portal, not in your code. Once the integration on this page is done, adding a new payment method needs no changes on your side.

How it works

  1. Your backend creates a session with the cart, the customer's details, your references and the webhooks you want.
  2. Your page shows the payment step. The session comes with an HTML snippet that embeds Briqpay's iFrame.
  3. You keep the session in sync. If the cart or shipping changes, you update the session and refresh the iFrame.
  4. You approve the purchase. When the customer clicks pay, Briqpay asks you for a final decision (stock, price, permissions).
  5. The order is confirmed. The customer is redirected to your confirmation page, and a webhook tells your backend the order's status.
  6. You capture, cancel or refund through the API when you ship, cancel or take a return.
A payment from start to finish
  1. Your backend to BriqpayCreate session with the cart and customer
  2. Briqpay to Your backendsessionId and htmlSnippet
  3. Your backend to Your pageShow the htmlSnippet
  4. Customer to BriqpayPicks a payment method and clicks pay
  5. Briqpay to Your pagemake_decision event
  6. Your page to Your backendAsk for a decision
  7. Your backend to BriqpayMake decision: allow
  8. Your page to BriqpayresumeDecision()
  9. Briqpay to Payment providerAuthorize the payment
  10. Payment provider to BriqpayAuthorized
  11. Briqpay to Your pageRedirect to your confirmation page
  12. Briqpay to Your backendorder_status webhook
  13. Your backend to BriqpayCapture when you ship
  14. Steps 5 to 8 happen only with the decision flow turned on, which we recommend. Section 4 shows it in full.

Before you start

You need API credentials for the playground. Get them by registering in the Merchant Portal. Authentication has the details.

Every request uses HTTP Basic authentication, with your merchant ID as the username and your secret as the password:

Authorization: Basic <base64(merchantId:secret)>
EnvironmentBase URL
Playgroundhttps://playground-api.briqpay.com
Productionhttps://api.briqpay.com

Send Content-Type: application/json on every request except GET, including requests without a body, such as cancelling an order.

1. Create a session

Call Create session from your backend when the customer reaches the checkout. Never call the API from the browser: the request carries your secret.

curl -X POST 'https://playground-api.briqpay.com/v3/session' \
  -H 'Authorization: Basic <base64(merchantId:secret)>' \
  -H 'Content-Type: application/json' \
  -d '{
  "product": { "type": "payment", "intent": "payment_one_time" },
  "customerType": "consumer",
  "country": "SE",
  "locale": "sv-se",
  "urls": {
    "terms": "https://example.com/terms",
    "redirect": "https://example.com/confirmation"
  },
  "references": { "reference1": "ORDER-1234" },
  "modules": {
    "loadModules": ["payment"],
    "config": { "payment": { "decision": { "enabled": true } } }
  },
  "hooks": [
    {
      "eventType": "order_status",
      "statuses": ["order_pending", "order_approved_not_captured", "order_rejected", "order_cancelled"],
      "method": "POST",
      "url": "https://example.com/webhooks/briqpay"
    }
  ],
  "data": {
    "order": {
      "currency": "SEK",
      "amountIncVat": 105000,
      "amountExVat": 84000,
      "cart": [
        {
          "productType": "physical",
          "reference": "SKU-001",
          "name": "Desk lamp",
          "quantity": 1,
          "quantityUnit": "pc",
          "unitPrice": 80000,
          "taxRate": 2500,
          "discountPercentage": 0
        },
        {
          "productType": "shipping_fee",
          "reference": "SHIPPING",
          "name": "Home delivery",
          "quantity": 1,
          "quantityUnit": "pc",
          "unitPrice": 4000,
          "taxRate": 2500,
          "discountPercentage": 0
        }
      ]
    },
    "billing": {
      "firstName": "Anna",
      "lastName": "Andersson",
      "email": "anna@example.com",
      "phoneNumber": "+46701234567",
      "streetAddress": "Storgatan 1",
      "zip": "11122",
      "city": "Stockholm",
      "country": "SE"
    },
    "shipping": {
      "firstName": "Anna",
      "lastName": "Andersson",
      "email": "anna@example.com",
      "phoneNumber": "+46701234567",
      "streetAddress": "Storgatan 1",
      "zip": "11122",
      "city": "Stockholm",
      "country": "SE"
    }
  }
}'

The response (201) is the full session. You need three of its fields:

  • sessionId: store it with your order. You need it for updates, decisions and order management.
  • htmlSnippet: the HTML that shows the payment step on your page.
  • clientToken: an alternative to the snippet, for loading the iFrame with the JS SDK yourself.

The example above sets modules.loadModules to ["payment"]. This is the Payment Module setup: you collect the customer's details yourself, and Briqpay only handles the payment. If you leave loadModules out, Briqpay loads the modules set up for your checkout. For business customers that can include Briqpay's own company, billing and shipping steps. The other values are company_lookup, billing, shipping, upsell, cross_border, order_note, custom_form and terms. To send details you already have, see Prefill data.

Also set references.reference1 to your order number (see References) and turn on the decision flow (see step 4).

2. Show the payment step

Put the htmlSnippet where the payment step belongs on your checkout page. Give it at least 640 pixels of width on desktop, and as much width as possible on mobile. By default the payment step is at most 640 pixels wide. For a wider checkout, raise the maximum in the Merchant Portal, up to 1280 pixels.

The snippet also loads Briqpay's JS SDK. If you insert the snippet with JavaScript instead of in your server-rendered HTML, add the SDK to your page's <head> yourself:

<script async src="https://api.briqpay.com/briq.min.js" id="briq-sdk"></script>

The JS SDK guide covers everything the SDK can do.

3. Keep the session in sync

If the customer changes the cart, the shipping method or a discount code, update the session so they never pay for an outdated cart:

  1. Suspend the iFrame with window._briqpay.v3.suspend(). The customer can't pay while it's suspended.
  2. Your backend calls Update session with the complete updated order and recalculated amounts. The new order replaces the old one.
  3. Resume the iFrame with window._briqpay.v3.resume(). This loads the new data into it and unlocks it.
Updating the session when the cart changes
  1. Customer to Your pageChanges the cart or shipping
  2. Your page to Briqpaysuspend()
  3. Your page to Your backendSend the new cart
  4. Your backend to BriqpayUpdate session with the complete order
  5. Your page to Briqpayresume(), always, even if the update failed
// Customer changed the cart
async function onCartChanged(cart) {
  window._briqpay.v3.suspend()
  try {
    // Your backend calls PATCH /v3/session/{sessionId}
    await fetch('/api/checkout/update', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(cart),
    })
  } finally {
    // Always resume, even if the update failed
    window._briqpay.v3.resume()
  }
}

To change references, the terms URL or the redirect URL, for example once your final order number exists, use Update metadata instead.

You can also change the customer's details with the same call, in data.billing, data.shipping and data.company. Send only the object you want to change, with the same fields as when you created the session. This works only if the matching Briqpay module is not part of the session, and only until the purchase is complete.

What you can't update:

  • Billing, shipping or company details, if the session includes Briqpay's own billing, shipping or company lookup step. Send them when you create the session.
  • Which modules are loaded, and the payment method rules. Create a new session instead.
  • The order of a completed session. After the purchase, use order management.

4. Approve the purchase

The decision flow gives you a last check before the payment is authorized: is the item still in stock, is the price still right, may this customer buy it. We recommend it for every integration.

Turn it on when you create the session, with modules.config.payment.decision.enabled: true. Then:

  1. The customer clicks pay. The iFrame waits, and the JS SDK fires a make_decision event on your page.
  2. Your backend checks the order. Use Read session to get the final cart and customer details.
  3. Your backend sends its answer with Make decision. It answers 204.
  4. Your page calls window._briqpay.v3.resumeDecision(), and the payment goes ahead or the customer sees your message.
The decision flow
  1. Customer to BriqpayClicks pay
  2. Briqpay to Your pagemake_decision event
  3. Your page to Your backendCheck this order
  4. Your backend to BriqpayRead session
  5. Briqpay to Your backendFinal cart and customer
  6. Your backend to BriqpayMake decision: allow or reject
  7. Your page to BriqpayresumeDecision()
  8. Briqpay to CustomerThe payment goes ahead, or your message
  9. Briqpay waits 20 seconds for your decision. After that, the customer sees a general error.
window._briqpay.subscribe('make_decision', async function () {
  // Your backend validates the session and calls POST /decision
  await fetch('/api/checkout/decision', { method: 'POST' })
  window._briqpay.v3.resumeDecision()
})

Your backend's request to Make decision carries one of these bodies:

{ "decision": "allow" }

A rejection always needs a rejectionType. With notify_user the customer sees your messages and can try again; with reject_session_with_error the session closes. Messages can be up to 256 characters, with up to 10 softErrors, and can contain links written as [text](https://...).

5. Handle the completed order

When the purchase goes through, the customer is redirected to your urls.redirect, and Briqpay sends the order_status webhook, normally within about a minute.

Don't treat the redirect as proof of payment. Use the webhook:

StatusWhat to do
order_pendingCreate the order as pending and wait. Most orders leave this status within minutes.
order_approved_not_capturedThe payment is authorized. Place the order.
order_rejectedThe payment failed. Don't ship.
order_cancelledThe order was cancelled.

The order_status webhook (and Read session) also tells you how the customer paid, in the transaction object:

  • reservationId: the payment provider's main reference. Use it for reconciliation.
  • pspDisplayName: the payment method's name as the customer saw it, for example "Card". Use it in your order confirmation.
  • secondaryReservationId, pspId, pspIntegrationName: further references, not available for every provider.

Some providers also send a pspMetadata object, with for example the card type or the payer's name. Its fields depend on the provider, so always check for missing values.

6. Capture, cancel and refund

After the purchase, you manage the order through the API. Most calls give you the result straight away in the response, and Briqpay sends the matching webhook too. When the payment provider confirms later, the response says pending and the final result comes in the webhook.

Capturing an order
  1. Your backend to BriqpayCapture an order
  2. Briqpay to Payment providerCapture
  3. Payment provider to BriqpayApproved, rejected or pending
  4. Briqpay to Your backendThe capture and its status, or an error
  5. Briqpay to Your backendcapture_status webhook, with the final result if it was pending
ActionEndpointWhen
CaptureCapture an orderWhen you ship. Depending on the payment method, you can capture part of the order and the rest later.
CancelCancel an orderOnly before anything is captured. After a capture, refund instead.
RefundRefund a captureAfter a capture. A refund belongs to one capture: if the order has several captures, you must include the captureId, or the refund is rejected.

Capture and refund take a data.order in the same format as creating a session, including amountExVat. To capture or refund part of an order, send only those lines.

Two kinds of line exist only for refunds, and Briqpay doesn't compare them with the captured cart:

  • surcharge with a negative unitPrice keeps a fee out of the refund, for example a return fee. Send it as an extra line next to the returned items.
  • adjustment refunds an amount that isn't an item, for example a goodwill refund for a damaged product.

Order line types has an example of each.

  • Capture and refund answer 201 with the capture or refund, including its status: pending, approved or rejected. If it's pending, the final result comes in the capture_status or refund_status webhook. If the provider refuses, you get an error response and a rejected webhook.
  • Cancel answers 204 when the provider confirms right away, or 202 with {"status": "cancel_pending"} when it confirms later. The order_status webhook then tells you when the order is cancelled.

Also available:

  • Release remaining order amount, after a partial capture, to release the rest of the authorization. It takes no body and answers 204. The order then gets the status captured_partial_and_released, and an order_status webhook is sent if you listed that status.
  • Update cart, to change the cart after the purchase. The new cart must still contain everything already captured.
  • Update references, to change your references after the purchase.

Release remaining works only when the session is completed, the order is captured_partial, and the order has at least one capture. Otherwise it answers 400 with one of these error codes:

Error codeMeaning
ORDER_NOT_COMPLETEDThe session isn't completed yet.
ORDER_PENDINGThe order is still pending. Wait for order_approved_not_captured.
ORDER_REJECTEDThe payment provider rejected the order.
ORDER_ALREADY_CANCELLEDThe order is cancelled, or the cancel is still pending.
AUTHORIZATION_EXPIREDThe authorization has expired.
OPERATION_NOT_SUPPORTEDThe order has no captures, or isn't captured_partial, for example fully captured.

Amounts and the cart

  • Amounts are whole numbers in minor units, such as öre or cents. 1,000.00 SEK is 100000.
  • Tax rates are the percentage times 100. 25% is 2500.
  • The order total must match the sum of the cart lines. Briqpay tolerates a small rounding difference, but don't rely on it: payment providers can be stricter.
  • Currency is a three-letter code, such as SEK, EUR or NOK.
  • Everything is a cart line. Shipping, discounts and fees go in the cart as their own lines, with productType shipping_fee, discount or surcharge. Never put them only in the total. The other types are physical, digital, deposit, gift_card and, for the US only, sales_tax. Order line types describes each type.

References

Set references.reference1 to your own order number on every session. Briqpay passes it to the payment provider as your merchant reference, so you can match a payment in the provider's portal and reports to your order. Exactly how it shows up depends on the provider.

You can add your own keys too, such as orderId or customerId, for your internal tracking. You can have up to 10 references. Keys can be up to 128 characters and values up to 512. Each cart line also has its own reference, such as the SKU. Don't name a key event, status or sessionId: in a webhook it would replace the field of that name.

Before the purchase, change references with Update metadata. After it, use Update references.

Webhooks

Choose which events you want in the hooks array when you create the session.

EventStatuses
order_statusorder_pending, order_approved_not_captured, order_rejected, order_cancelled, captured_partial_and_released
capture_statuspending, approved, rejected
refund_statuspending, approved, rejected
session_statuscompleted (mainly for sign-ups)

Every webhook has event, status and sessionId, plus your references as top-level fields. With POST, order_status also carries the full transaction, capture_status the capture and its captureId, and refund_status the refund and its refundId. A rejected capture or refund carries an error instead. The Outgoing Webhooks reference has every payload field.

  • Expect duplicates. A webhook that doesn't get a 2xx response in time is sent again, up to 20 times, about two hours apart. Deduplicate on the event, the status and the ID: sessionId for order_status, captureId for capture_status, refundId for refund_status.
  • Answer right away. Return 2xx at once and do the work afterwards. A slow answer counts as a failed delivery.
  • Check that it came from Briqpay. Set a webhook secret in the Merchant Portal, and Briqpay signs every POST webhook. Without signing, read the session through the API to confirm what the webhook says.

With signing on, each webhook has an x-briq-signature header like t=1760342400000,s1=<signature>, and a timestamp field in the body. The signature is the Base64-encoded HMAC-SHA256 of <t>.<raw body>, keyed with your webhook secret:

import crypto from 'node:crypto'

// rawBody: the request body exactly as received, before JSON parsing
function isFromBriqpay(header, rawBody, webhookSecret) {
  // Split on the first "=" only: the Base64 signature can end in "="
  const parts = Object.fromEntries(
    header.split(',').map(p => [p.slice(0, p.indexOf('=')), p.slice(p.indexOf('=') + 1)])
  )
  const expected = Buffer.from(
    crypto.createHmac('sha256', webhookSecret).update(`${parts.t}.${rawBody}`).digest('base64')
  )
  const received = Buffer.from(parts.s1 ?? '')

  return received.length === expected.length && crypto.timingSafeEqual(received, expected)
}

Briqpay sets t each time it sends a webhook, including on a retry. To block replays, compare t with the current time and reject a webhook that is too old, for example more than 5 minutes.