# 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.

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](https://app.briqpay.com), 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.

```sequence title="A payment from start to finish"
lanes: Customer, Your page, Your backend, Briqpay, Payment provider
Your backend -> Briqpay: Create session with the cart and customer
Briqpay --> Your backend: sessionId and htmlSnippet
Your backend -> Your page: Show the htmlSnippet
Customer -> Briqpay: Picks a payment method and clicks pay
Briqpay -> Your page: make_decision event
Your page -> Your backend: Ask for a decision
Your backend -> Briqpay: Make decision: allow
Your page -> Briqpay: resumeDecision()
Briqpay -> Payment provider: Authorize the payment
Payment provider --> Briqpay: Authorized
Briqpay -> Your page: Redirect to your confirmation page
Briqpay -> Your backend: order_status webhook
Your backend -> Briqpay: Capture when you ship
note: 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](https://app.briqpay.com). [Authentication](https://developer.briqpay.com/docs/authentication.md) has the details.

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

```http title="Authentication"
Authorization: Basic <base64(merchantId:secret)>
```

| Environment | Base URL                             |
| ----------- | ------------------------------------ |
| Playground  | `https://playground-api.briqpay.com` |
| Production  | `https://api.briqpay.com`            |

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

> [!NOTE]
> For narrower access, [Generate a secret](https://developer.briqpay.com/api-reference/generate-a-secret.md) gives you short-lived secrets limited to one session or to certain operations. They last one day by default and up to seven days.

## 1. Create a session

Call [Create session](https://developer.briqpay.com/api-reference/create-session.md) from your backend when the customer reaches the checkout. Never call the API from the browser: the request carries your secret.

```bash title="cURL"
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.

> [!IMPORTANT]
> The payment step stays locked until the session has the customer's billing details and billing address, and a shipping address unless shipping isn't required. For business customers it also needs the company's details. Send them when you create the session.

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](https://developer.briqpay.com/docs/prefill-data.md).

Also set `references.reference1` to your order number (see [References](#references)) and turn on the decision flow (see [step 4](#4-approve-the-purchase)).

## 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:

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

The [JS SDK](https://developer.briqpay.com/docs/sdk.md) 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](https://developer.briqpay.com/api-reference/update-session.md) 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.

```sequence title="Updating the session when the cart changes"
lanes: Customer, Your page, Your backend, Briqpay
Customer -> Your page: Changes the cart or shipping
Your page -> Briqpay: suspend()
Your page -> Your backend: Send the new cart
Your backend -> Briqpay: Update session with the complete order
Your page -> Briqpay: resume(), always, even if the update failed
```

```js title="Frontend"
// 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()
  }
}
```

```http title="Backend"
PATCH /v3/session/{sessionId}
Authorization: Basic <base64(merchantId:secret)>
Content-Type: application/json

{
  "data": {
    "order": {
      "currency": "SEK",
      "amountIncVat": 205000,
      "amountExVat": 164000,
      "cart": [ ... the complete cart ... ]
    }
  }
}
```

To change references, the terms URL or the redirect URL, for example once your final order number exists, use [Update metadata](https://developer.briqpay.com/api-reference/update-metadata.md) 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](#6-capture-cancel-and-refund).

## 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](https://developer.briqpay.com/api-reference/read-session.md) to get the final cart and customer details.
3. Your backend sends its answer with [Make decision](https://developer.briqpay.com/api-reference/make-decision.md). It answers `204`.
4. Your page calls `window._briqpay.v3.resumeDecision()`, and the payment goes ahead or the customer sees your message.

```sequence title="The decision flow"
lanes: Customer, Your page, Your backend, Briqpay
Customer -> Briqpay: Clicks pay
Briqpay -> Your page: make_decision event
Your page -> Your backend: Check this order
Your backend -> Briqpay: Read session
Briqpay --> Your backend: Final cart and customer
Your backend -> Briqpay: Make decision: allow or reject
Your page -> Briqpay: resumeDecision()
Briqpay -> Customer: The payment goes ahead, or your message
note: Briqpay waits 20 seconds for your decision. After that, the customer sees a general error.
```

```js title="Frontend"
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](https://developer.briqpay.com/api-reference/make-decision.md) carries one of these bodies:

```json title="Allow"
{ "decision": "allow" }
```

```json title="Reject with a message"
{
  "decision": "reject",
  "rejectionType": "notify_user",
  "softErrors": [{ "message": "An item is no longer in stock" }]
}
```

```json title="Reject and close the session"
{
  "decision": "reject",
  "rejectionType": "reject_session_with_error",
  "hardError": { "message": "This order can no longer be completed." }
}
```

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://...)`.

> [!WARNING]
> The iFrame waits 20 seconds for your decision. If no decision arrives in time, the customer sees a general "please try again" error. Keep the check fast.

## 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:

| Status                        | What to do                                                                          |
| ----------------------------- | ----------------------------------------------------------------------------------- |
| `order_pending`               | Create the order as pending and wait. Most orders leave this status within minutes. |
| `order_approved_not_captured` | The payment is authorized. Place the order.                                         |
| `order_rejected`              | The payment failed. Don't ship.                                                     |
| `order_cancelled`             | The order was cancelled.                                                            |

The `order_status` webhook (and [Read session](https://developer.briqpay.com/api-reference/read-session.md)) 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.

```sequence title="Capturing an order"
lanes: Your backend, Briqpay, Payment provider
Your backend -> Briqpay: Capture an order
Briqpay -> Payment provider: Capture
Payment provider --> Briqpay: Approved, rejected or pending
Briqpay --> Your backend: The capture and its status, or an error
Briqpay -> Your backend: capture_status webhook, with the final result if it was pending
```

| Action  | Endpoint                                            | When                                                                                                                                              |
| ------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| Capture | [Capture an order](https://developer.briqpay.com/api-reference/capture-an-order.md) | When you ship. Depending on the payment method, you can capture part of the order and the rest later.                                             |
| Cancel  | [Cancel an order](https://developer.briqpay.com/api-reference/cancel-an-order.md)   | Only before anything is captured. After a capture, refund instead.                                                                                |
| Refund  | [Refund a capture](https://developer.briqpay.com/api-reference/refund-a-capture.md) | After 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](https://developer.briqpay.com/docs/order-lines.md#lines-for-refunds) has an example of each.

> [!IMPORTANT]
> What you can capture depends on the payment method the customer used. Many allow partial captures, but some only allow capturing the whole order at once, and for some no capture is needed at all. Your order handling should work in all three cases, since the payment methods you offer can change without any change in your code.

- **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.

> [!NOTE]
> An authorization doesn't last forever, and how long it lasts depends on the payment provider. When a payment provider reports that an authorization has expired, the order is cancelled and you get the `order_status` webhook with `order_cancelled`. If the provider hasn't reported it, you find out when a capture fails with `AUTHORIZATION_EXPIRED`. Capture soon after you ship.

Also available:

- [Release remaining order amount](https://developer.briqpay.com/api-reference/release-remaining-order-amount.md), 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](https://developer.briqpay.com/api-reference/update-cart.md), to change the cart after the purchase. The new cart must still contain everything already captured.
- [Update references](https://developer.briqpay.com/api-reference/update-references.md), 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 code                | Meaning                                                                             |
| ------------------------- | ----------------------------------------------------------------------------------- |
| `ORDER_NOT_COMPLETED`     | The session isn't completed yet.                                                    |
| `ORDER_PENDING`           | The order is still pending. Wait for `order_approved_not_captured`.                 |
| `ORDER_REJECTED`          | The payment provider rejected the order.                                            |
| `ORDER_ALREADY_CANCELLED` | The order is cancelled, or the cancel is still pending.                             |
| `AUTHORIZATION_EXPIRED`   | The authorization has expired.                                                      |
| `OPERATION_NOT_SUPPORTED` | The 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](https://developer.briqpay.com/docs/order-lines.md) describes each type.

> [!WARNING]
> Some payment providers reject an order that is off by even a single minor unit. Calculate every line and total exactly, the same way each time, and check that the cart adds up before you send it.

## 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](https://developer.briqpay.com/api-reference/update-metadata.md). After it, use [Update references](https://developer.briqpay.com/api-reference/update-references.md).

## Webhooks

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

| Event            | Statuses                                                                                                             |
| ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `order_status`   | `order_pending`, `order_approved_not_captured`, `order_rejected`, `order_cancelled`, `captured_partial_and_released` |
| `capture_status` | `pending`, `approved`, `rejected`                                                                                    |
| `refund_status`  | `pending`, `approved`, `rejected`                                                                                    |
| `session_status` | `completed` (mainly for sign-ups)                                                                                    |

> [!IMPORTANT]
> List every status you want in `statuses`. A webhook is only sent for the statuses listed. For `order_status` and `session_status`, a hook without `statuses` is rejected when you create the session. For `capture_status` and `refund_status`, it is accepted but never fires.

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](https://developer.briqpay.com/api-reference/outgoing-webhooks.md) 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:

```js title="Node.js"
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.
