> ## Documentation Index
> Fetch the complete documentation index at: https://dev.moonpay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Buy Button

> Details on working with the Buy Button frame, which renders the Apple Pay, Google Pay, or card button for a quote and runs the purchase, or runs it headless behind your own button.

The Buy Button frame takes a quote signature to payment. It renders the button
that matches the payment method in the quote: Apple Pay, Google Pay, or a saved
card. When the customer taps it, it opens the native Apple Pay or Google Pay
sheet, or goes straight to the purchase for a card. Behind the button, it
evaluates transaction requirements, creates the transaction, and completes
post-transaction processing.

Pass `headless=true` to run the same purchase with no button. The frame renders
nothing and starts the purchase as soon as it loads, so your confirmation
screen, loading states, and purchase button stay fully under your control. Use
[headless mode](#headless-mode) for card and bank transfer quotes when you draw
your own button.

> [!NOTE]
>
> The Buy Button frame replaces the Apple Pay, Google Pay, and Buy frames. If
> you load `/platform/v1/apple-pay` or `/platform/v1/google-pay`, MoonPay serves
> this frame. If you load `/platform/v1/buy`, MoonPay serves this frame in
> headless mode. Existing integrations keep working, and the events below apply
> to them.

For platform-specific walkthroughs, see [manual integration](https://dev.moonpay.com/platform/guides/manual-integration/overview.md): [Web](https://dev.moonpay.com/platform/guides/manual-integration/web.md#buy-button-frame), [React Native](https://dev.moonpay.com/platform/guides/manual-integration/react-native.md#buy-button-frame), [Flutter](https://dev.moonpay.com/platform/guides/manual-integration/flutter.md#buy-button-frame), [iOS](https://dev.moonpay.com/platform/guides/manual-integration/ios.md#buy-button-frame), and [Android](https://dev.moonpay.com/platform/guides/manual-integration/android.md#buy-button-frame).

## URL

```
https://platform.moonpay.com/platform/v1/buy-button
```

## Payment methods

The quote's `paymentMethod.type` decides which mode to use. Card works in both
modes. SEPA bank transfer has no button to tap, so it runs in headless mode.
Apple Pay and Google Pay open a payment sheet from the customer's tap, so they
run with the button.

| Payment method | With the button (default) | Headless (`headless=true`) |
| - | - | - |
| `card` (a saved card) | ✅ Renders the card button and creates the transaction on tap | ✅ Creates the transaction on load |
| `sepa` (bank transfer, EUR) | Use headless mode | ✅ Creates the transaction on load. You then fetch the bank details and show them to the customer. See [Bank transfer](#bank-transfer) |
| `apple_pay` | ✅ Renders the Apple Pay button and opens the Apple Pay sheet | Use the button |
| `google_pay` | ✅ Renders the Google Pay button and opens the Google Pay sheet | Use the button |

If the quote's payment method doesn't run in the mode you load, the frame sends
[`error`](#error) with `unsupportedPaymentMethod`. Guest checkout runs with the
button only. Card and bank transfer quotes need a connected customer, not a
guest. See [Pay with card](https://dev.moonpay.com/platform/guides/pay-with-card.md) and [Pay with bank
transfer](https://dev.moonpay.com/platform/guides/pay-with-bank-transfer.md).

## Requirements

### Size

With the button, the frame container **height must be 44px**. Width is
flexible; the button inside the frame uses 100% of the container width. If you
set a custom `height` through
[`applePayButtonSettings`](#apple-pay-button-settings) or
[`googlePayButtonSettings`](#google-pay-button-settings), size the frame
container to match.

In [headless mode](#headless-mode), the frame renders nothing. Mount it with
zero dimensions so it does not affect your layout:

```html Example theme={null}
<iframe
  src="https://platform.moonpay.com/platform/v1/buy-button?headless=true&..."
  style="position: absolute; width: 0; height: 0; border: none; overflow: hidden;"
/>
```

### Permissions

The `payment` [permission policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Permissions-Policy#iframes) is required for Apple Pay and Google Pay. If you use the MoonPay web SDK to render the frame, it sets this for you; the guidance below applies to manual integrations, where you build the iframe yourself.

```tsx Example theme={null}
<iframe
  src="https://platform.moonpay.com/platform/v1/buy-button"
  allow="payment"
/>
```

In [test mode](https://dev.moonpay.com/platform/overview/test-mode.md), the frame simulates the wallet
payment with a JavaScript `window.prompt` dialog, for both Apple Pay and Google
Pay. If your iframe uses the
[`sandbox`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe#sandbox)
attribute, include `allow-modals`.

#### Sandboxed iframe (PCI DSS v4)

If you render the frame in a sandboxed iframe (for example, for PCI DSS v4 compliance), include `allow-scripts allow-popups allow-same-origin allow-forms`. Sandboxing is one way to isolate the frame when Google Pay's `pay.js` cannot provide a stable Subresource Integrity hash. See [Google Pay inside sandboxed iframe for PCI DSS v4 compliance](https://developers.googleblog.com/google-pay-inside-sandboxed-iframe-for-pci-dss-v4-compliance/) for details.

When you use the `sandbox` attribute, each value serves a specific purpose:

* `allow-scripts` runs `pay.js`.
* `allow-popups` opens the payment window on user interaction.
* `allow-same-origin` grants the browser storage and cookie access needed for compatibility.
* `allow-forms` submits the Google Pay sign-in form.
* `allow-modals` shows the test-mode payment dialog (`window.prompt`).

### Mobile WebViews

Rendering the frame inside a mobile WebView has additional requirements:

* **Apple Pay in an iOS `WKWebView`**: handle the JavaScript dialogs the frame
  uses. See [WKWebView](#wkwebview).
* **Google Pay in an Android WebView**: needs the AndroidX WebKit dependency,
  intent queries, the Payment Request API enabled, and an approved app. See
  [Android WebView](https://dev.moonpay.com/platform/overview/requirements.md#android-webview).
* **Google Pay in an iOS `WKWebView`**: not available. Offer another payment
  method. See [iOS WKWebView](https://dev.moonpay.com/platform/overview/requirements.md#ios-wkwebview).

### WKWebView

In a native iOS app, you render the frame inside a `WKWebView`. The frame communicates with the host app through the `postMessage`-based [frames protocol](https://dev.moonpay.com/platform/frames/overview.md#frames-protocol). See [Events](#events) below.

You must handle JavaScript dialogs. The frame uses `window.prompt` to present the simulated Apple Pay sheet in [test mode](https://dev.moonpay.com/platform/overview/test-mode.md#apple-pay). By default a `WKWebView` silently dismisses `alert`, `confirm`, and `prompt`: `window.prompt` returns `null` with no UI shown, and the frame reads that as the customer cancelling, so the transaction comes back with `status: "failed"`.

To fix this, conform your view controller to `WKUIDelegate`, set `webView.uiDelegate`, and present the text input panel, for example as a `UIAlertController` with a text field:

```swift theme={null}
extension MoonPayFrameViewController: WKUIDelegate {
    func webView(_ webView: WKWebView,
                 runJavaScriptTextInputPanelWithPrompt prompt: String,
                 defaultText: String?,
                 initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (String?) -> Void) {
        let alert = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
        alert.addTextField { $0.text = defaultText }
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
            completionHandler(nil)
        })
        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
            completionHandler(alert.textFields?.first?.text ?? defaultText)
        })
        present(alert, animated: true)
    }
}
```

Returning a string (even an empty one) authorizes the test payment; returning `nil` declines it.

Wire this even if you only ship live mode, since the default behavior applies to any dialog the frame surfaces.

For a complete native walkthrough that covers rendering the frame, wiring the bridge and events, and the full dialog handler, see [iOS manual integration](https://dev.moonpay.com/platform/guides/manual-integration/ios.md#buy-button-frame).

## Initialization parameters

| Property | Type | Required | Description |
| - | - | - | - |
| `clientToken` | `string` | ✅ | The [client token](https://dev.moonpay.com/platform/guides/api-and-sdk-credentials.md#client-token) from the [connect flow](https://dev.moonpay.com/platform/guides/connect-a-customer.md), or from the [connection check](https://dev.moonpay.com/platform/frames/check.md) when you offer [guest checkout](https://dev.moonpay.com/platform/guides/guest-checkout.md). Guest checkout needs the button, not headless mode. |
| `channelId` | `string` | ✅ | A unique identifier for the frame generated on your client. This value is attached to each `postMessage` payload to help identify messages. The format of this string is up to you. |
| `signature` | `string` | ✅ | The quote `signature` from the [quote endpoint](https://dev.moonpay.com/api-reference/platform/endpoints/quotes/get.md). Pass `signature` as returned. |
| `externalTransactionId` | `string` | | Your own identifier for the transaction. Stored and associated with the MoonPay transaction for correlation. Reuse the same value when a customer retries, so you can group attempts and calculate success rate more reliably. |
| `headless` | `string` | | Pass `true` to run the purchase on load with no button. Card and SEPA bank transfer quotes only; Apple Pay and Google Pay quotes need the button. See [Headless mode](#headless-mode). |
| `theme` | `string` | | Pass `dark` or `light` to force a specific appearance. If you omit this, the frame uses the user's system appearance. |
| `applePayButtonSettings` | `string` | | A `JSON.stringify`-ed, URL-encoded object that styles the Apple Pay button variant. See [Apple Pay button settings](#apple-pay-button-settings). |
| `googlePayButtonSettings` | `string` | | A `JSON.stringify`-ed, URL-encoded object that styles the Google Pay button variant. See [Google Pay button settings](#google-pay-button-settings). |

## Headless mode

Pass `headless=true` when you draw your own purchase button. The frame renders
nothing: after the [handshake](#handshake), it sends [`ready`](#ready) and starts
the purchase straight away. Mount the frame when the customer confirms the
purchase in your UI, not before, because mounting it is what starts the
purchase.

Headless mode runs the same steps as a tap on the card button, and uses the
same events, with these differences:

* It accepts card and SEPA bank transfer quotes only. See [Payment
  methods](#payment-methods).
* It needs a connected customer. A guest checkout quote gets [`error`](#error)
  with `invalidQuote`.
* It never sends [`buttonPressed`](#buttonpressed) or
  [`cancelled`](#cancelled).
* After `ready`, it sends exactly one final event:
  [`complete`](#complete), [`challenge`](#challenge), or [`error`](#error).
  Every quote that decodes gets `ready` first, including one the frame then
  rejects with `unsupportedPaymentMethod` or `invalidQuote`.
* It reads [`setQuote`](#setquote) only after an `error` with `quoteExpired`.
  The new quote starts a new attempt. At any other time the frame ignores
  `setQuote`, so it never starts a second purchase.
* On [`challenge`](#challenge), open the challenge frame without `resume`. The
  challenge frame finishes the purchase and sends its own
  [`complete`](https://dev.moonpay.com/platform/frames/challenge#complete).

### Bank transfer

For a SEPA bank transfer quote, the frame creates the transaction, but the
customer still has to send the money from their bank. MoonPay doesn't show the
bank details, so you do:

1. Read the transaction `id` from [`complete`](#complete).
2. Fetch the transaction with that `id` from the [transaction
   endpoint](https://dev.moonpay.com/api-reference/platform/endpoints/transactions/get.md), or with
   `client.getTransaction()` in the SDK.
3. Show the customer the bank details from
   [`bankTransferDepositInfo`](https://dev.moonpay.com/api-reference/platform/objects-and-types/transaction#bank-transfer-deposit-info)
   and the amount to send from `source.amount`.

The customer must include the payment `reference` from
`bankTransferDepositInfo` with their transfer, or it is rejected. See [Pay with
bank transfer](https://dev.moonpay.com/platform/guides/pay-with-bank-transfer.md).

## Apple Pay button settings

The Buy Button frame renders the button that matches the payment method in the
quote signature. `applePayButtonSettings` styles the **Apple Pay button variant
only**. It has no effect when the frame renders the card or Google Pay button,
or runs in headless mode.

Use `applePayButtonSettings` to style the Apple Pay button without injecting
custom CSS. Build a settings object, pass it through `JSON.stringify`,
URL-encode the result, and append it to the frame URL.

Every property is optional. Any property you omit keeps the button's default.

| Property | Type | Allowed values |
| - | - | - |
| `width` | `string` | Button width in pixels, as a bare number (`"320"`) or a `px` value (`"320px"`). Normalized to `"<n>px"`. Defaults to `100%` so the button fills the container. |
| `height` | `string` | Button height in pixels, in the same format as `width`. Defaults to `44px`. |
| `borderRadius` | `string` | Corner radius in pixels, in the same format as `width`. Defaults to `16px`. |
| `paddingX` | `string` | Horizontal padding in pixels, in the same format as `width`. Defaults to `16px`. |
| `paddingY` | `string` | Vertical padding in pixels, in the same format as `width`. Defaults to `8px`. |
| `style` | `string` | The button's visual style. One of `black`, `white-outline`, or `white`. When you omit this, the button follows the frame's `theme`: light renders the black button and dark renders the white button. |
| `type` | `string` | The button label. One of `plain`, `buy`, `top-up`, `reload`, `continue`, `check-out`, or `pay`. Defaults to `pay`. |
| `locale` | `string` | The button's language. One of `en-US`, `ar-AB`, `ca-ES`, `zh-CN`, `zh-HK`, `zh-TW`, `hr-HR`, `cs-CZ`, `da-DK`, `de-DE`, `nl-NL`, `en-AU`, `en-GB`, `fi-FI`, `fr-CA`, `fr-FR`, `el-GR`, `he-IL`, `hi-IN`, `hu-HU`, `id-ID`, `it-IT`, `ja-JP`, `ko-KR`, `ms-MY`, `nb-NO`, `pl-PL`, `pt-BR`, `pt-PT`, `ro-RO`, `ru-RU`, `sk-SK`, `es-MX`, `es-ES`, `sv-SE`, `th-TH`, `tr-TR`, `uk-UA`, or `vi-VN`. |

Dimensions accept pixels only. A bare number is treated as pixels and normalized to a `px` value.

### Validation

Validation applies each property on its own:

* A property with an invalid value is ignored, and the remaining valid properties still apply. Invalid values include a non-pixel dimension such as `50%`, and a `style`, `type`, or `locale` outside its allowed set.
* If the whole value is not valid JSON, the frame ignores `applePayButtonSettings` entirely and uses the defaults.

### Example

This object sets a 52px-tall white button with a 26px corner radius, the `buy` label, and French text:

```json theme={null}
{
  "height": "52",
  "borderRadius": "26",
  "style": "white",
  "type": "buy",
  "locale": "fr-FR"
}
```

Run it through `JSON.stringify`, URL-encode the result, and append it to the frame URL:

```
https://platform.moonpay.com/platform/v1/buy-button?...&applePayButtonSettings=%7B%22height%22%3A%2252%22%2C%22borderRadius%22%3A%2226%22%2C%22style%22%3A%22white%22%2C%22type%22%3A%22buy%22%2C%22locale%22%3A%22fr-FR%22%7D
```

If you set a custom `height`, size the [frame container](#size) to match.

## Google Pay button settings

`googlePayButtonSettings` styles the **Google Pay button variant only**. It has
no effect when the frame renders the card or Apple Pay button, or runs in
headless mode. You can pass both `applePayButtonSettings` and
`googlePayButtonSettings` on the same frame URL. The frame applies the one that
matches the button it renders.

Build a settings object, pass it through `JSON.stringify`, URL-encode the
result, and append it to the frame URL. Every property is optional. Any
property you omit keeps the button's default.

| Property | Type | Allowed values |
| - | - | - |
| `width` | `string` | Button width in pixels, as a bare number (`"320"`) or a `px` value (`"320px"`). Normalized to `"<n>px"`. When you omit this, the button fills the container. |
| `height` | `string` | Button height in pixels, in the same format as `width`. Defaults to `44px`. |
| `borderRadius` | `string` | Corner radius in pixels, in the same format as `width`. Defaults to `16px`. |
| `paddingX` | `string` | Horizontal padding in pixels, in the same format as `width`. If you set `paddingY` without `paddingX`, horizontal padding is `0px`. |
| `paddingY` | `string` | Vertical padding in pixels, in the same format as `width`. If you set `paddingX` without `paddingY`, vertical padding is `0px`. |
| `style` | `string` | The button's visual style. One of `black`, `white`, or `white-outline`. `white` and `white-outline` render the same white button with an outline. When you omit this, the color follows the frame's appearance. |

Unlike Apple Pay, the Google Pay button has no `type` (label) or `locale`
setting.

### Validation

Validation applies each property on its own:

* A property with an invalid value is ignored, and the remaining valid
  properties still apply. Dimensions must match `^\d+(\.\d+)?(px)?$`, so a value
  in another unit, such as `50%` or `2rem`, is ignored. A `style` outside its
  allowed set is ignored.
* The frame ignores `googlePayButtonSettings` entirely and uses the defaults if
  the value is not valid JSON, is longer than 4,096 characters, or is not a JSON
  object.

### Example

This object sets a 48px-tall black button with a 28px corner radius:

```json theme={null}
{
  "style": "black",
  "height": "48",
  "borderRadius": "28"
}
```

Run it through `JSON.stringify`, URL-encode the result, and append it to the frame URL:

```
https://platform.moonpay.com/platform/v1/buy-button?...&googlePayButtonSettings=%7B%22style%22%3A%22black%22%2C%22height%22%3A%2248%22%2C%22borderRadius%22%3A%2228%22%7D
```

If you set a custom `height`, size the [frame container](#size) to match.

## Events

All events are dispatched using the message pattern described in the [frames
protocol](https://dev.moonpay.com/platform/frames/overview.md#frames-protocol). Headless mode
uses the same events; see [Headless mode](#headless-mode) for which ones it
sends.

### Outbound events

frame->parent

These events are sent from this frame to the parent window.

#### `handshake`

The frame requests that you open a message channel.

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "handshake"
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type HandshakeEvent = Message<{
  kind: "handshake";
}>;
```

#### `ready`

With the button, the frame finished loading and the payment button is rendered.
Use this to coordinate UI transitions if needed. The frame sends `ready` again
after a [`setQuote`](#setquote) with a different currency has been checked.

In [headless mode](#headless-mode), the purchase is starting. Use this to show
a loading indicator in your UI. After `ready`, the frame sends exactly one final
event: [`complete`](#complete), [`challenge`](#challenge), or [`error`](#error).

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "ready"
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type ReadyEvent = Message<{
  kind: "ready";
}>;
```

#### `buttonPressed`

The customer tapped the pay button. The frame emits this the instant the button
is tapped. For Apple Pay and Google Pay, it fires before the OS presents the
payment sheet (PassKit on iOS, the Google Pay sheet on Android). For card, it
fires before the card pipeline runs. Treat it as an intent-to-buy signal: use it
to react to the tap, for example to show a loading state or fire analytics.
Headless mode does not send this event.

This event carries no payload. Route it by `channelId`.

`buttonPressed` is not a purchase outcome. It still fires if the customer opens
the payment sheet and then cancels, and it fires before any authorization
happens. For the transaction result, listen for [`complete`](#complete), which
reports the outcome once the payment resolves.

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "buttonPressed"
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type ButtonPressedEvent = Message<{
  kind: "buttonPressed";
}>;
```

#### `complete`

The purchase finished. Check `transaction.status` before treating it as a
success:

* Not `failed`: the transaction was created and payment is processing. Use the
  transaction `id` to track final status, for example by polling or via
  webhooks. For a bank transfer quote, also use the `id` to fetch the bank
  details to show the customer. See [Bank transfer](#bank-transfer).
* `failed`: the payment did not go through. `failureCode` says why and
  `failureReason` gives developer-facing details. If `id` is present, the
  transaction exists and you can fetch it. If `id` is missing, the transaction
  was never created, so there is nothing to poll.

After a guest checkout recovery that finished on this button with `resume`, the
payload also carries `sessionUpgraded: true`: create a new session and check
the connection again. See [Finish on your buy
button](https://dev.moonpay.com/platform/guides/pay-with-buy-button.md#finish-on-your-buy-button).

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "complete",
  "payload": {
    "transaction": {
      "id": "txn_01",
      "status": "pending"
    }
  }
}
```

```json Failed example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "complete",
  "payload": {
    "transaction": {
      "status": "failed",
      "failureCode": "authorizationDeclined",
      "failureReason": "Your payment was declined by your bank."
    }
  }
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type FrameTransactionFailureCode =
  | "applePayMerchantUnavailable"
  | "authorizationDeclined"
  | "serviceUnavailable"
  | "transactionDeclined"
  | "transactionNotAllowed"
  | "unknown"
  | "validationError";

type BuyButtonCompleteEvent = Message<{
  kind: "complete";
  payload: {
    transaction:
      | {
          id: string;
          status: "pending" | "completed" | "failed";
        }
      | {
          /** Missing when the transaction was never created. */
          id?: string;
          status: "failed";
          failureCode: FrameTransactionFailureCode;
          /** A developer-facing reason. Not intended to be rendered in UI. */
          failureReason: string;
        };
    /** Present after a guest checkout recovery. */
    sessionUpgraded?: true;
  };
}>;
```

##### Failure codes

Branch on `failureCode`, not `failureReason`, for programmatic handling.

| `failureCode` | When it fires | Recommended handling |
| - | - | - |
| `authorizationDeclined` | The issuer or gateway rejected the authorization. | Prompt the customer to try a different card. |
| `transactionNotAllowed` | The payment method or account isn't eligible, for example a region restriction or purchase limit. | Guide the customer to resolve the issue or choose a different payment method. |
| `validationError` | The transaction request was invalid, for example an unsupported currency. | Check the quote parameters and retry with corrected values. |
| `serviceUnavailable` | A temporary problem on MoonPay's side. | Get a new quote and try again. |
| `applePayMerchantUnavailable` | Apple Pay merchant validation failed. Apple Pay only. | Retry after a short delay or offer an alternative payment method. |
| `transactionDeclined` | The transaction was declined. Not sent by this frame today. | Treat like `unknown`. |
| `unknown` | Any other failure, including fraud blocks. | Read `failureReason` for details and let the customer retry. |

> [!TIP]
>
> Quote expiry is reported through the [`error`](#error) event with `code:
>     "quoteExpired"`, not through `complete`. Listen for both events to cover all
> failure paths.

#### `challenge`

Verification is required before the transaction can proceed. Render the
[challenge frame](https://dev.moonpay.com/platform/frames/challenge.md) at the provided URL. Do not
construct the URL yourself — use it as-is.

For an Apple Pay or Google Pay quote, open the challenge frame with `resume` to
have the customer pay on this button once the challenge is done. Keep this
button mounted. The challenge frame then emits
[`resolved`](https://dev.moonpay.com/platform/frames/challenge#resolved), and the customer taps this
button again. See [Finish on your buy
button](https://dev.moonpay.com/platform/guides/pay-with-buy-button.md#finish-on-your-buy-button).

For a card or bank transfer quote, including [headless
mode](#headless-mode), open the challenge frame without `resume`. It finishes
the purchase and sends [`complete`](https://dev.moonpay.com/platform/frames/challenge#complete).

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "challenge",
  "payload": {
    "kind": "frame",
    "url": "https://platform.moonpay.com/platform/v1/challenge?challengeToken=..."
  }
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type BuyButtonChallengeEvent = Message<{
  kind: "challenge";
  payload: {
    kind: string;
    /** Fully-formed URL to pass directly as the challenge frame src. */
    url: string;
  };
}>;
```

#### `cancelled`

The customer dismissed the Apple Pay or Google Pay sheet without paying. This
is a cancellation, not a failure, so handle it separately from
[`error`](#error). The button stays on screen and the customer can tap it
again. Card payments and headless mode do not send this event.

The payload carries `code: "payment_sheet_dismissed"` and a developer-facing
`message`. The message is not intended to be rendered in UI.

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "cancelled",
  "payload": {
    "code": "payment_sheet_dismissed",
    "message": "Apple Pay sheet was dismissed"
  }
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type BuyButtonCancelledEvent = Message<{
  kind: "cancelled";
  payload: {
    /** Always `payment_sheet_dismissed` for this event. */
    code: "payment_sheet_dismissed";
    /** A developer-facing message. Not intended to be rendered in UI. */
    message: string;
  };
}>;
```

#### `error`

The purchase could not run. Remove the frame and log the message for
debugging, except after `quoteExpired`: keep the frame and send a new quote with
[`setQuote`](#setquote). `error` covers setup problems, an expired quote, and
unexpected errors (`generic`). A payment that fails arrives as a
[`complete`](#complete) event with `status: "failed"`.

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "error",
  "payload": {
    "code": "invalidQuote",
    "message": "Unable to decode the quote signature."
  }
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type BuyButtonErrorEvent = Message<{
  kind: "error";
  payload: {
    code:
      | "configurationError"
      | "invalidQuote"
      | "quoteExpired"
      | "unsupportedPaymentMethod"
      | "applePayUnavailable"
      | "googlePayUnavailable"
      | "generic";
    /** A developer-facing error message. Not intended to be rendered in UI. */
    message: string;
  };
}>;
```

| Code | Description |
| - | - |
| `configurationError` | Missing `channelId`, `clientToken` or `signature` parameter |
| `invalidQuote` | The quote can't be used. For example, the signature can't be decoded, or the customer can't pay with it (card and bank transfer quotes need a connected customer, not a guest) |
| `quoteExpired` | The quote expired before the transaction was created. Get a new quote and send it with [`setQuote`](#setquote) |
| `unsupportedPaymentMethod` | The quote's payment method doesn't run in the mode you loaded: a `sepa` quote without `headless=true`, or an Apple Pay or Google Pay quote with it. See [Payment methods](#payment-methods) |
| `applePayUnavailable` | The quote is for Apple Pay, but Apple Pay is not available on this device or browser |
| `googlePayUnavailable` | The quote is for Google Pay, but Google Pay is not available on this device or browser |
| `generic` | Unspecified error |

### Inbound events

parent->frame

These events are sent from the parent window to this frame.

#### `ack`

Acknowledge the [handshake](#handshake).

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "ack"
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type AckEvent = Message<{
  kind: "ack";
}>;
```

#### `setQuote`

Provide a new quote to the frame. Pass `signature` as returned by the quote
endpoint.

With the button, send this when the current quote expires before the customer
completes the purchase.

In [headless mode](#headless-mode), send this only after an [`error`](#error)
with `quoteExpired`. The frame retries the purchase with the new quote. At any
other time it ignores `setQuote`, so it never starts a second purchase.

```json Example theme={null}
{
  "version": 2,
  "meta": { "channelId": "ch_1" },
  "kind": "setQuote",
  "payload": {
    "quote": {
      "signature": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9..."
    }
  }
}
```

```ts twoslash TypeScript definition theme={null}
type Message<T> = T & {
  version: 2;
  meta: { channelId: string };
};

type SetQuoteEvent = Message<{
  kind: "setQuote";
  payload: {
    quote: {
      /** The signature from a valid quote. */
      signature: string;
    };
  };
}>;
```
