# JS SDK

Briqpay's JS SDK connects your page to the checkout iFrame. Use it to pause and resume the iFrame, lock modules, and react to events such as address changes, decisions and a completed session.

The Briqpay JS SDK is a small script that connects your page to the checkout iFrame. It adjusts the height of the iFrame as its content changes, lets you control the iFrame from your page, and tells your page what the customer does. It lives on `window._briqpay`.

Every page that shows a Briqpay iFrame needs the SDK.

## Load the SDK

The `htmlSnippet` from [Create session](https://developer.briqpay.com/api-reference/create-session.md) and [Read session](https://developer.briqpay.com/api-reference/read-session.md) already contains the SDK script. If you put the snippet in your server-rendered HTML, you don't need to do anything.

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>
```

> [!NOTE]
> The snippet loads the SDK from the API you created the session with. Load it from the same environment: the Base URL table in [Payment Module](https://developer.briqpay.com/docs/payment-module.md) lists them.

### Wait for the iFrame

The SDK and the iFrame need a moment to connect. Pass a function to `window._briqpay.v3.onReady` and it runs once they are connected. Use it for anything you want to do as soon as the page loads, such as unlocking a module:

```js title="Frontend"
window._briqpay.v3.onReady(function () {
  // Replace with your own check
  const hasAllUserData = true;

  if (hasAllUserData) {
    window._briqpay.v3.unlockModule("payment");
  }
});
```

If you load the script yourself, call `onReady` in the script's `onload` handler, when `window._briqpay` exists. Register it early: a function passed after the iFrame has already connected only runs at the next change of module state.

## Control the iFrame

These functions live on `window._briqpay.v3`.

| Function                       | What it does                                                                        |
| ------------------------------ | ----------------------------------------------------------------------------------- |
| `suspend()`                    | Stops the customer from using the iFrame. The iFrame fades out and shows a spinner. |
| `resume()`                     | Loads the latest session data into the iFrame and makes it usable again. It doesn't change module locks. |
| `resumeDecision()`             | Tells the iFrame your decision is ready, so the payment can continue.               |
| `lockModule(name, stickyLock)` | Locks one module, for example `'payment'`.                                          |
| `unlockModule(name)`           | Unlocks one module.                                                                 |

The cart-update flow (`suspend`, update the session, `resume`) is in [Keep the session in sync](https://developer.briqpay.com/docs/payment-module.md#3-keep-the-session-in-sync). The decision flow, where you call `resumeDecision()` after [Make decision](https://developer.briqpay.com/api-reference/make-decision.md), is in [Approve the purchase](https://developer.briqpay.com/docs/payment-module.md#4-approve-the-purchase).

### Lock a module

`lockModule` takes the module name and a second argument, `stickyLock`. It decides where the lock is kept:

- `lockModule('payment', true)` is a sticky lock. Briqpay saves it on the session, so the module stays locked when the customer reloads the page.
- `lockModule('payment', false)`, or no second argument, locks the module on this page only. A reload removes the lock.

```js title="Frontend"
// Stays locked after a reload
window._briqpay.v3.lockModule("payment", true);

// Locked until the page reloads
window._briqpay.v3.lockModule("payment", false);

// Removes both kinds of lock
window._briqpay.v3.unlockModule("payment");
```

A locked module shows as `locked_by_merchant` in the `module_state` event. Locking and unlocking only work in a session that shows the payment step without Briqpay's own address or company steps, as in the [Payment Module](https://developer.briqpay.com/docs/payment-module.md) setup. A lock request is also ignored while the session is being completed.

> [!NOTE]
> The payment step also stays locked by itself until the session has the details it needs. See [Payment Module](https://developer.briqpay.com/docs/payment-module.md#1-create-a-session).

## Events

Listen to events from the iFrame with `subscribe`:

```js title="Frontend"
window._briqpay.subscribe("event name", function (data) {
  // Use data as you like
});
```

`window._briqpay.unsubscribe('event name')` removes all your listeners for that event.

| Event                     | Fires when                                                            | Payload                                                                                      |
| ------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `addressupdate`           | The customer saves a billing or shipping address.                     | `billingaddress` and `shippingaddress`, each with `zip` and `country`.                       |
| `companyUpdate`           | In a business checkout, the company is set, changed or cleared.       | `cin`, `country`, `companyName`, `manuallyEntered`.                                          |
| `billing_validate`        | The customer submits the billing address.                             | `zip`, `country`, `city`. You must answer: see Validate addresses below.    |
| `shipping_validate`       | The customer submits the shipping address.                            | `zip`, `country`, `city`. You must answer: see Validate addresses below.    |
| `module_state`            | The state of a module changes.                                        | An object with only the modules that changed, such as `{ "payment": "completed" }`.          |
| `before-purchase`         | The customer clicks pay and the decision flow starts.                 | `sessionid`                                                                                  |
| `make_decision`           | The same moment as `before-purchase`. Your cue to make a decision.    | `sessionId`, `sessionIntent`, `module`                                                       |
| `paymentProcessStarted`   | The payment starts.                                                   | `sessionId`, `pspId`, `pspDisplayName`                                                       |
| `paymentProcessCancelled` | A payment that had started doesn't go through.                        | None.                                                                                        |
| `session_complete`        | The session is completed.                                             | `sessionId`, `sessionIntent`                                                                 |
| `additionalFieldsUpdate`  | The customer changes a field in the payment step's additional fields. | `events`: a list of `{ key, value }`.                                                        |
| `upsellFieldsUpdate`      | The customer changes a field in the upsell module.                    | `events`: a list of `{ key, value }`.                                                        |

Use `make_decision` for the decision flow. Don't rely on `before-purchase`: it fires at the same time and only carries the session ID.

### Address updates

A common use is to offer other shipping methods when the shipping address changes. `addressupdate` gives you the country and postcode to calculate them. If the customer has no separate shipping address, `shippingaddress` has the billing postcode.

```js title="Frontend"
window._briqpay.subscribe("addressupdate", function (data) {
  console.log(data.shippingaddress.zip);
});
```

```json title="Payload"
{
  "billingaddress": { "zip": "12345", "country": "SE" },
  "shippingaddress": { "zip": "12345", "country": "SE" }
}
```

If your shipping options change, update the session like in [Keep the session in sync](https://developer.briqpay.com/docs/payment-module.md#3-keep-the-session-in-sync).

### Company updates

In a business checkout, `companyUpdate` fires when the buyer's company is set, changed or cleared. Use it to check the company's VAT number before the purchase, for example. The checkout doesn't wait for your page to answer.

```js title="Frontend"
window._briqpay.subscribe("companyUpdate", function (data) {
  console.log(data.cin, data.companyName);
});
```

```json title="Payload"
{
  "cin": "5560000001",
  "country": "SE",
  "companyName": "Test AB",
  "manuallyEntered": false
}
```

- `cin`: the company identification number, in the same format as `company.cin` on the session.
- `country`: the session country.
- `companyName`: the company name.
- `manuallyEntered`: `true` if the buyer typed the company in instead of picking it from the lookup.

When the company is cleared, `cin`, `companyName` and `manuallyEntered` are `null`.

### Validate addresses

To check an address on your side, subscribe to `billing_validate` or `shipping_validate`. They carry the same data. Answer with `billingValidate` or `shippingValidate`:

```js title="Frontend"
window._briqpay.subscribe("billing_validate", function (data) {
  const isValid = data.zip.length === 5; // Replace with your own check
  window._briqpay.v3.billingValidate(isValid);
});

window._briqpay.subscribe("shipping_validate", function (data) {
  const isValid = data.zip.length === 5;
  window._briqpay.v3.shippingValidate(isValid);
});
```

```json title="Payload"
{ "zip": "12345", "country": "SE", "city": "The test city" }
```

With `true`, the checkout saves the address. With `false`, it shows an error and doesn't save it.

> [!WARNING]
> The checkout waits 3 seconds for your answer. After that, it treats the address as valid and continues. Answer quickly, and don't depend on a slow request to reject an address.

If you don't subscribe to an event, the SDK answers `true` for you. If you subscribe and later call `unsubscribe` for it, nothing answers any more, and each address waits the full 3 seconds.

### Module state

`module_state` fires when a module changes state, for example when you lock the payment module or the customer completes it. The payload holds only the modules that changed, with their new state:

```js title="Frontend"
window._briqpay.subscribe("module_state", function (data) {
  console.log(data);
});
```

```json title="Payload when you lock the payment module"
{ "payment": "locked_by_merchant" }
```

```json title="Payload when the payment module is completed"
{ "payment": "completed" }
```

The states are `locked_by_merchant`, `hidden`, `not_yet_reached`, `not_yet_reached_locked`, `empty_cart_locked`, `visible`, `visible_optional`, `visible_required` and `completed`.

### Session complete

`session_complete` fires when the session is completed. By default, the customer is then redirected to your `urls.redirect`, and your code may not get time to run. To handle the end of the session on your page, set `config.disableSessionCompleteRedirect` to `true` when you create the session. Briqpay then doesn't redirect, and you do it yourself or hide the iFrame:

```js title="Frontend"
window._briqpay.subscribe("session_complete", function (data) {
  // data.sessionId, data.sessionIntent
  window.location.href = "/confirmation";
});
```

> [!IMPORTANT]
> A completed session is not proof of payment. Use the `order_status` webhook, as described in [Payment Module](https://developer.briqpay.com/docs/payment-module.md#5-handle-the-completed-order).
