### Install SDK with bun Source: https://dev.moonpay.com/platform/sdk-reference/web/overview Install the SDK package using bun. ```bash bun add @moonpay/platform ``` -------------------------------- ### Install SDK with pnpm Source: https://dev.moonpay.com/platform/sdk-reference/web/overview Install the SDK package using pnpm. ```bash pnpm i @moonpay/platform ``` -------------------------------- ### Install SDK with npm Source: https://dev.moonpay.com/platform/sdk-reference/web/overview Install the SDK package using npm. ```bash npm i @moonpay/platform ``` -------------------------------- ### URL Signing Example Source: https://dev.moonpay.com/llms-full.txt Example demonstrating how to handle URL signing requests for secure widget integration. ```APIDOC ## URL Signing Integration ### Description This example shows how to implement the `onUrlSignatureRequested` prop for the `MoonPayBuyWidget`. It includes an asynchronous function `handleGetSignature` that fetches a signature from a backend API. This is crucial for security when using `walletAddress` or `walletAddresses` query parameters. ### Component ```typescript import { MoonPayBuyWidget } from "@moonpay/moonpay-react"; const handleGetSignature = async (url: string): Promise => { const signature = await fetch( `https://YOUR_API_DOMAIN.com/sign-url?url=${url}`, ); return signature; }; export default function Home() { return ( <> ); } ``` ``` -------------------------------- ### Install MoonPay Node.js SDK Source: https://dev.moonpay.com/widget/on-ramp-node-sdk Install the MoonPay Node.js SDK using npm. ```APIDOC ## Install MoonPay Node.js SDK ```bash npm install @moonpay/moonpay-node ``` ``` -------------------------------- ### Install react-native-webview with React Native CLI Source: https://dev.moonpay.com/platform/guides/manual-integration/react-native Install the react-native-webview library using your preferred package manager (pnpm, bun, or npm). If targeting iOS, run `pod install` in the `ios` directory. ```bash pnpm i react-native-webview ``` ```bash bun add react-native-webview ``` ```bash npm i react-native-webview ``` -------------------------------- ### Initialize Swap Flow with Customer Setup Source: https://dev.moonpay.com/llms-full.txt Initializes the MoonPay SDK for a 'swapsCustomerSetup' flow, handling authentication tokens and setup completion. ```APIDOC ## Initialize Swap Flow (w/customer setup) ### Description Initializes the MoonPay SDK for a 'swapsCustomerSetup' flow, handling authentication tokens and setup completion. ### Method `moonPay?.({...})` ### Parameters * `flow` (string) - Required - Must be "swapsCustomerSetup" * `environment` (string) - Required - "sandbox" or "production" * `variant` (string) - Required - "overlay" * `params` (object) - Required - Contains `apiKey`, `amount`, `amountCurrencyCode` * `handlers` (object) - Optional - Contains `onAuthToken` and `onSwapsCustomerSetupComplete` ### Request Example ```typescript const widget = moonPay?.({ flow: "swapsCustomerSetup", environment: "sandbox", variant: "overlay", params: { apiKey: "pk_test_123", amount: "300", amountCurrencyCode: "usd", }, handlers: { async onAuthToken({ token }) { // Once the customer has logged in in the widget, we share their // swaps-scoped authentication token with your app so you can // perform swaps requests on behalf of the customer. // The token needs to be passed as an Authorization header in the format // "Authorization: Bearer {token}". console.log("onAuthToken received with token:", token); }, async onSwapsCustomerSetupComplete() { // When this is received, you can close the widget and resume the // the swap flow in your UI. console.log("onSwapsCustomerSetupComplete received"); }, }, }); widget?.show(); ``` ``` -------------------------------- ### Install MoonPay JS SDK Source: https://dev.moonpay.com/widget/off-ramp-web-sdk Install the MoonPay JavaScript SDK using npm for type-safe integration. ```bash npm install @moonpay/moonpay-js ``` -------------------------------- ### Install react-native-webview Source: https://dev.moonpay.com/widget/off-ramp-react-native-sdk Install the react-native-webview package, which is required for the SDK's in-app browser functionality. ```bash npm install --save react-native-webview ``` -------------------------------- ### Install react-native-url-polyfill Source: https://dev.moonpay.com/widget/off-ramp-react-native-sdk Install the react-native-url-polyfill package to prevent potential issues with URL formatting. ```bash npm install --save react-native-url-polyfill ``` -------------------------------- ### Install MoonPay Node.js SDK Source: https://dev.moonpay.com/widget/off-ramp-node-sdk Install the MoonPay Node.js SDK using npm. This is the first step to integrating MoonPay functionality into your backend. ```bash npm install @moonpay/moonpay-node ``` -------------------------------- ### Install OpenAPI Generator CLI Source: https://dev.moonpay.com/platform/guides/openapi-codegen Install the OpenAPI Generator command-line interface globally to generate clients for various languages. ```bash npm install @openapitools/openapi-generator-cli -g ``` -------------------------------- ### Install react-native-webview with bun Source: https://dev.moonpay.com/llms-full.txt Install the react-native-webview library using bun. This is required for rendering MoonPay frames in React Native applications. ```bash bun add react-native-webview ``` -------------------------------- ### Get Swap Transaction by ID Source: https://dev.moonpay.com/api-reference/widget/getswaptransaction Returns a swap transaction by id. Refer to our Recipes section for more detailed examples. ```APIDOC ## Get Swap Transaction by ID ### Description Returns a swap transaction by id. Refer to our Recipes section for more detailed examples. ### Method GET ### Endpoint /swap-transactions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the swap transaction. ### Response #### Success Response (200) - **transaction** (object) - Details of the swap transaction. - **id** (string) - The unique identifier of the transaction. - **status** (string) - The current status of the transaction (e.g., "pending", "completed", "failed"). - **from_currency** (string) - The currency being sent. - **to_currency** (string) - The currency being received. - **amount** (string) - The amount of the transaction. - **created_at** (string) - The timestamp when the transaction was created. - **updated_at** (string) - The timestamp when the transaction was last updated. #### Response Example ```json { "transaction": { "id": "swap_abc123", "status": "completed", "from_currency": "BTC", "to_currency": "ETH", "amount": "0.1", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:05:00Z" } } ``` ``` -------------------------------- ### Ready Event Source: https://dev.moonpay.com/llms-full.txt The buy pipeline is starting. Use this to show a loading indicator in your UI. ```APIDOC ## Ready Event ### Description The buy pipeline is starting. Use this to show a loading indicator in your UI. ### Kind ready ### Payload Example ```json { "version": 2, "meta": { "channelId": "ch_1" }, "kind": "ready" } ``` ### TypeScript Definition ```ts type Message = T & { version: 2; meta: { channelId: string }; }; type ReadyEvent = Message<{ kind: "ready"; }>; ``` ``` -------------------------------- ### Get Swap Requote by ID Source: https://dev.moonpay.com/api-reference/widget/getswaprequote Returns a swap transaction re quote by id. Refer to our Recipes section for more detailed examples. ```APIDOC ## Get Swap Requote by ID ### Description Returns a swap transaction re quote by id. Refer to our Recipes section for more detailed examples. ### Method GET ### Endpoint `/v1/quotes/swap/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the swap transaction to re quote. ``` -------------------------------- ### MoonPay Buy Frame Usage in Flutter Source: https://dev.moonpay.com/platform/guides/manual-integration/flutter Example of integrating the MoonPayBuyFrame and MoonPayChallengeFrame within a Flutter screen. This setup handles initiating a purchase, managing quote expiration, and displaying the challenge flow when needed. It includes error handling and navigation callbacks. ```dart class BuyPaymentScreen extends StatefulWidget { final String clientToken; final String initialQuoteSignature; const BuyPaymentScreen({ super.key, required this.clientToken, required this.initialQuoteSignature, }); @override State createState() => _BuyPaymentScreenState(); } class _BuyPaymentScreenState extends State { late String _quoteSignature; String? _challengeUrl; @override void initState() { super.initState(); _quoteSignature = widget.initialQuoteSignature; } Future _fetchNewQuote() async { final newQuote = await yourApi.getQuote(); setState(() => _quoteSignature = newQuote.signature); } void _handleComplete(TransactionResult transaction) { setState(() => _challengeUrl = null); debugPrint('Transaction initiated: ${transaction.id}'); Navigator.of(context).pushNamed('/transaction-status'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Buy Crypto')), body: Stack( children: [ // Your payment summary UI MoonPayBuyFrame( clientToken: widget.clientToken, quoteSignature: _quoteSignature, onComplete: _handleComplete, onChallenge: (url) => setState(() => _challengeUrl = url), onError: (error) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error: ${error.message}')), ); }, onQuoteExpired: _fetchNewQuote, ), if (_challengeUrl != null) Positioned.fill( child: MoonPayChallengeFrame( challengeUrl: _challengeUrl!, onComplete: _handleComplete, onCancelled: () => setState(() => _challengeUrl = null), onError: (error) { setState(() => _challengeUrl = null); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error: ${error.message}')), ); }, ), ), ], ), ); } } ``` -------------------------------- ### Initialize SDK with In-App Browser Wrapper Source: https://dev.moonpay.com/widget/off-ramp-react-native-sdk This example shows how to initialize the SDK with a custom wrapper for the in-app browser. It also requires fetching a signature from your backend. ```typescript import { View, Button, Text, useEffect } from "react-native"; import { useMoonPaySdk } from "@moonpay/react-native-moonpay-sdk"; const InAppBrowserWrapper = { open: async (url) => { // Use any in-app browser method here InAppBrowser.open(url); }, }; const YourComponent = () => { const { openWithInAppBrowser, generateUrlForSigning, updateSignature } = useMoonPaySdk({ sdkConfig: { flow: "buy", environment: "sandbox", params: { apiKey: "pk_test_123", }, }, InAppBrowser: InAppBrowserWrapper, }); useEffect(() => { // The URL for signature should be sent to your backend, which should then // sign it with your API secret and return the signature. // Once you have the signature, you can update the SDK with it and show the widget. fetch("/sign-url", { headers: { "Content-Type": "application/json", Authorization: "Bearer ", }, method: "POST", body: JSON.stringify({ url: generateUrlForSigning(), }), }) .then((res) => res.json()) .then((data) => { const signature = data.signature; updateSignature(signature); }); }, []); return ( ); }; ``` -------------------------------- ### Transaction Example Source: https://dev.moonpay.com/api-reference/platform/objects-and-types/transaction An example of a completed transaction object. ```APIDOC ## Example ```json { "id": "tr_abc123", "createdAt": "2026-01-29T14:30:50.000Z", "updatedAt": "2026-01-29T15:30:50.000Z", "status": "completed", "source": { "amount": "100.00", "asset": { "code": "USD" } }, "destination": { "amount": "0.0025", "asset": { "code": "ETH" } }, "fees": { "network": { "amount": "2.50", "currencyCode": "USD" }, "moonpay": { "amount": "3.99", "currencyCode": "USD" } }, "wallet": { "address": "0x1234...abcd" }, "customer": { "id": "cust_xyz789" }, "paymentMethod": { "type": "apple_pay" } } ``` ``` -------------------------------- ### Get a transaction Source: https://dev.moonpay.com/llms-full.txt Get details for a single transaction by ID. ```APIDOC ## GET /platform/v1/transactions/{id} ### Description Get details for a single transaction by ID. ### Method GET ### Endpoint /platform/v1/transactions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the transaction. ``` -------------------------------- ### Initialize SDK using Package Source: https://dev.moonpay.com/llms-full.txt Asynchronously loads the MoonPay SDK constructor using the `loadMoonPay` function from the `@moonpay/moonpay-js` package. ```APIDOC ## Initialize SDK using Package ### Description Asynchronously loads the MoonPay SDK constructor using the `loadMoonPay` function from the `@moonpay/moonpay-js` package. ### Method `await loadMoonPay()` ### Code Example ```typescript import { loadMoonPay } from "@moonpay/moonpay-js"; const moonPay = await loadMoonPay(); ``` ``` -------------------------------- ### Initialize SDK with WebView Source: https://dev.moonpay.com/widget/off-ramp-react-native-sdk This snippet demonstrates initializing the SDK to use a WebView for displaying the MoonPay widget. It includes a placeholder for fetching a signature. ```typescript import { View, Button, Text } from "react-native"; import { useMoonPaySdk } from "@moonpay/react-native-moonpay-sdk"; const YourComponent = () => { const { MoonPayWebView } = useMoonPaySdk({ flow: "buy", environment: "sandbox", params: { apiKey: "pk_test_key", }, }); useEffect(() => { // This is just an example of how it might look like. // You may handle this differently. fetch("/sign-url", { headers: { "Content-Type": "application/json", Authorization: "Bearer ", }, method: "POST", body: JSON.stringify({ url: sdk.generateUrlForSigning(), }), } ``` -------------------------------- ### MoonPaySellWidget Example Source: https://dev.moonpay.com/llms-full.txt Example of how to use the MoonPaySellWidget with the 'overlay' variant and control its visibility. ```APIDOC ## MoonPaySellWidget Usage ### Description This example demonstrates how to use the `MoonPaySellWidget` component from the `@moonpay/moonpay-react` library. It shows how to set the widget variant, currency codes and amounts, and how to control the widget's visibility using a state variable. ### Component ```typescript import { MoonPaySellWidget } from "@moonpay/moonpay-react"; import { useState } from "react"; export default function Home() { const [visible, setVisible] = useState(false); return ( <> ); } ``` ``` -------------------------------- ### MoonPayBuyWidget Example Source: https://dev.moonpay.com/llms-full.txt Example of how to use the MoonPayBuyWidget with the 'overlay' variant and control its visibility. ```APIDOC ## MoonPayBuyWidget Usage ### Description This example demonstrates how to use the `MoonPayBuyWidget` component from the `@moonpay/moonpay-react` library. It shows how to set the widget variant, currency codes and amounts, and how to control the widget's visibility using a state variable. ### Component ```typescript import { MoonPayBuyWidget } from "@moonpay/moonpay-react"; import { useState } from "react"; export default function Home() { const [visible, setVisible] = useState(false); return ( <> ); } ``` ``` -------------------------------- ### Initialize SDK with WebView Source: https://dev.moonpay.com/widget/on-ramp-react-native-sdk This snippet demonstrates how to initialize the SDK for use within a WebView. It includes a placeholder for fetching a signature, similar to the in-app browser examples. ```typescript import { View, Button, Text } from "react-native"; import { useMoonPaySdk } from "@moonpay/react-native-moonpay-sdk"; const YourComponent = () => { const { MoonPayWebView } = useMoonPaySdk({ flow: "buy", environment: "sandbox", params: { apiKey: "pk_test_key", }, }); useEffect(() => { // This is just an example of how it might look like. // You may handle this differently. fetch("/sign-url", { headers: { "Content-Type": "application/json", Authorization: "Bearer ", }, method: "POST", body: JSON.stringify({ url: sdk.generateUrlForSigning(), }), }); }); } ``` -------------------------------- ### client.setupApplePay() Source: https://dev.moonpay.com/platform/sdk-reference/web/setup-apple-pay Render the Apple Pay frame into your UI and initiate a transaction with an executable quote signature. ```APIDOC ## client.setupApplePay() ### Description Render the Apple Pay frame into your UI and initiate a transaction with an executable quote signature. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `quote` (string) - Required - The quote `signature` returned from [`getQuote`](/platform/sdk-reference/web/get-quote). * `container` (HTMLElement) - Required - A DOM element to render the Apple Pay frame into. * `onEvent` ((event: ApplePayEvent) => void) - Required - Callback invoked for Apple Pay flow events. See [`ApplePayEvent`](#applepayevent). This method does not require a `clientToken` parameter. The client uses stored credentials from an active connection. ### `ApplePayEvent` `onEvent` receives events as the Apple Pay flow progresses. Use `event.kind` to decide how to handle each event. | kind | Payload | When you receive it | | ---------------- | ------------------------------------------------ | --------------------------------------------------------------------------------| | `"ready"` | — | The Apple Pay UI is rendered and ready to be shown. | | `"complete"` | `{ transaction: [`Transaction`](#transaction) }` | The Apple Pay flow finished and a transaction was created. | | `"quoteExpired"` | `{ setQuote: (quoteSignature: string) => void }` | The quote signature expired. Fetch a new quote and call `payload.setQuote(...)`. | | `"error"` | [`ApplePayEventError`](#applepayeventerror) | The flow encountered an error. | | `"unsupported"` | — | Apple Pay isn't supported or available in the user's current environment. | #### `Transaction` This is the transaction object returned when the Apple Pay flow completes. See the [API reference](/api-reference/platform/endpoints/transactions/get) for details. | Field | Type | Required | Description | | --------------- | ----------------------------------------- | -------- | ----------------------------------------------------------------- | | `status` | `"complete"` | ` ``` -------------------------------- ### onSwapsCustomerSetupComplete Source: https://dev.moonpay.com/widget/off-ramp-sdk-events-details Fired when the Swaps Customer Setup flow has completed. ```APIDOC ## onSwapsCustomerSetupComplete ### Description Fired when the Swaps Customer Setup flow has completed signaling to the parent app that the widget may now be closed. ### Method `onSwapsCustomerSetupComplete(): Promise` ### Returns `Promise` ``` -------------------------------- ### client.setupApplePay() Source: https://dev.moonpay.com/platform/sdk-reference/web/setup-apple-pay Initializes the Apple Pay integration. It returns a Result object which can either be an ApplePayFrame on success or a SetupApplePayError on failure. ```APIDOC ## `client.setupApplePay()` ### Description Initializes the Apple Pay integration. It returns a `Result`. ### Returns - `Result`: An object indicating success or failure. #### `Result` Structure | Field | Type | Required | Description | | ------- | ------------------------------------------- | -------- | -------------------------------- | | `ok` | `boolean` | ✅ | Whether the operation succeeded. | | `value` | [`ApplePayFrame`](#applepayframe) | | Present when `ok` is `true`. | | `error` | [`SetupApplePayError`](#setupapplepayerror) | | Present when `ok` is `false`. | ### `ApplePayFrame` | Field | Type | Required | Description | | ---------- | ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | | `setQuote` | `(quoteSignature: string) => void` | ✅ | Updates the quote signature used by the frame. Use this in response to `quoteExpired`. | | `dispose` | `() => void` | ✅ | Unmounts the frame. After you call this, no further events are dispatched to your `onEvent` callback. | ### `SetupApplePayError` | Field | Type | Required | Description | | --------- | ----------------------------------------------------------------------------------- | -------- | --------------------------- | | `kind` | `"invalidQuote"` \| `"quoteExpired"` \| `"applePayUnavailable"` \| `"genericError"` | ✅ | The error category. | | `message` | `string` | ✅ | Developer-friendly details. | ``` -------------------------------- ### Install @hey-api/openapi-ts Source: https://dev.moonpay.com/platform/guides/openapi-codegen Install the necessary package for generating TypeScript clients. This is a development dependency. ```bash npm install -D @hey-api/openapi-ts ``` -------------------------------- ### Install MoonPay Platform skills Source: https://dev.moonpay.com/llms-full.txt Run one of these commands to add MoonPay Platform skills to your agent's context. The skills CLI discovers and installs the `skill.md` file automatically. ```bash npx skills add https://dev.moonpay.com ``` ```bash bunx skills add https://dev.moonpay.com ``` ```bash pnpm dlx skills add https://dev.moonpay.com ``` -------------------------------- ### onReady Source: https://dev.moonpay.com/widget/off-ramp-sdk-events-details Fired when the SDK's communication layer has been set up and the Widget is loaded. ```APIDOC ## onReady ### Description Fired when the SDK's communication layer has been set up and the Widget is loaded. ### Method `onReady(): Promise` ### Returns `Promise` ``` -------------------------------- ### Error Handling Example Source: https://dev.moonpay.com/api-reference/platform/documentation/using-the-api Provides an example of the error object returned when an API request fails. ```APIDOC ## Error Handling When a request fails (4xx), the API returns an error object with details: ```json { "code": 400, "type": "Invalid request", "message": "Invalid request. sourceAmount must be greater than 0." } ``` ``` -------------------------------- ### Configure and Load Add Card Frame (Swift) Source: https://dev.moonpay.com/llms-full.txt Sets up the MoonPayAddCardViewController by configuring the client token and loading the add-card frame. Ensure configure(clientToken:) is called before presenting the view controller. ```swift import UIKit protocol AddCardFrameDelegate: AnyObject { func addCardDidComplete(card: [String: Any]) func addCardDidError(code: String, message: String) } class MoonPayAddCardViewController: MoonPayFrameViewController { private var clientToken: String! weak var addCardDelegate: AddCardFrameDelegate? func configure(clientToken: String) { self.clientToken = clientToken } override func viewDidLoad() { super.viewDidLoad() delegate = self guard clientToken != nil else { fatalError("Call configure(clientToken:) before presenting") } loadFrame(path: "/platform/v1/add-card", params: [ "clientToken": clientToken, "channelId": channelId, ]) } } // MARK: - MoonPayFrameDelegate extension MoonPayAddCardViewController: MoonPayFrameDelegate { func frameDidReceiveMessage(_ message: [String: Any]) { guard let kind = message["kind"] as? String else { return } switch kind { case "ready": break case "complete": let payload = message["payload"] as? [String: Any] ?? [:] let card = payload["card"] as? [String: Any] ?? [:] addCardDelegate?.addCardDidComplete(card: card) case "error": let payload = message["payload"] as? [String: Any] ?? [:] addCardDelegate?.addCardDidError( code: payload["code"] as? String ?? "unknown", message: payload["message"] as? String ?? "Unknown error" ) default: break } } func frameDidCompleteHandshake() { // Handshake complete } } ``` -------------------------------- ### Install MoonPay React Native SDK Source: https://dev.moonpay.com/widget/off-ramp-react-native-sdk Install the official MoonPay package using npm. ```bash npm install --save @moonpay/react-native-moonpay-sdk ``` -------------------------------- ### Initialize and Configure Check Frame Source: https://dev.moonpay.com/platform/guides/manual-integration/ios Configure the check frame to verify customer connection status. This frame is headless and does not display any UI. It requires a session token for configuration. ```swift class SplashViewController: UIViewController, CheckFrameDelegate { func checkConnection() { let checkVC = MoonPayCheckViewController() checkVC.configure(sessionToken: "your-session-token") checkVC.checkDelegate = self // The check frame is headless — add as a child without visible UI addChild(checkVC) checkVC.view.frame = .zero view.addSubview(checkVC.view) checkVC.didMove(toParent: self) } // MARK: - CheckFrameDelegate func checkDidFindActiveConnection(accessToken: String, clientToken: String, expiresAt: String) { // Customer is already connected — skip to payment CredentialsManager.shared.accessToken = accessToken CredentialsManager.shared.clientToken = clientToken let paymentVC = PaymentViewController() navigationController?.pushViewController(paymentVC, animated: true) } func checkDidRequireConnection(accessToken: String, clientToken: String) { // Store both tokens in memory, then show connect frame with the anonymous clientToken CredentialsManager.shared.accessToken = accessToken CredentialsManager.shared.clientToken = clientToken let connectVC = MoonPayConnectViewController() connectVC.configure(clientToken: clientToken) navigationController?.pushViewController(connectVC, animated: true) } func checkDidFail(status: String, reason: String?) { print("Check \(status): \(reason ?? "No reason provided")") } func checkDidError(code: String, message: String) { print("Check error: \(code) — \(message)") } } ``` -------------------------------- ### Setup MoonPay Node.js SDK Source: https://dev.moonpay.com/widget/on-ramp-node-sdk Import and initialize the MoonPay class with your secret key. Ensure your secret key is loaded from an environment variable and never used in client-side code. ```APIDOC ## Setup MoonPay Node.js SDK First, import the `MoonPay` class. ```typescript import { MoonPay } from '@moonpay/moonpay-node'; ``` Set up the `MoonPay` class with your secret key. NEVER use your secret key in client side code. Load your secret key from an environment variable instead. ```typescript const moonPay = new MoonPay("sk_test_..."); ``` ``` -------------------------------- ### Setup Headless Buy Frame Source: https://dev.moonpay.com/platform/guides/pay-with-card Initialize the headless buy frame for full UI control. Handle events like 'ready', 'complete', 'challenge', 'quoteExpired', and 'error' to manage the transaction lifecycle. ```typescript import type { BuyEvent } from "@moonpay/platform"; const buyResult = await client.setupBuy({ quote: quoteResult.value.signature, onEvent: (event: BuyEvent) => { switch (event.kind) { case "ready": // Pipeline starting — show a loading indicator break; case "complete": // Transaction complete. Track status via polling. console.log(event.payload.transaction); // { id: "txn_01", status: "pending" } break; case "challenge": // Verification required — render the challenge frame openChallengeFrame(event.payload.url, buyResult); break; case "quoteExpired": // Fetch a new quote, then update the frame: // const newQuote = await client.getQuote({...}); // event.payload.setQuote(newQuote.value.signature); break; case "error": console.error(event.payload.message); break; } }, }); if (!buyResult.ok) { // Handle error } ``` -------------------------------- ### Example Serialized Payload Source: https://dev.moonpay.com/llms-full.txt An example of a JSON message payload serialized into a string, as it would be transmitted via postMessage. ```json "{\"version\":\"2\",\"meta\":{\"channelId\":\"some_unique_value\"},\"kind\":\"example\",\"payload\":{\"example\":\"an example payload\"}}" ``` -------------------------------- ### Express Endpoint Example Source: https://dev.moonpay.com/widget/on-ramp-node-sdk An example of an Express endpoint that signs a URL query parameter using the MoonPay SDK. ```APIDOC ## Express Endpoint Example Here's an example of an Express endpoint that signs a URL query param. ```typescript import express from "express"; import { MoonPay } from "@moonpay/moonpay-node"; const moonPay = new MoonPay("sk*test*..."); const app = express(); app.get("/moonpay_signature", (req, res) => { const { url } = req.query; const signature = moonPay.url.generateSignature(url); res.send({ signature }); }); app.listen(3000, () => console.log("Listening on port 3000!")); ``` ``` -------------------------------- ### Setup MoonPay Class Source: https://dev.moonpay.com/widget/off-ramp-node-sdk Import and instantiate the MoonPay class with your secret key. Ensure your secret key is loaded from an environment variable and never used in client-side code. ```typescript import { MoonPay } from '@moonpay/moonpay-node'; const moonPay = new MoonPay("sk_test_..."); ``` -------------------------------- ### Node.js SDK - Express Endpoint Example Source: https://dev.moonpay.com/llms-full.txt Example of an Express.js endpoint that uses the MoonPay SDK to sign a URL query parameter. ```APIDOC ## Example: Express endpoint to sign URL query param ### Description This example demonstrates how to create an Express.js endpoint that receives a URL as a query parameter and returns its MoonPay signature. ### Setup 1. Install dependencies: `npm install express @moonpay/moonpay-node` 2. Ensure your secret key is loaded from an environment variable. ### Code Example ```typescript import express from "express"; import { MoonPay } from "@moonpay/moonpay-node"; // IMPORTANT: Load your secret key from an environment variable, NEVER hardcode it. const moonPay = new MoonPay("sk_test_..."); const app = express(); app.get("/moonpay_signature", (req, res) => { const { url } = req.query; if (!url || typeof url !== 'string') { return res.status(400).send({ error: "URL parameter is required and must be a string." }); } try { const signature = moonPay.url.generateSignature(url); res.send({ signature }); } catch (error) { console.error("Error generating signature:", error); res.status(500).send({ error: "Failed to generate signature." }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Listening on port ${PORT}!`)); ``` ``` -------------------------------- ### Setup Apple Pay Source: https://dev.moonpay.com/platform Initiate the Apple Pay payment process. This function sets up the Apple Pay button and handles events during the payment flow. ```APIDOC ## POST /platform/v1/apple-pay/setup ### Description Sets up the Apple Pay payment interface. ### Method POST ### Endpoint /platform/v1/apple-pay/setup ### Parameters #### Request Body - **quote** (string) - Required - The signature of the quote obtained from `getQuote`. - **container** (HTMLElement) - Required - The DOM element where the Apple Pay button will be rendered. - **onEvent** (function) - Required - A callback function to handle events during the Apple Pay flow. - **event.kind** (string) - The type of event (e.g., "ready", "complete", "quoteExpired"). - **event.payload** - Event-specific payload data. - For "complete": **transaction** (object) - Details of the transaction. - For "quoteExpired": **setQuote** (function) - Function to update the quote signature. ### Request Example ```javascript import type { ApplePayEvent } from "@moonpay/platform"; const paymentButtonContainer = document.querySelector("#payment"); const setupApplePayResult = await client.setupApplePay({ quote: quoteResult.value.signature, // The quote signature container: paymentButtonContainer, onEvent: (event: ApplePayEvent) => { switch (event.kind) { case "ready": // Reveal the button paymentButtonContainer.style.opacity = "1"; break; case "complete": // The transaction is executing. Use polling and/or webhooks to track final status. console.log(event.payload.transaction); // { id: "txn_01", status: "pending" } break; case "quoteExpired": // Fetch a new quote and update the frame // event.payload.setQuote(newQuote.signature); break; } }, }); if (!setupApplePayResult.ok) { // Handle error } ``` ### Response #### Success Response (200) Indicates successful setup of the Apple Pay interface. The actual payment processing is handled via the `onEvent` callback. ```