# Submitting the KYB Application Source: https://docs.grain.inc/get-started/onboarding/kyb-dashboard A general overview of the KYB Portal and what to expect during submission ## The KYB Portal Grain uses a dedicated KYB Portal to collect and verify your business information. When you're ready to begin, you'll receive a unique link to access the portal. The application is organized into clearly labeled sections, each covering a different aspect of your business. The portal sections include: * **Business Profile** — Your company's basic information and contact details * **Incorporation & Tax Details** — Registration details, entity type, and tax identification * **Business Activities** — Description of your operations, source of funds, and expected transaction volume * **Industry** — Your business sector and primary target market * **Ownership & Control** — Details about the company's ownership structure * **Beneficial Owners & Individuals** — Personal information for all control personnel, signers, and beneficial owners * **Ownership Documents** — Upload of formation documents and EIN documentation * **Business Details** — Additional context about your business operations * **Business Details Documents** — Supporting documentation for your business * **Review** — A summary of all entered information before final submission ## Tips for a Smooth Submission Make sure you have all required documents and information gathered before starting. Refer to the [KYB Requirements](/get-started/onboarding/kyb-requirements) page for the full checklist. * **Complete each section fully** — The portal tracks your progress across all sections. Incomplete sections will prevent you from submitting. * **Double-check personal details** — Names, dates of birth, and ID numbers must exactly match the documents you upload. Mismatches are one of the most common reasons for review delays. * **Use high-quality document scans** — Ensure uploaded documents are legible, not cropped, and show all four corners. Blurry or partial uploads will be rejected. * **FATF Grey List countries** — If any personnel resides in a [FATF Grey List](https://www.fatf-gafi.org/en/countries/black-and-grey-lists.html) country, an additional proof of address document is required. * **At least one signer is required** — Every company must designate at least one authorized signer. This person can also be a control person or beneficial owner. ## Sharing the Application The KYB Portal generates a unique link that can be shared with the appropriate person at your organization. If someone other than you is responsible for providing business documents or ownership details, you can share the portal link with them directly so they can fill in their section. ## After You Submit Once you submit your application through the portal, the Grain compliance team reviews your information. You will be notified by email when your application status changes. If additional information is needed, you'll receive a specific request detailing what to provide. Most applications are reviewed within 2–3 business days. Applications requiring enhanced due diligence may take up to 7 business days. # KYB Requirements Source: https://docs.grain.inc/get-started/onboarding/kyb-requirements What you need to complete Know Your Business verification ## What is KYB? Know Your Business (KYB) verification is a regulatory requirement that confirms your company's identity and legitimacy before you can process payments through Grain. All merchants must complete KYB verification before accepting live payments. Gather all documents and information below before starting your application. Incomplete submissions are the most common cause of delays in the review process. ## Documents to Prepare Have the following documents ready to upload during your application: * **Formation Document** — Copy of your LLC Agreement, Certificate of Incorporation, or equivalent * **Employer Identification Number** — IRS CP 575 letter, EIN confirmation letter, or equivalent * **Government-Issued ID for all Control Personnel and Beneficial Owners** * **U.S. Persons** — U.S. Driver's License (front and back), State ID Card (front and back), or Passport * **Non-U.S. Persons** — Passport Any personnel who resides in a country on the [FATF Grey List](https://www.fatf-gafi.org/en/countries/black-and-grey-lists.html) must also provide a copy of proof of address. ## Company Information to Prepare You will be asked to provide the following details about your business: * Registered company name and DBA name (if any) * Company description * Company address (both incorporation and operating address if different) * Entity type (LLC, C Corp, etc.) * Incorporation date * Employer Identification Number * Industry (Financial Services, Technology, Crypto, etc.) * Source of funds (Revenue, Investment, etc.) * Expected countries to send or receive funds * Expected monthly volume for crypto and fiat * Primary target market (Retail, Commercial, etc.) * Purpose of account (Business Operations, Cross-Border Payments, etc.) ## Control Personnel, Signers, and Beneficial Owners For each control person, signer, and beneficial owner, prepare the following information: * Full legal name (First, Middle, Last) * Date of birth * Home address * Social Security Number or Tax Identification Number * Role in the company (if control person) * Contact information (email and phone number) * Ownership percentage (if applicable) At least one signer is required for each company. A signer can also serve as a control person or beneficial owner. ## Review Timeline | Stage | Typical Duration | | ------------------------------------ | ----------------- | | Document review | 1–2 business days | | Enhanced due diligence (if required) | 3–5 business days | | Final approval | 1 business day | Most merchants receive approval within **2–3 business days** of submitting a complete application. ## What Happens After Approval Once your KYB verification is approved: 1. You receive a confirmation email with next steps 2. Production API keys become available in the Dashboard 3. You can configure your settlement preferences 4. You can start accepting live payments # Overview Source: https://docs.grain.inc/how-grain-works/overview How Grain enables merchants to accept crypto payments ## What Is Grain? Grain is a crypto payment processing platform that lets you accept cryptocurrency payments from your customers while receiving settlement in fiat currency. Your customers pay in the crypto of their choice, and Grain handles conversion, compliance, and settlement so you receive funds in your local currency. You never need to hold, manage, or understand cryptocurrency. Grain abstracts the complexity of blockchain payments into a simple merchant experience. ## How It Works At a high level, every Grain payment follows the same flow: 1. Your customer chooses to pay with crypto at checkout. 2. Grain generates a payment request with a unique wallet address. 3. The customer sends crypto from their wallet. 4. Grain detects the payment on-chain, converts the crypto to fiat, and settles the funds to your bank account. The entire process is automatic. You integrate once and Grain handles the rest. ## Key Components Follow a payment from creation through blockchain confirmation to final settlement in your bank account. Learn how and when you receive funds, how fees are deducted, and how to track settlement status. ## Integration Options Grain offers several ways to start accepting crypto payments: * **Checkout SDK** — Embed a crypto payment option directly into your existing checkout flow with a few lines of code. * **Payment Links** — Generate shareable payment links from the Grain Dashboard without writing any code. * **API** — Build fully custom payment experiences using the Grain REST API. ## Merchant Dashboard The Grain Dashboard is your central hub for managing payments, viewing settlement history, configuring your account, and accessing API keys. Every payment and settlement is tracked in real time so you always have full visibility into your funds. # Payment Lifecycle Source: https://docs.grain.inc/how-grain-works/payment-lifecycle Understand each stage of a Grain payment from initiation to settlement ## Payment Flow Every Grain payment moves through a defined set of stages — from checkout to final settlement. Understanding this flow helps you build better integrations and set clear expectations for your customers. ### Customer Initiates Payment The customer interacts with your payment module and selects **Pay with Crypto**. Grain's API generates a prefilled payment link containing the destination address, token, and amount. The customer is prompted to review, agree, and sign the transaction. If the customer does not agree or sign, the transaction is marked as **rejected** and the payment is **cancelled**. Once the customer signs the transaction, it undergoes Grain's automated compliance screening. After screening passes, the funds are delivered to a **one-time storage wallet** generated by Grain. The payment enters a settlement hold period while awaiting final settlement. If a refund is requested during this period, the refund process begins (see [Refund Flow](#refund-flow) below). If no refund is requested and the settlement period has passed, the transaction is **captured**. Once a transaction has been **captured**, your merchant account balance is **credited** and funds are ready to be **disbursed** based on your elected settlement method. *** ## Refund Flow Refunds can be initiated by either the customer or the merchant, following the merchant's refund policy. Here is how the refund process works: ### Refund Requested A refund is initiated by the user or merchant according to the merchant's refund policy. The request appears in your Grain Dashboard for review. ### Merchant Review You review the refund request on your Dashboard. You can approve or deny the request based on your refund policy and the details of the transaction. ### Refund Decision If approved, funds are sent back to the customer's **original payment address** from the generated one-time payment address. If denied, the refund request is rejected and the held funds are deposited to your **merchant account balance**. # Settlement Source: https://docs.grain.inc/how-grain-works/settlement How and when you receive funds from completed payments ## How Settlement Works After a crypto payment is confirmed, Grain converts the received cryptocurrency to your chosen settlement currency and transfers the funds to your account. By default, you receive fiat directly to your bank account. If you prefer, you can opt to receive settlement in a supported stablecoin instead. Settlement is fully automatic. Once you configure your bank account and settlement preferences in the Grain Dashboard, every confirmed payment flows through to your account without manual intervention. ## Settlement Schedule Settlement timing depends on your chosen settlement method: | Method | Timeline | Description | | ---------------------- | ------------- | ---------------------------------------------------------------------------------------- | | **Stablecoin** | **T+0** | Funds settle same day once the payment is confirmed on-chain | | **ACH** | **T+0 / T+1** | Funds settle same day or next business day depending on when the settlement is submitted | | **Domestic Wire** | **T+0 / T+1** | Funds settle same day or next business day via domestic wire transfer | | **International Wire** | **T+2 / T+3** | Funds settle within two to three business days via international wire transfer | Settlement scheduling is configured automatically — no manual setup required. Final settlement timing for fiat payments is subject to the receiving bank's processing schedule. If your settlement method is wire, additional wire transfer fees may be incurred by your bank. ## Settlement Amount Calculation The amount deposited into your bank account is the confirmed payment amount minus applicable fees: ``` Settlement Amount = Payment Amount (in fiat) − Transaction Fee ``` For example, if a customer pays the equivalent of \$100.00 USD and your transaction fee rate is 1.0%: | Item | Amount | | --------------------- | ----------- | | Payment amount | \$100.00 | | Transaction fee (1%) | −\$1.00 | | **Settlement amount** | **\$99.00** | The transaction fee is the only deduction applied by Grain. Note that if your settlement method is wire, your receiving bank may charge additional wire transfer fees. ## Supported Settlement Currencies ### Fiat Grain currently supports settlement in the following fiat currency: * **USD** — US Dollar The following currencies are coming soon to Grain: * **EUR** — Euro * **GBP** — British Pound * **CAD** — Canadian Dollar * **AUD** — Australian Dollar ### Stablecoin Grain currently supports settlement in the following stablecoins: * **USDC** — USD Coin * **USDT** — USD Tether The following stablecoins are coming soon to Grain: * **USD1** — World Liberty USD * **PYUSD** — PayPal USD If your desired currency is not listed, please contact us for supportability. # Grain Documentation Source: https://docs.grain.inc/index Everything you need to integrate and manage crypto payments with Grain Welcome to the Grain documentation. Whether you're integrating our Payment SDK, managing transactions through the Grain Dashboard, or getting your business verified — you'll find everything you need here. ## Start building Learn how Grain processes payments, from checkout to settlement. Prepare KYB verification, complete onboarding, and start accepting payments. ## Integrate & manage Install, configure, and integrate the Grain Payment SDK into your application. Monitor transactions, track settlements, and manage your account settings. Explore endpoints, authentication, error codes, and rate limits. Get help, check system status, and browse the FAQ. # API and Webhooks Source: https://docs.grain.inc/partner-dashboard/guide/api-and-webhooks Access your API keys and configure webhook endpoints The **Settings** tab is where you customize your account, manage security, and configure payment and payout options. Use the top navigation bar to switch between settings pages. Settings navigation bar In the API & Webhooks section, access your API keys and configure webhook endpoints. API and webhooks settings # Billing and Payouts Source: https://docs.grain.inc/partner-dashboard/guide/billing-and-payouts Manage your payout schedule and bank account Manage your payout schedule, minimum payout threshold, and bank account details. Billing and payouts settings # Filtering and Searching Source: https://docs.grain.inc/partner-dashboard/guide/filtering-and-searching Find specific transactions using filters, search, and CSV export ### Filtering Transactions The left sidebar provides a set of filters to help you narrow down your transaction list. Use these filters to quickly find transactions by their current status or isolate activity within a specific time period. Transaction filters **Status filters** let you isolate transactions by their current state: * **Started** — Payment session has been created * **Processing** — Payment is being confirmed on-chain * **Paid Out** — Funds have been settled to your account * **Settled** — Transaction is fully complete * **Failed** — Payment did not succeed **Date Range** options let you scope transactions by time period: * **Weekly** — View the last 7 days * **Monthly** — View the last 30 days * **Yearly** — View the last 12 months * **Custom Range** — Pick specific start and end dates using the calendar picker ### Searching and Exporting The search bar at the top right lets you instantly find specific transactions by **Transaction ID**, **Wallet Address**, or **Booking Reference**. Search and export Click **Export CSV** to download your filtered transaction data for accounting, reconciliation, or reporting. # Filters and Performance Source: https://docs.grain.inc/partner-dashboard/guide/filters-and-performance Filter by transaction status and visualize trends over time Use the dropdowns in the top right of the dashboard to filter your view by transaction status — Created, Pending, Funded, Succeeded, or Failed. Status filter dropdown The performance chart lets you visualize your sales volume and transaction trends over time. Performance overview chart # Key Metrics Source: https://docs.grain.inc/partner-dashboard/guide/key-metrics Track your sales volume, transaction count, and unique wallets at a glance When you first log in, you land on the main Dashboard — your command center for real-time business performance. Grain Dashboard overview At the top of the page, you'll find three key metrics to track your performance. Dashboard key metrics * **Total Sales Volume** — The total value of all successful transactions. * **Transaction Count** — The number of transactions processed over a selected period. * **Unique Wallets** — The number of unique customer wallets that have interacted with your business. # Notifications Source: https://docs.grain.inc/partner-dashboard/guide/notifications Configure email alerts for important events Configure email alerts for important events like daily transaction summaries, high-value transactions, and payout confirmations. Notification preferences # Payment Settings Source: https://docs.grain.inc/partner-dashboard/guide/payment-settings Choose which cryptocurrencies and networks to accept Choose which cryptocurrencies and networks you want to accept from your customers. Payment settings # Payouts and Recent Transactions Source: https://docs.grain.inc/partner-dashboard/guide/payouts-and-recent-transactions View your payout summary and latest transactions from the dashboard The bottom of the dashboard shows your payout summary and recent transactions at a glance. Payouts and recent transactions * **Payout Summary** — See how much has been paid out, what amount is pending, and when your next payout is scheduled. * **Recent Transactions** — A list of your most recent transactions for quick monitoring. # Security Source: https://docs.grain.inc/partner-dashboard/guide/security Enable two-factor authentication and manage IP whitelists Enable two-factor authentication and manage IP whitelists to secure your account. Security settings # Team Management Source: https://docs.grain.inc/partner-dashboard/guide/team-management Invite and manage team members on your account Invite and manage team members who have access to your Grain Dashboard. Team management settings # Transaction Details Source: https://docs.grain.inc/partner-dashboard/guide/transaction-details View a full breakdown of any individual payment Click on any transaction in the list to open the **Transaction Details** panel. This gives you a comprehensive breakdown of the payment in one view. Transaction details view ### Transaction Overview The top section displays the core payment information: * **Date & Time** — When the transaction was initiated (e.g., Jan 27, 2025 at 03:22PM) * **USD Volume** — The transaction value in USD * **Asset Type** — The cryptocurrency used for the payment (e.g., USDC) * **Network** — The blockchain network the payment was processed on (e.g., Ethereum) ### Customer Info Details about the customer who made the payment: * **Wallet Address** — The wallet that sent the payment * **Location** — The customer's country of origin ### Booking Details If your integration passes booking metadata, this section displays: * **Reference ID** — Your internal booking reference (e.g., `BK-2025-001472`) * **Service** — The type of service or product purchased * **Notes** — Any additional details associated with the booking ### Transaction Timeline The timeline at the bottom tracks each stage the transaction has passed through. Each step is visually connected so you can see exactly where the payment is in its lifecycle: 1. **Started** — Payment session created 2. **Processing** — Payment detected on-chain 3. **Settled** — Funds confirmed and settled 4. **Paid Out** — Funds transferred to your payout account # Viewing Transactions Source: https://docs.grain.inc/partner-dashboard/guide/viewing-transactions Monitor all your payments in one place The Transactions page is a detailed log of every payment that flows through your Grain integration. It displays all your transactions in a list with key details visible at a glance. Transactions page overview Each row in the transaction list shows: * **Transaction ID** — A unique identifier (e.g., `GRN-0004821`). * **Date and Time** — When the transaction was initiated. * **Wallet Address** — The wallet address that sent the payment. * **USD Amount** — The transaction value. * **Status** — The current state of the payment, color-coded for quick scanning. # Overview & Navigation Source: https://docs.grain.inc/partner-dashboard/overview Navigate the Grain Dashboard and understand its key features ## Welcome to the Grain Dashboard The Grain Dashboard is your central hub for managing crypto payment processing. From here, you can monitor transactions in real time, track payouts, and configure your account settings. Grain Dashboard overview After signing in at [dashboard.grain.co](https://dashboard.grain.co), you land on the **Home** screen with a snapshot of your sales volume, transaction count, and recent activity. ## Main Navigation The primary navigation runs along the left side of the dashboard, organized into three main areas: ### Dashboard Your command center with key metrics, a performance chart, payout summary, and recent transactions — everything you need at a glance. ### Transactions A detailed log of every payment that flows through your Grain integration. Filter by status, date range, search for specific transactions, and export to CSV. ### Settings Manage API keys and webhooks, choose which cryptocurrencies to accept, invite team members, configure security, set notification preferences, and manage billing and payouts. ## Quick Links Track sales volume, transaction count, and unique wallets. Filter by status and visualize trends over time. View payout summary and latest transactions. Find specific transactions and export to CSV. View a full breakdown of any payment. Access API keys and configure webhook endpoints. Choose which cryptocurrencies and networks to accept. Invite and manage team members. Enable 2FA and manage IP whitelists. Configure email alerts for important events. Manage payout schedule and bank account. ## Environment Switcher Use the environment toggle in the top-right corner to switch between **Sandbox** and **Production**. Sandbox mode lets you test your integration with simulated transactions before going live. Start in Sandbox mode to verify your integration end-to-end. When you are ready, switch to Production and generate live API keys from the **Settings** page. # Authentication Source: https://docs.grain.inc/payment-sdk/api-reference/authentication Authenticate your API requests to the Payment SDK ## Bearer Token Authentication All server-side Grain API requests require your API key passed as a Bearer token in the `Authorization` header. ```bash theme={null} curl -X POST https://api.pay.grain.inc/payment-sessions \ -H "Authorization: Bearer your-api-key" \ -H "Content-Type: application/json" \ -d '{"amount": "50.00", "currency": "USD"}' ``` ```typescript theme={null} const response = await fetch("https://api.pay.grain.inc/payment-sessions", { method: "POST", headers: { Authorization: `Bearer ${process.env.CUBEPAY_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ amount: "50.00", currency: "USD" }), }); ``` ## Credential Types Grain uses two types of credentials for different contexts: | Credential | Use | Scope | | --------------------------------------------------- | ------------------------ | --------------------------------------------------------------------- | | **API Key** (`CUBEPAY_API_KEY`) | Server-side only | Create payment sessions, authenticate with the Grain API | | **Merchant ID** (`NEXT_PUBLIC_CUBEPAY_MERCHANT_ID`) | Client-side | Initialize the SDK, identify your merchant account | | **Session Token** (`paymentSessionToken`) | Client-side, per session | Authorize SDK operations and session retrieval for a specific payment | Your **API key** is a server-side secret. Never expose it in client-side code, public repositories, or frontend bundles. If you suspect a key has been compromised, rotate it immediately in the [Grain Dashboard](https://dashboard.grain.inc). ## Session Token Authentication When you create a payment session, the API returns a `paymentSessionToken`. This short-lived token is scoped to a single session and used for: * Opening the SDK payment modal (`sdk.open()`) * Retrieving session details (`GET /api/payment-sessions`) ```typescript theme={null} // Server creates the session const session = await createPaymentSession({ amount: "50.00", currency: "USD" }); // Client uses the session token const result = await sdk.open({ paymentSessionId: session.paymentSessionId, paymentSessionToken: session.paymentSessionToken, }); ``` Session tokens expire automatically and cannot be reused across sessions. Each `POST /payment-sessions` call returns a fresh token. ## Rotate API Keys In the [Grain Dashboard](https://dashboard.grain.inc), go to **Settings > API Keys** and generate a new key. Replace `CUBEPAY_API_KEY` in your environment variables and deploy. Once your application is running with the new key, revoke the old one in the dashboard. ## Next Steps Explore the full list of [Endpoints](/payment-sdk/api-reference/endpoints) available in the Payment SDK API. # Endpoints Source: https://docs.grain.inc/payment-sdk/api-reference/endpoints Complete reference of Payment SDK API endpoints ## Base URL | Environment | Base URL | | ----------- | ----------------------------------- | | Production | `https://api.pay.grain.inc` | | Sandbox | `https://api.sandbox.pay.grain.inc` | *** ## Payment Sessions ### Create Payment Session ``` POST /payment-sessions ``` Create a new payment session. Returns a session ID and token for the client-side SDK. **Headers:** | Header | Value | | --------------- | -------------------------- | | `Authorization` | `Bearer {CUBEPAY_API_KEY}` | | `Content-Type` | `application/json` | **Request Body:** | Parameter | Type | Required | Description | | ----------- | -------- | -------- | ------------------------------------------------------------- | | `amount` | `string` | Yes | Payment amount as a decimal string (e.g., `"50.00"`) | | `currency` | `string` | Yes | Currency code (e.g., `"USD"`) | | `requestId` | `string` | No | Idempotency key — your own UUID to prevent duplicate sessions | **Example:** ```bash theme={null} curl -X POST https://api.pay.grain.inc/payment-sessions \ -H "Authorization: Bearer your-api-key" \ -H "Content-Type: application/json" \ -d '{"amount": "50.00", "currency": "USD", "requestId": "ord_12345"}' ``` **Response** `200 OK`: ```json theme={null} { "paymentSessionId": "ps_abc123def456", "paymentSessionToken": "eyJhbGciOiJIUzI1NiIs...", "amount": "50.00", "currency": "USD", "network": "ETHEREUM", "tokenSymbol": "USDC", "oneTimeWalletAddress": "0x1234...abcd", "userAddress": null, "fundingTransactionHash": null, "status": "PENDING", "createdAt": "2026-03-20T12:00:00Z" } ``` *** ### Get Payment Session ``` GET /payment-sessions/{paymentSessionId} ``` Retrieve the current state of a payment session. **Headers:** | Header | Value | | --------------- | ------------------------------ | | `Authorization` | `Bearer {paymentSessionToken}` | **Example:** ```bash theme={null} curl https://api.pay.grain.inc/payment-sessions/ps_abc123def456 \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." ``` **Response** `200 OK`: ```json theme={null} { "paymentSessionId": "ps_abc123def456", "status": "FUNDED", "amount": "50.00", "currency": "USD", "network": "ETHEREUM", "tokenSymbol": "USDC", "userAddress": "0xCustomerWallet...", "oneTimeWalletAddress": "0xOTW...", "fundingTransactionHash": "0xabc123...", "userSubmittedTransactionHash": "0xdef456...", "createdAt": "2026-03-20T12:00:00Z" } ``` *** ## Captures ### Create Capture ``` POST /api/v1/payment-sessions/{paymentSessionId}/captures ``` Transfer funds from the one-time wallet (OTW) to your treasury wallet. Supports partial and final captures. Only available when the session status is `FUNDED`. **Headers:** | Header | Value | | --------------- | -------------------------- | | `Authorization` | `Bearer {CUBEPAY_API_KEY}` | | `Content-Type` | `application/json` | **Request Body:** | Parameter | Type | Required | Description | | ---------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------ | | `requestId` | `string` | Yes | Idempotency key to prevent duplicate captures | | `captureAmount` | `string` | Yes | Amount to capture (e.g., `"50.00"`) | | `isFinalCapture` | `boolean` | No | Default `false`. When `true`, remaining balance is refunded to the customer and session moves to `SUCCEEDED` | **Example:** ```bash theme={null} curl -X POST https://api.pay.grain.inc/api/v1/payment-sessions/ps_abc123def456/captures \ -H "Authorization: Bearer your-api-key" \ -H "Content-Type: application/json" \ -d '{"requestId": "cap_ord_12345", "captureAmount": "50.00", "isFinalCapture": true}' ``` **Response** `202 Accepted`: ```json theme={null} { "captureId": "cap_xyz789", "captureAmount": "50.00", "refundAmount": "0.00", "status": "CAPTURING" } ``` *** ### Get Capture ``` GET /api/v1/payment-sessions/{paymentSessionId}/captures/{captureId} ``` Check the status of a capture operation. **Headers:** | Header | Value | | --------------- | -------------------------- | | `Authorization` | `Bearer {CUBEPAY_API_KEY}` | **Example:** ```bash theme={null} curl https://api.pay.grain.inc/api/v1/payment-sessions/ps_abc123def456/captures/cap_xyz789 \ -H "Authorization: Bearer your-api-key" ``` **Response** `200 OK`: ```json theme={null} { "captureId": "cap_xyz789", "status": "CAPTURED", "captureAmount": "50.00", "refundAmount": "0.00", "captureTransferTransactionHash": "0xcapture123...", "refundTransferTransactionHash": null } ``` ### Capture Object | Field | Type | Description | | -------------------------------- | ---------------- | ---------------------------------------------------- | | `captureId` | `string` | Unique capture identifier | | `status` | `string` | `CAPTURING` (in progress) or `CAPTURED` (complete) | | `captureAmount` | `string` | Amount captured | | `refundAmount` | `string` | Amount refunded to customer (on final capture) | | `captureTransferTransactionHash` | `string \| null` | On-chain hash of the capture transfer | | `refundTransferTransactionHash` | `string \| null` | On-chain hash of the refund transfer (if applicable) | *** ## Webhooks ### Payment Status Update ``` POST {your-webhook-url} ``` Grain sends payment status updates to your registered webhook URL as JSON-RPC 2.0 requests. **Payload:** ```json theme={null} { "jsonrpc": "2.0", "id": "1770947403693", "method": "cubepay_paymentStatusUpdate", "params": [ { "merchantId": "your-merchant-id", "paymentSessionId": "ps_abc123def456", "status": "FUNDED", "updatedAt": "2026-03-20T12:05:00Z" } ] } ``` **Status Values:** | Status | Description | | ----------- | ------------------------------------------------------------- | | `CREATED` | Session created, customer has not connected a wallet yet | | `PENDING` | Wallet connected, awaiting funding transaction | | `FUNDED` | Funds received at the one-time wallet — ready to capture | | `CAPTURING` | Capture in progress (funds being transferred) | | `SUCCEEDED` | Final capture complete — funds settled to your treasury | | `CANCELED` | Session expired or was cancelled (not funded within 24 hours) | | `ERROR` | An error occurred during processing | **Expected Response:** Return `200` with a JSON-RPC acknowledgment: ```json theme={null} { "jsonrpc": "2.0", "result": "ok" } ``` *** ## Response Fields Reference ### Payment Session Object | Field | Type | Description | | ------------------------------ | ---------------- | ---------------------------------------------------------------------- | | `paymentSessionId` | `string` | Unique session identifier | | `paymentSessionToken` | `string` | Short-lived token for client-side operations | | `amount` | `string` | Payment amount | | `currency` | `string` | Currency code | | `network` | `string` | Blockchain network (e.g., `ETHEREUM`, `SEPOLIA`) | | `tokenSymbol` | `string` | Token used for payment (e.g., `USDC`) | | `oneTimeWalletAddress` | `string` | Unique receiving address for this session | | `userAddress` | `string \| null` | Customer's wallet address (populated after connection) | | `fundingTransactionHash` | `string \| null` | Transaction hash of the funding transfer | | `userSubmittedTransactionHash` | `string \| null` | Transaction hash as submitted by the user's wallet | | `capturableAmount` | `string` | Remaining balance available for capture | | `capturedAmount` | `string` | Total amount captured so far | | `captures` | `array` | Array of capture operations with their statuses and transaction hashes | | `status` | `string` | Current session status | | `createdAt` | `string` | ISO 8601 creation timestamp | All endpoints require [authentication](/payment-sdk/api-reference/authentication). See [Error Codes](/payment-sdk/api-reference/error-codes) for error response formats. # Error Codes Source: https://docs.grain.inc/payment-sdk/api-reference/error-codes Reference of Payment SDK API and error codes ## HTTP Error Responses All API errors return a JSON response with an error message. ```json theme={null} { "error": "The 'amount' field is required." } ``` ### Status Codes | Status | Description | Resolution | | ------ | ------------------------------------------------------------------- | ------------------------------------------------------------------- | | `400` | Invalid request — malformed body, missing fields, or invalid values | Check that `amount` is a positive number and `currency` is provided | | `401` | Unauthorized — API key is missing, invalid, or revoked | Verify your `CUBEPAY_API_KEY` environment variable | | `500` | Internal server error | Retry with exponential backoff | | `502` | Bad gateway — upstream payment service unavailable | The Grain API is temporarily unreachable. Retry shortly | *** ## SDK Errors These errors are thrown by the client-side SDK service during payment execution. ### CubePayClosedError Thrown when the user closes the payment modal without completing the transaction. This is **not a failure** — it indicates the user chose to cancel. ```typescript theme={null} try { const result = await cubePayService.executePayment({ amount: 50, currency: "USD" }); } catch (error) { if (error.name === "CubePayClosedError") { // User cancelled — handle gracefully return; } throw error; } ``` ### Initialization Errors | Error Message | Cause | Resolution | | -------------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------------------- | | `NEXT_PUBLIC_CUBEPAY_MERCHANT_ID is not set` | Missing merchant ID environment variable | Add the variable to your `.env` file | | `Missing CubePay container element with id 'cubepay-sdk-root'` | Mount point not in the DOM | Add `
` to your layout | | `Failed to load Cubist Pay SDK script` | SDK bundle not found or failed to load | Verify `public/vendor/cubist-pay-client-sdk.umd.js` exists | | `Failed to load Cubist Pay SDK` | `window.CubePaySDK` not available after script loaded | Check the browser console for script errors | ### Session Creation Errors | Error Message | Cause | Resolution | | ---------------------------------- | ---------------------------------------------- | --------------------------------------------------- | | `Amount must be a positive number` | Invalid amount (zero, negative, NaN, Infinity) | Validate the amount before calling `executePayment` | | `Failed to create payment session` | Server returned a non-2xx response | Check server logs for the upstream API error | | `Payment service unavailable` | Network error or API timeout | Retry the request | *** ## Webhook Error Handling Your webhook endpoint should always return `200` regardless of internal processing status: ```typescript theme={null} export async function POST(request: Request) { try { const body = await request.json(); await processWebhook(body); } catch (error) { // Log but don't return an error status console.error("Webhook processing failed:", error); } // Always acknowledge receipt return NextResponse.json({ jsonrpc: "2.0", result: "ok" }); } ``` Returning a non-2xx status causes the payment service to retry webhook delivery. Always return `200` to prevent duplicate processing. *** ## Debugging Tips The SDK logs initialization steps and errors to the browser console. Open DevTools and filter for "CubePay" or "cubepay" messages. Missing or incorrect environment variables are the most common cause of SDK failures. Double-check that `NEXT_PUBLIC_CUBEPAY_MERCHANT_ID` is set on the client and `CUBEPAY_API_KEY` is set on the server. When `CUBEPAY_API_KEY` is absent and `NODE_ENV` is not `production`, the SDK returns mock data. This is useful for isolating whether an issue is in your code or the API integration. Use the browser Network tab to inspect requests to `/api/payment-sessions`. Check that the request body is valid JSON and the response contains `paymentSessionId` and `paymentSessionToken`. # Installation & Setup Source: https://docs.grain.inc/payment-sdk/installation-setup Set up the Payment SDK in your application ## Prerequisites * A Grain merchant account with a **Merchant ID** * A server-side **API key** for creating payment sessions * Node.js 18+ (for Next.js applications) ## Get Your Credentials Log in to the [Grain Dashboard](https://dashboard.grain.inc) and navigate to **Settings > API Keys**. Copy your **Merchant ID** — this is used to initialize the client-side SDK. From the same page, copy your **API Key**. This is your server-side secret used to create payment sessions. Never expose your API key in client-side code. It should only be used in server-side route handlers or backend services. ## Configure Environment Variables Add the following to your `.env` file: ```bash theme={null} # Required NEXT_PUBLIC_CUBEPAY_MERCHANT_ID=your-merchant-id # Client-side: SDK initialization CUBEPAY_API_KEY=your-api-key # Server-side: session creation # Optional CUBEPAY_API_HOST=https://api.pay.grain.inc # API host (defaults to production) ``` ## Add the SDK Mount Point The Payment SDK renders its payment modal inside a dedicated DOM element. Add this to your root layout: ```tsx theme={null} // app/layout.tsx export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children}
); } ``` The SDK creates a **Shadow DOM** inside this element, so its styles are fully isolated from your application. No CSS conflicts. ## Load the SDK Bundle The client-side SDK is distributed as a UMD bundle. Place it in your public directory: ``` public/ vendor/ cubist-pay-client-sdk.umd.js ``` The SDK service loads this script lazily on first use — no manual script tags needed. ## Environment Comparison | Feature | Sandbox | Production | | ------------------- | --------------------------- | ------------------------- | | Blockchain networks | Testnets (Sepolia) | Mainnets (Ethereum, Base) | | Real funds | No | Yes | | Webhooks | Supported | Supported | | Settlement | Simulated | Real on-chain settlement | | API host | `api.sandbox.pay.grain.inc` | `api.pay.grain.inc` | ## Next Steps Proceed to [Initialize the SDK](/payment-sdk/integration-guide/initialize-sdk) to set up the SDK service and process your first payment. # Create a Payment Session Source: https://docs.grain.inc/payment-sdk/integration-guide/create-payment-session Generate a payment session and launch the payment modal ## Server-Side: Create a Session Create payment sessions from your backend using your API key. This returns a session ID and token that the client uses to open the payment modal. ```typescript theme={null} // app/api/payment-sessions/route.ts (Next.js App Router) import { NextResponse } from "next/server"; export async function POST(request: Request) { const { amount, currency, requestId } = await request.json(); const response = await fetch(`${process.env.CUBEPAY_API_HOST}/payment-sessions`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.CUBEPAY_API_KEY}`, }, body: JSON.stringify({ amount: String(amount), currency: currency || "USD", requestId, }), }); const session = await response.json(); return NextResponse.json({ paymentSessionId: session.paymentSessionId, paymentSessionToken: session.paymentSessionToken, }); } ``` ### Request Parameters | Parameter | Type | Required | Description | | ----------- | -------- | -------- | ------------------------------------------------------------------ | | `amount` | `string` | Yes | Payment amount as a decimal string (e.g., `"50.00"`) | | `currency` | `string` | Yes | Currency code (e.g., `"USD"`) | | `requestId` | `string` | No | Idempotency key — pass your own UUID to prevent duplicate sessions | ### Response ```json theme={null} { "paymentSessionId": "ps_abc123def456", "paymentSessionToken": "eyJhbGciOiJIUzI1NiIs...", "amount": "50.00", "currency": "USD", "network": "SEPOLIA", "tokenSymbol": "USDC", "oneTimeWalletAddress": "0x1234...abcd", "status": "PENDING", "createdAt": "2026-03-20T12:00:00Z" } ``` The `paymentSessionToken` is a short-lived credential scoped to this session. Pass it to the client, but never log or store it permanently. *** ## Client-Side: Launch the Payment Modal Pass the session credentials to the SDK service to open the payment modal. ```typescript theme={null} import { cubePayService } from "@/services/cubepay-sdk"; async function handlePayment(amount: number) { try { const result = await cubePayService.executePayment({ amount, currency: "USD", }); // Payment succeeded console.log("Transaction hash:", result.transactionHash); console.log("Session:", result.session); } catch (error) { // Payment failed or was cancelled console.error("Payment error:", error); } } ``` ### What `executePayment` Does The `executePayment` method handles the full payment lifecycle: Calls your server's `POST /api/payment-sessions` endpoint with the amount and currency. Loads the SDK bundle (if not already loaded) and initializes it with your merchant configuration. Calls `sdk.open()` with the session ID and token. The customer sees the payment modal with wallet options. On success, returns the transaction hash and session details. On cancellation, throws a `CubePayClosedError`. ## Using in a React Component ```tsx theme={null} "use client"; import { useState } from "react"; import { cubePayService } from "@/services/cubepay-sdk"; export function PayButton({ amount }: { amount: number }) { const [loading, setLoading] = useState(false); const handleClick = async () => { setLoading(true); try { const result = await cubePayService.executePayment({ amount, currency: "USD", }); // Redirect to success page or update UI window.location.href = `/success?tx=${result.transactionHash}`; } catch (error) { if (error.name === "CubePayClosedError") { // User closed the modal — not an error console.log("Payment cancelled by user"); } else { console.error("Payment failed:", error.message); } } finally { setLoading(false); } }; return ( ); } ``` The SDK modal supports both mobile (drawer) and desktop (dialog) layouts automatically based on viewport size. ## Next Steps Learn how to [Handle Payment Completion](/payment-sdk/integration-guide/handle-payment-completion) and confirm payments via webhooks. # Handle Errors & Edge Cases Source: https://docs.grain.inc/payment-sdk/integration-guide/handle-errors Gracefully handle payment failures, cancellations, and edge cases ## User Closes the Modal When a customer closes the payment modal without completing, the SDK throws a `CubePayClosedError`. This is not a failure — it means the user chose to cancel. ```typescript theme={null} try { const result = await cubePayService.executePayment({ amount: 50.0, currency: "USD", }); } catch (error) { if (error.name === "CubePayClosedError") { // User closed the modal — not an error console.log("Payment flow cancelled by user"); return; } // Actual error console.error("Payment failed:", error.message); } ``` Always check for `CubePayClosedError` before treating a thrown error as a failure. This is the most common "error" you will encounter. *** ## Client-Side Errors | Error | Cause | Resolution | | -------------------------- | -------------------------------------------------------------- | --------------------------------------------------------- | | `CubePayClosedError` | User closed the payment modal | Let the user retry when ready | | Missing merchant ID | `NEXT_PUBLIC_CUBEPAY_MERCHANT_ID` not set | Add the environment variable | | Missing container | `#cubepay-sdk-root` element not in DOM | Add the mount point to your layout | | Script load failure | SDK bundle not found at `/vendor/cubist-pay-client-sdk.umd.js` | Verify the file exists in your `public/vendor/` directory | | SDK initialization failure | `window.CubePaySDK` not available after script load | Check for script loading errors in the browser console | *** ## Server-Side Errors ### Session Creation Errors | HTTP Status | Cause | Resolution | | ----------- | -------------------------------------------------- | ------------------------------------------------------------------- | | `400` | Invalid request body or missing fields | Check that `amount` is a positive number and `currency` is provided | | `400` | Amount is not a valid number, is zero, or negative | Validate the amount before sending | | `401` | Invalid or missing API key | Verify `CUBEPAY_API_KEY` in your environment | | `500` | Internal server error | Retry with exponential backoff | | `502` | Upstream API unavailable | The payment service is temporarily unreachable — retry shortly | ### Handling Server Errors ```typescript theme={null} export async function POST(request: Request) { const { amount, currency } = await request.json(); // Validate before calling the API const numericAmount = parseFloat(amount); if (isNaN(numericAmount) || !isFinite(numericAmount) || numericAmount <= 0) { return NextResponse.json( { error: "Amount must be a positive number" }, { status: 400 } ); } try { const response = await fetch(`${process.env.CUBEPAY_API_HOST}/payment-sessions`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.CUBEPAY_API_KEY}`, }, body: JSON.stringify({ amount: String(numericAmount), currency }), }); if (!response.ok) { const errorData = await response.json().catch(() => null); return NextResponse.json( { error: errorData?.message || "Failed to create session" }, { status: response.status } ); } return NextResponse.json(await response.json()); } catch (error) { return NextResponse.json( { error: "Payment service unavailable" }, { status: 502 } ); } } ``` *** ## Webhook Error Handling Design your webhook handler to be **idempotent** and always return `200`: ```typescript theme={null} export async function POST(request: Request) { try { const body = await request.json(); const { method, params } = body; if (method === "cubepay_paymentStatusUpdate") { await processStatusUpdate(params[0]); } } catch (error) { // Log the error but still return 200 console.error("Webhook processing error:", error); } return NextResponse.json({ jsonrpc: "2.0", result: "ok" }); } ``` If your webhook handler returns a non-2xx status code, the payment service will retry delivery. Return `200` even when your internal processing fails to avoid duplicate deliveries. *** ## Next Steps Set up your [Sandbox Environment](/payment-sdk/testing/test-in-sandbox) to test the full payment flow with test networks. # Handle Payment Completion Source: https://docs.grain.inc/payment-sdk/integration-guide/handle-payment-completion Process successful payments, capture funds, and confirm via webhooks ## Client-Side: Transaction Hash When a customer completes the payment modal, `executePayment` resolves with the funding transaction details. At this point the session status is `FUNDED` — funds are sitting in the one-time wallet (OTW), ready for you to capture. ```typescript theme={null} const result = await cubePayService.executePayment({ amount: 50.0, currency: "USD", }); console.log(result.transactionHash); // "0xabc123..." console.log(result.session); // { paymentSessionId, status: "FUNDED", ... } ``` ### Result Object | Field | Type | Description | | ----------------- | -------- | ------------------------------------------------------------ | | `transactionHash` | `string` | On-chain funding transaction hash | | `session` | `object` | Full session details (ID, status, network, token, addresses) | | `details` | `object` | Additional session metadata | `FUNDED` does not mean the payment is complete. You must **capture** the funds to transfer them from the OTW to your treasury wallet. *** ## Capture the Payment Once a session is `FUNDED`, your server calls the capture endpoint to move funds from the one-time wallet to your treasury wallet. Capture supports both full and partial amounts. ### Capture Request ```typescript theme={null} // Server-side: capture the full payment const captureResponse = await fetch( `${process.env.CUBEPAY_API_HOST}/api/v1/payment-sessions/${paymentSessionId}/captures`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.CUBEPAY_API_KEY}`, }, body: JSON.stringify({ requestId: "capture_ord_12345", // idempotency key captureAmount: "50.00", // amount to capture isFinalCapture: true, // true = capture + refund remaining balance }), } ); const capture = await captureResponse.json(); // { captureId: "cap_xyz", captureAmount: "50.00", refundAmount: "0.00", status: "CAPTURING" } ``` ### Capture Parameters | Parameter | Type | Required | Description | | ---------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------------- | | `requestId` | `string` | Yes | Idempotency key to prevent duplicate captures | | `captureAmount` | `string` | Yes | Amount to capture (e.g., `"50.00"`) | | `isFinalCapture` | `boolean` | No | Default `false`. When `true`, any remaining balance is refunded to the customer and the session moves to `SUCCEEDED` | ### Capture Response ```json theme={null} { "captureId": "cap_xyz789", "captureAmount": "50.00", "refundAmount": "0.00", "status": "CAPTURING" } ``` Capture is an **async operation**. The response returns immediately with status `CAPTURING`. You receive a webhook when the capture completes. ### Partial vs Final Capture Capture a portion of the funded amount. The session returns to `FUNDED` and remains open for additional captures. ```json theme={null} { "captureAmount": "25.00", "isFinalCapture": false } ``` Capture the remaining amount (or a specific amount) and close the session. Any uncaptured balance is refunded to the customer. ```json theme={null} { "captureAmount": "25.00", "isFinalCapture": true } ``` ### Check Capture Status ```typescript theme={null} const status = await fetch( `${process.env.CUBEPAY_API_HOST}/api/v1/payment-sessions/${paymentSessionId}/captures/${captureId}`, { headers: { Authorization: `Bearer ${process.env.CUBEPAY_API_KEY}` }, } ); ``` **Response:** ```json theme={null} { "captureId": "cap_xyz789", "status": "CAPTURED", "captureAmount": "50.00", "refundAmount": "0.00", "captureTransferTransactionHash": "0xcapture123...", "refundTransferTransactionHash": null } ``` | Field | Type | Description | | -------------------------------- | ---------------- | ---------------------------------------------- | | `captureId` | `string` | Unique capture identifier | | `status` | `string` | `CAPTURING` or `CAPTURED` | | `captureAmount` | `string` | Amount captured | | `refundAmount` | `string` | Amount refunded to customer (on final capture) | | `captureTransferTransactionHash` | `string \| null` | On-chain hash of the capture transfer | | `refundTransferTransactionHash` | `string \| null` | On-chain hash of the refund transfer | *** ## Fetch Session Details After funding or capture, retrieve the full session state: ```typescript theme={null} const response = await fetch( `${process.env.CUBEPAY_API_HOST}/payment-sessions/${sessionId}`, { headers: { Authorization: `Bearer ${paymentSessionToken}` }, } ); ``` The response includes `capturableAmount`, `capturedAmount`, and a `captures` array tracking all capture operations. *** ## Server-Side: Webhook Confirmation Never rely solely on client-side results to fulfill orders. Always confirm payments server-side via webhooks. ### Register Your Webhook Endpoint Configure your webhook URL in the [Grain Dashboard](https://dashboard.grain.inc) under **Settings > Webhooks**. ### Handle the Webhook Grain sends payment status updates as **JSON-RPC 2.0** requests: ```typescript theme={null} // app/api/transactions/webhook/route.ts import { NextResponse } from "next/server"; export async function POST(request: Request) { const body = await request.json(); const { method, params } = body; if (method === "cubepay_paymentStatusUpdate") { const update = params[0]; switch (update.status) { case "FUNDED": // Customer funded the OTW — ready to capture await initiateCapture(update.paymentSessionId); break; case "CAPTURING": // Capture in progress console.log("Capture in progress:", update.paymentSessionId); break; case "SUCCEEDED": // Final capture complete — funds in your treasury await confirmSettlement(update.paymentSessionId); break; case "CANCELED": await handleCancellation(update.paymentSessionId); break; case "ERROR": await handlePaymentError(update.paymentSessionId); break; } } // Always return 200 to acknowledge receipt return NextResponse.json({ jsonrpc: "2.0", result: "ok" }); } ``` ### Webhook Payload ```json theme={null} { "jsonrpc": "2.0", "id": "1770947403693", "method": "cubepay_paymentStatusUpdate", "params": [ { "merchantId": "your-merchant-id", "paymentSessionId": "ps_abc123def456", "status": "FUNDED", "updatedAt": "2026-03-20T12:05:00Z" } ] } ``` ## Payment Status Lifecycle ``` CREATED → PENDING → FUNDED → CAPTURING → SUCCEEDED | | | ↓ ↓ ↓ CANCELED CANCELED FUNDED (partial capture) ``` | Status | Meaning | | ----------- | ------------------------------------------------------------- | | `CREATED` | Session created, customer has not connected a wallet yet | | `PENDING` | Wallet connected, awaiting funding transaction | | `FUNDED` | Funds received at the one-time wallet — ready to capture | | `CAPTURING` | Capture in progress (funds being transferred) | | `SUCCEEDED` | Final capture complete — funds settled to your treasury | | `CANCELED` | Session expired or was cancelled (not funded within 24 hours) | | `ERROR` | An error occurred during processing | Always return a `200` status from your webhook handler, even if your internal processing fails. This prevents unnecessary retries. Handle errors asynchronously. ## Next Steps Learn how to [Handle Errors & Edge Cases](/payment-sdk/integration-guide/handle-errors) for robust payment flows. # Initialize the SDK Source: https://docs.grain.inc/payment-sdk/integration-guide/initialize-sdk Set up the Payment SDK service in your application ## SDK Service The Payment SDK uses a singleton service that handles script loading, initialization, and payment execution. Import and use it directly in your components. ```typescript theme={null} import { cubePayService } from "@/services/cubepay-sdk"; ``` The service: * **Lazy-loads** the SDK bundle on first use (no upfront script loading) * **Initializes once** and reuses the same instance across your app * Creates a **Shadow DOM** inside the `#cubepay-sdk-root` element for style isolation ## Initialization Flow When you call `executePayment()` for the first time, the service automatically: Injects `/vendor/cubist-pay-client-sdk.umd.js` into the page and waits for `window.CubePaySDK` to become available. Calls `CubePaySDK.init()` with your merchant ID, the container element, and optional configuration (RPC endpoints, theme variables). The initialized SDK instance is cached. All subsequent calls reuse it without re-initialization. ## Configuration Options The SDK reads configuration from environment variables automatically. You can customize behavior through these settings: | Option | Environment Variable | Description | | ----------- | --------------------------------- | ---------------------------------------------- | | Merchant ID | `NEXT_PUBLIC_CUBEPAY_MERCHANT_ID` | **Required.** Identifies your merchant account | ## Theme Customization The SDK applies CSS custom properties to the payment modal. Override these in your `#cubepay-sdk-root` element to match your brand: ```css theme={null} .cubepay-sdk-root { --tint: #2563eb; --background: #ffffff; --background-secondary: #f8fafc; --background-tertiary: #f1f5f9; --label: #0f172a; --label-secondary: #475569; --label-tertiary: #64748b; --label-quaternary: #94a3b8; --system-blue: #2563eb; --separator: rgba(15, 23, 42, 0.08); } ``` Override `--tint` and `--system-blue` to change the primary accent color of the payment modal to match your brand. ## Next Steps Create your first [Payment Session](/payment-sdk/integration-guide/create-payment-session). # Overview Source: https://docs.grain.inc/payment-sdk/overview Introduction to the Payment SDK — accept crypto payments in your application ## What is the Payment SDK? The Payment SDK is a drop-in SDK that lets you accept cryptocurrency payments directly in your application. It handles wallet connections, network selection, transaction signing, and payment confirmation — so you can focus on your product. The SDK renders inside a **Shadow DOM modal** for complete style isolation, supports multiple wallet providers, and works with any JavaScript framework. ```typescript theme={null} // 1. Create a session on your server const session = await fetch("/api/payment-sessions", { method: "POST", body: JSON.stringify({ amount: "50.00", currency: "USD" }), }); // 2. Open the payment modal on the client const transactionHash = await sdk.open({ paymentSessionId: session.paymentSessionId, paymentSessionToken: session.paymentSessionToken, }); ``` ## How It Works Call the Grain API from your backend with the payment amount and currency. You receive a `paymentSessionId` and `paymentSessionToken`. Pass the session credentials to the client-side SDK. It opens a modal where the customer selects a wallet, connects, and approves the transaction. Each session gets a unique one-time wallet (OTW) address. The customer's funds are sent to this address. The session status moves to `FUNDED`. Once funded, your server calls the capture endpoint to transfer funds from the OTW to your treasury wallet. You can capture the full amount or do partial captures. The SDK returns the transaction hash on success. Your server receives webhooks as the session moves through `FUNDED` → `CAPTURING` → `SUCCEEDED`. ## Key Features * **Drop-in modal** — Shadow DOM-based payment UI with full style isolation. No CSS conflicts with your application. * **Multi-wallet support** — WalletConnect, injected wallets (MetaMask, Coinbase Wallet), and more out of the box. * **Payment methods** — Crypto (stablecoins) with additional methods coming soon. * **One-time wallets** — Every payment session gets a unique receiving address for clean reconciliation. * **Flexible capture** — Capture the full amount or do partial captures. Final capture automatically refunds any remaining balance to the customer. * **Webhook confirmations** — Receive server-side status updates via JSON-RPC 2.0 webhooks. * **Customizable theme** — Match the payment modal to your brand with CSS custom properties. ## Payment Methods | Method | Description | Settlement | | ---------- | --------------------------------------------------------------- | ---------- | | **Crypto** | Customer pays with stablecoins (USDC) from any supported wallet | On-chain | ## Next Steps Get up and running in minutes. Follow the [Installation & Setup](/payment-sdk/installation-setup) guide to add the SDK to your project, then walk through the [Integration Guide](/payment-sdk/integration-guide/initialize-sdk) to process your first payment. # Test in Sandbox Source: https://docs.grain.inc/payment-sdk/testing/test-in-sandbox Validate your integration using the Grain sandbox environment ## Configure for Sandbox Point the SDK to the sandbox API by setting the host environment variable: ```bash theme={null} CUBEPAY_API_HOST=https://api.sandbox.pay.grain.inc ``` All other environment variables (`NEXT_PUBLIC_CUBEPAY_MERCHANT_ID`, `CUBEPAY_API_KEY`) use your sandbox credentials from the [Grain Dashboard](https://dashboard.grain.inc). *** ## Run an End-to-End Test Use your server to create a session against the sandbox API. ```bash theme={null} curl -X POST https://api.sandbox.pay.grain.inc/payment-sessions \ -H "Authorization: Bearer your-sandbox-api-key" \ -H "Content-Type: application/json" \ -d '{"amount": "10.00", "currency": "USD"}' ``` Launch the SDK on the client with the returned session credentials. In sandbox, the SDK connects to test blockchain networks (Sepolia) automatically. Connect a wallet funded with testnet tokens and approve the transaction. The SDK handles network switching automatically. Go to the [Grain Dashboard](https://dashboard.grain.inc) and navigate to **Transactions**. Confirm your test payment appears with the expected status. *** ## Test Webhook Delivery Sandbox webhooks work identically to production. Configure your webhook URL in the dashboard and use a tunneling tool to receive webhooks locally: ```bash theme={null} # Expose your local server ngrok http 3000 ``` Then update your webhook URL in the Grain Dashboard to point to your ngrok URL: ``` https://your-subdomain.ngrok.io/api/transactions/webhook ``` ### Simulate Payment Statuses Each webhook delivery contains a `status` field. In sandbox, payments progress through the full lifecycle: | Status | When It Fires | | ----------- | ---------------------------------------------- | | `PENDING` | Session created | | `FUNDED` | Testnet tokens received at the one-time wallet | | `SUCCEEDED` | Simulated sweep to settlement | | `CANCELED` | Payment cancelled (timeout or user action) | | `ERROR` | Simulated error condition | Verify your webhook handler processes each status correctly by monitoring your server logs as you complete test payments. *** ## Sandbox vs Production | Behavior | Sandbox | Production | | ------------------ | --------------------------- | -------------------------- | | Blockchain network | Sepolia (testnet) | Ethereum, Base (mainnet) | | Tokens | Test USDC (no real value) | Real USDC | | Settlement | Simulated | Real on-chain settlement | | Webhooks | Delivered to your endpoint | Delivered to your endpoint | | API host | `api.sandbox.pay.grain.inc` | `api.pay.grain.inc` | Always test the full payment flow in sandbox before switching to production. Verify that your webhook handler, success screen, and error handling all work as expected. # Complaints Source: https://docs.grain.inc/support/complaints How to submit a complaint and what to expect Your satisfaction matters. We are committed to providing you with great service, and that means we need to know when we get things wrong. We want to help resolve your complaint as quickly as possible. We treat any expression of dissatisfaction with our services or products as a complaint and will aim to respond. We listen to your complaints, treat them seriously, and learn from them so that we can continuously improve Grain. ## Submitting a Complaint Submit your complaint through our **[online complaint form](https://forms.gle/41qKGk1WojkAS8EB7)**. The form will guide you through the information we need to get started. For additional questions about an existing complaint, please reach out to **[complaints@grain.inc](mailto:complaints@grain.inc)**. ## What to Expect We will confirm receipt of your complaint promptly and provide you with a reference number for tracking. Our team will review the details of your complaint. We may reach out to you for additional information if needed. We will provide you with a response outlining our findings and any actions we have taken to address your complaint. If you are not satisfied with the outcome, we will explain the next steps available to you, including any escalation options. # Release Notes Source: https://docs.grain.inc/support/release-notes Latest updates and changes to the Grain platform Subscribe to release notifications in your Dashboard under **Settings > Notifications** to get notified when new versions are published. ### v0.12.1 --- September 4, 2026 **Improved** * Payment links are now served from `pay.grain.inc` under your partner slug. *** ### v0.12.0 --- September 4, 2026 **Added** * **Billing & Payouts** settings section in the Dashboard. **Improved** * Grain Pay overhaul — new payment-link URLs and reorganized checkout routes. *** ### v0.11.0 --- August 31, 2026 **Added** * Adverse media and PEP screening now run as part of KYB submission. **Improved** * The KYB save button sits beside the next button, and summary details collapse fully. **Fixed** * Session churn that forced constant re-authentication, and the KYB 403 errors it caused. * A failed database write no longer sends a KYB invite email anyway. * A stale modified timestamp that silently blocked saving your KYB progress. * Only document keys matching the selected document type are submitted. *** ### v0.10.0 – v0.10.2 --- August 26–27, 2026 **Added** * Invoices section and sidebar navigation in the Dashboard. * Transaction details now show the asset and network used. * Email alerts when a transaction settles. * KYB invite emails. **Improved** * KYB authenticates through your Dashboard login rather than an invite token, and autosaves when the page loads. * Payment pages gained an Address Line 2 field, thousands separators in amounts, and address autocomplete limited to street addresses. * Consistent money formatting across the Dashboard and payment pages. * Unified toast notifications throughout KYB. **Fixed** * Over-eager Dashboard re-authentication. * Payment notification email formatting. * Dropdowns no longer clear your typed value when reopened. *** ### v0.9.0 – v0.9.2 --- August 13–20, 2026 **Added** * Submit a transaction hash to speed up payment processing. **Improved** * Monetary amounts are handled in minor units for exact precision. * Payments now complete correctly even if the customer closes the page after the confirmation screen. **Changed** * Automatic Erebor onboarding removed from the Middesk webhook; the `kyb_status` field is gone. *** ### v0.8.0 – v0.8.1 --- August 11–13, 2026 **Added** * Multi-factor authentication with preferred and fallback methods. * Reset password and MFA code emails. **Changed** * KYB submission can be finalized without waiting on Middesk success. *** ### v0.7.0 – v0.7.1 --- July 28–29, 2026 **Added** * Blocked-account email template. **Improved** * Coinbase Wallet now behaves like any other wallet at checkout. * Payouts are generally available — the feature flag is removed. **Fixed** * A race between the funding webhook and payment submission that stranded auto-capture. * Deleting a payment from the Dashboard. * Restored the "This field is required" message in place of an unclear error. *** ### v0.6.0 --- July 23, 2026 **Added** * Notes on payments. **Improved** * Manual payments are now called **invoices** throughout. * A payment session in `PENDING` now displays as `CREATED` in the Dashboard. **Fixed** * Recent transactions and payout summary modules. * Filter status names now match transaction labels. * Address autocomplete and the country dropdown on the create payment form. * Invoice bugs surfaced by the payments service refactor. * `/payment` and `/payments` now redirect to the base URL. * Auth0 signup redirect loop and stale session handling. * Cross-origin payment deletion. *** ### v0.5.0 – v0.5.3 --- July 14–21, 2026 **Added** * Passkey and security key autoprompt at login. * `dashboard_status` on payments. **Fixed** * Payout summary and Dashboard statuses now window on the correct timestamp. *** ### v0.4.0 --- July 10, 2026 **Added** * Manual payments end to end — create and edit from the Dashboard, with a payment details panel and reusable templates. * White-label payment page at `/pay/[token]`. * Payment link template endpoints. * Per-partner checkout configuration resolved by slug. **Improved** * Shared dropdown component across the Dashboard and payment pages. * "Powered by Grain" mark on the payment page. * Create Payment form UX. *** ### 0.3.0 – 0.3.3 --- June 30 – July 8, 2026 **Added** * Invite team members to your organization. * Add and update your partner bank account. * An organization is created automatically when a partner is created. **Improved** * Auto-capture v2. * Identity verification during KYB is now best-effort and no longer blocks finalizing your profile. **Fixed** * Fee calculation now activates when a payment reaches `SUCCEEDED`. *** ### 0.2.0 --- June 15, 2026 **Added** * Dashboard overhaul, including a rebuilt transaction list. * Plaid bank connection. * Multi-organization support. * Passkey authentication screens and custom login pages. * KYB clickwrap consent recording. * Solana and Coinbase Wallet support at checkout. * Merchant-specific networks and tokens on the payment page. **Improved** * Payment SDK separated into its own package and hardened over two QA rounds. * KYB flow — address autocomplete, phone number input, and review page. * PO boxes are flagged during address entry. **Security** * Fixed merchant API key exposure in the Payment SDK. * Added IP and VPN detection with sanctioned-country blocking at checkout. *** ### 0.1.0 --- May 20, 2026 **Added** * KYB onboarding with Middesk and Erebor — business and person applicants, onboarding flows, and document upload. * Fee computation covering Grain fees, network fees, and net payout based on your take rate. * Payment records with currency, network and token detail, fee breakdown, and net payout. * Grain Pay checkout with QR code generation. * Dashboard login. **Fixed** * Payment processing uses the specified amount rather than a hardcoded default. # System Status Source: https://docs.grain.inc/support/system-status Check the current operational status of Grain services ## Status Page You can view the real-time operational status of all Grain services at our dedicated status page: Visit **status.grain.inc** to see current uptime, ongoing incidents, and scheduled maintenance windows. ## Monitored Services Grain continuously monitors the following core services: ### API The Grain REST API that powers payment creation, refunds, webhooks, and all programmatic interactions. This is the service your integration communicates with directly. ### Dashboard The web-based merchant dashboard used for managing settings, viewing transactions, generating reports, and accessing support. ### Website The public-facing Grain website. This covers availability and performance of the main Grain site. If the API is operational but you are experiencing issues, the problem is likely related to your integration configuration. Please contact us to investigate any issues.