# Cancel Payment Link Source: https://docs.withgale.com/api-reference/endpoint/cancel-payment-link POST /api/v2/payment-links/{id}/cancel Cancel an active payment link # Cancel Payment Link Cancel an active payment link to prevent it from being used. Only links with `active` status can be cancelled. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `id` | string | Yes | Payment link ID (e.g., `plink_abc123xyz`) | ## Request Body ```json theme={null} { "reason": "Customer requested cancellation" } ``` | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `reason` | string | No | Reason for cancellation (max 500 chars) | ## Response > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ```json theme={null} { "id": "plink_abc123xyz", "amount": 4995, "currency": "USD", "description": "Premium Blood Pressure Monitor", "status": "cancelled", "cancelled_at": "2026-02-25T16:00:00Z", "cancellation_reason": "Customer requested cancellation" } ``` ## Example ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/payment-links/plink_abc123xyz/cancel \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reason": "Order cancelled by customer" }' ``` ## Cancellation Rules | Current Status | Can Cancel? | Notes | | :- | :- | :- | | `active` | Yes | Status changes to `cancelled` | | `paid` | No | Use [Create Refund](/api-reference/endpoint/create-refund) instead | | `expired` | No | Already expired | | `cancelled` | No | Already cancelled | > [!WARNING] > > Cancelled links cannot be reactivated. Create a new link if needed. ## Webhooks Cancelling a link triggers a `payment_link.cancelled` webhook event. See [Webhooks Reference](/developer-manual/webhooks) for details. ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 400 | `invalid_state` | Link is not in cancellable state | | 401 | `unauthorized` | Invalid or missing API key | | 404 | `not_found` | Payment link not found | ## Related * [Create Payment Link](/api-reference/endpoint/create-payment-link) * [Get Payment Link](/api-reference/endpoint/get-payment-link) * [Create Refund](/api-reference/endpoint/create-refund) # Cancel Subscription Source: https://docs.withgale.com/api-reference/endpoint/cancel-subscription POST /api/v2/subscriptions/{id}/cancel Cancel a subscription # Cancel Subscription Cancel a subscription either immediately or at the end of the current billing period. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Subscription ID | ## Request Body ```json theme={null} { "cancel_at_period_end": true, "reason": "customer_request" } ``` | Parameter | Type | Required | Description | | - | - | - | - | | `cancel_at_period_end` | boolean | No | If true, cancel at period end (default: false) | | `reason` | string | No | Cancellation reason | ## Response ```json theme={null} { "id": "sub_abc123xyz", "status": "cancelled", "cancel_at_period_end": true, "current_period_end": "2025-11-18T14:30:00Z", "cancelled_at": "2025-10-20T10:00:00Z" } ``` ## Examples ### Cancel at Period End ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/subscriptions/sub_abc123xyz/cancel \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "cancel_at_period_end": true, "reason": "customer_request" }' ``` ### Immediate Cancellation ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/subscriptions/sub_abc123xyz/cancel \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "cancel_at_period_end": false }' ``` ## Related Endpoints * [Get Subscription](/api-reference/endpoint/get-subscription) * [List Subscriptions](/api-reference/endpoint/list-subscriptions) # Charge a Payment Method Source: https://docs.withgale.com/api-reference/endpoint/charge-payment-method POST /api/v2/payment-methods/{payment_method_id}/charges Charge a stored card for a new order, with the shopper absent # Charge a Payment Method Creates an order from the line items you send and charges the stored card for it. The shopper is not involved. Eligibility is checked for these items at the time of the charge, the same way as for a checkout. ## Endpoint ``` POST /api/v2/payment-methods/{payment_method_id}/charges ``` ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY Idempotency-Key: refill-2026-12-order-0042 ``` `Idempotency-Key` is required and must be 22 to 255 characters. Use one key per order. Sending the same key again returns the first result and never charges twice. ## Request Body ```json theme={null} { "reference_id": "refill-2026-12-0042", "line_items": [ { "product_id": "RX-100", "name": "Monthly prescription", "price": 4500, "quantity": 1, "currency": "USD" } ], "shipping": 500, "tax": 0, "discount": 0, "metadata": { "cycle": "2026-12" } } ``` > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ## Parameters | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `reference_id` | string | Yes | Your ID for this order, up to 50 characters | | `line_items` | array | Yes | Products being charged. Same fields as [Create Checkout Session](/api-reference/endpoint/create-checkout-v2) | | `shipping` | integer | No | Shipping amount in cents | | `tax` | integer | No | Tax amount in cents | | `discount` | integer | No | Discount amount in cents | | `metadata` | object | No | Custom key-value pairs, returned on the order | | `metadata.payment_source` | string | No | Set to `"stripe_elements_cpm"` to have this charge written to your Stripe account as a payment record, the same as the checkout that stored the card. See [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe) | | `metadata.stripe_customer_id` | string | No | The Stripe customer this payment belongs to (`cus_...`). Used with Stripe Billing. See [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing) | | `metadata.stripe_invoice_id` | string | No | The open Stripe invoice this payment settles (`in_...`). Needs `metadata.stripe_customer_id` | | `customer` | object | No | Defaults to the customer on the checkout that stored the card | | `shipping_info` | object | No | Defaults to the address on the checkout that stored the card | | `billing_info` | object | No | Defaults to the address on the checkout that stored the card | | `success_url` | string | No | Where the shopper returns after paying a declined order through `checkout_url` | | `failure_url` | string | No | Where the shopper returns if that payment fails or is cancelled | | `test_acquirer_response_code` | string | No | Test keys only. Simulates a declined charge, for example `"12"` | ## Response `201 Created`. The order, with the payment method that was charged. ```json theme={null} { "success": true, "message": "Payment method charged", "data": { "id": "ord_01ABC...", "checkout_id": "cs_def456", "status": "completed", "payment_status": "captured", "amount": 5000, "currency": "usd", "reference_id": "refill-2026-12-0042", "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "line_items": [ { "product_id": "RX-100", "name": "Monthly prescription", "quantity": 1, "unit_amount": 4500, "amount": 4500, "currency": "usd", "is_recurring": false } ], "payment_method": { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "usage": "off_session", "status": "active" }, "created_at": "2026-12-10T09:15:02Z" } } ``` The `order.completed` webhook is also sent for this order. ## Declined charges A decline returns `422` with `PAYMENT_METHOD_010`. No money is taken. The order stays open and `checkout_url` is its hosted checkout page, where the shopper can pay with another card. `payment.failed` is also sent. A declined charge is not retried automatically. ```json theme={null} { "success": false, "error": { "code": "PAYMENT_METHOD_010", "message": "The card was declined. No money was taken.", "details": { "decline_code": "12", "decline_reason": "issuer_limit", "decline_description": "Not enough balance.", "retryable": false, "order_id": "ord_01ABD...", "checkout_id": "cs_def456", "checkout_url": "" } } } ``` ## Errors | Status Code | Error Code | Description | What to do | | :- | :- | :- | :- | | 404 | `PAYMENT_METHOD_001` | Unknown ID, a payment method stored in the other mode, or saved payment methods not enabled for the account | Check the ID and the key | | 422 | `PAYMENT_METHOD_002` | Saved payment methods are not enabled for this account in this mode | Contact your account manager | | 422 | `PAYMENT_METHOD_003` | The payment method was removed or disabled | Send the shopper a new checkout to store a card | | 422 | `PAYMENT_METHOD_004` | The shopper did not agree to charges you start | Send the shopper a new checkout with `setup_future_usage` | | 422 | `PAYMENT_METHOD_006` | The order mixes HSA/FSA eligible and non-eligible items | Send one charge per group | | 422 | `PAYMENT_METHOD_007` | An item needs a Letter of Medical Necessity and the shopper holds no valid one for it | Send the shopper a checkout | | 422 | `PAYMENT_METHOD_008` | `Idempotency-Key` header missing or not 22 to 255 characters | Send a valid key | | 422 | `PAYMENT_METHOD_009` | `test_acquirer_response_code` sent with a live key | Remove the field | | 422 | `PAYMENT_METHOD_010` | The card was declined. No money was taken | Send the shopper `checkout_url` | | 503 | `PAYMENT_METHOD_011` | The charge was not completed and no money was taken | Retry with the same key, or a new key when `error.details.retry_with_new_key` is `true` | | 503 | `PAYMENT_METHOD_012` | The charge is not confirmed | Retry with the same key only. A new key could charge the shopper twice | | 409 | `PAYMENT_METHOD_013` | The key was already used to charge a different payment method | Use a new key | | 409 | `PAYMENT_METHOD_015` | A charge with this key is being processed | Retry shortly with the same key | | 422 | `GEN_003` | The request failed validation: a missing or malformed field, an order total of zero, or a total smaller than the fee for processing it. `error.validation_errors` names the field | Fix the request | | 422 | `CHECKOUT_004` | The charge names a Stripe invoice (`metadata.stripe_invoice_id`) that it cannot settle. No money was taken | See [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing#when-a-payment-is-refused-before-charging) | ## Related * [Saved Payment Methods guide](/integration/saved-payment-methods) * [Payment Method Object](/api-reference/objects/payment-method) * [Create Refund](/api-reference/endpoint/create-refund) * [Webhooks](/developer-manual/webhooks) # Create Checkout Session Source: https://docs.withgale.com/api-reference/endpoint/create-checkout-v2 POST /api/v2/checkout Create a checkout session and get a hosted checkout URL # Create Checkout Session Create a checkout session for a customer. Returns a checkout URL where the customer completes payment on Gale's hosted page. Gale handles card collection, eligibility detection, and LMN flow automatically. > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ## Endpoint ``` POST /api/v2/checkout ``` ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Request Body ```json theme={null} { "reference_id": "your-order-123", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe", "phone": "+1-555-123-4567" }, "line_items": [ { "product_id": "BP-MONITOR-001", "name": "Digital Blood Pressure Monitor", "image_url": "https://yourcdn.com/bp-monitor.jpg", "price": 4995, "quantity": 1, "currency": "USD" }, { "product_id": "VITAMINS-030", "name": "Daily Multivitamins (30-day)", "image_url": "https://yourcdn.com/vitamins.jpg", "price": 1999, "quantity": 2, "currency": "USD" } ], "shipping_info": { "address_line_1": "123 Main St", "address_line_2": "Apt 4B", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "billing_info": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "shipping": 500, "tax": 410, "discount": 0, "success_url": "https://yoursite.com/order/success", "failure_url": "https://yoursite.com/order/failed", "metadata": { "platform": "CUSTOM", "webhook_url": "https://your-server.com/webhooks/gale" } } ``` ## Parameters | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `reference_id` | string | Yes | Your order or cart ID for correlation | | `customer` | object | Yes | Customer information | | `customer.email` | string | Yes | Customer email | | `customer.first_name` | string | Yes | Customer first name | | `customer.last_name` | string | Yes | Customer last name | | `customer.phone` | string | No | Customer phone number | | `line_items` | array | Yes | Products being purchased | | `line_items[].product_id` | string | Yes | Your product ID (must match synced product) | | `line_items[].name` | string | Yes | Product name | | `line_items[].image_url` | string | No | Product image URL | | `line_items[].price` | integer | Yes | Unit price in cents | | `line_items[].quantity` | integer | Yes | Quantity | | `line_items[].currency` | string | Yes | Currency code (e.g., `"USD"`) | | `shipping_info` | object | Yes | Shipping address | | `shipping_info.address_line_1` | string | Yes | Address line 1 | | `shipping_info.address_line_2` | string | No | Address line 2 | | `shipping_info.city` | string | Yes | City | | `shipping_info.state` | string | Yes | State | | `shipping_info.postal_code` | string | Yes | ZIP/Postal code | | `shipping_info.country` | string | Yes | Country code (e.g., `"US"`) | | `billing_info` | object | No | Billing address (defaults to shipping if omitted) | | `billing_info.address_line_1` | string | Yes | Address line 1 | | `billing_info.address_line_2` | string | No | Address line 2 | | `billing_info.city` | string | Yes | City | | `billing_info.state` | string | Yes | State | | `billing_info.postal_code` | string | Yes | ZIP/Postal code | | `billing_info.country` | string | Yes | Country code (e.g., `"US"`) | | `shipping` | integer | No | Shipping amount in cents | | `tax` | integer | No | Tax amount in cents | | `discount` | integer | No | Discount amount in cents | | `success_url` | string | Yes | Redirect URL after successful payment | | `failure_url` | string | Yes | Redirect URL if payment fails or customer cancels | | `metadata` | object | No | Custom key-value pairs | | `metadata.webhook_url` | string | No | URL to receive payment webhooks (recommended) | | `metadata.payment_source` | string | No | Set to `"stripe_elements_cpm"` when Pay with HSA/FSA is in your Stripe Payment Element. The payment is then written to your Stripe account as a payment record. See [Stripe Payment Element](/custom-payment-methods/elements-payment-intent) | | `metadata.stripe_customer_id` | string | No | The Stripe customer this payment belongs to (`cus_...`). Used with Stripe Billing. See [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing) | | `metadata.stripe_invoice_id` | string | No | The open Stripe invoice this payment settles (`in_...`). Needs `metadata.stripe_customer_id` | | `setup_future_usage` | string | No | Set to `"off_session"` to store the shopper's card for charges you start later. The hosted page asks the shopper for consent. See [Saved Payment Methods](/integration/saved-payment-methods) | > [!WARNING] > > `product_id` is **your** product identifier — the one you supplied when syncing products (`merchant_product_id`), not the numeric id displayed in the dashboard. Line items that don't match a synced product are accepted as **pass-through items and treated as non-HSA/FSA-eligible**, so an unmatched id silently produces a regular (non-eligible) checkout. Your own product ids are identical across test and live, so the same integration carries to go-live unchanged. ## Response ```json theme={null} { "success": true, "message": "Checkout created", "data": { "checkout_id": "cs_a1b2c3...", "checkout_url": "https://checkout.withgale.com/checkout/cs_a1b2c3...?token=...", "reference_id": "order-789", "status": "open", "type": "eligible", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [ ... ], "amounts": { "subtotal": 4995, "hsa_amount": 4995, "regular_amount": 0, "shipping": 995, "tax": 410, "discount": 0, "total": 6400 }, "success_url": "https://yourapp.com/checkout/success", "failure_url": "https://yourapp.com/checkout/cancel", "expires_at": "2026-02-26T14:30:00Z", "created_at": "2026-02-26T13:30:00Z" }, "metadata": { "request_id": "..." } } ``` Fields are returned under `data`. | Field | Type | Description | | :- | :- | :- | | `data.checkout_id` | string | Unique checkout session identifier (`cs_...`) | | `data.checkout_url` | string | Hosted checkout page URL (includes access token) — redirect customer here | | `data.status` | string | Session status (`open`) | | `data.type` | string | Cart type (`eligible`, `split`, `regular`) | | `data.amounts` | object | All amounts in cents: `subtotal`, `hsa_amount`, `regular_amount`, `shipping`, `tax`, `discount`, `total` | | `data.expires_at` | timestamp | When session expires | | `data.setup_future_usage` | string | `off_session` when the request asked to store the card. Absent otherwise | ## Example ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/checkout \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reference_id": "order-789", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [ { "product_id": "BP-MONITOR-001", "name": "Digital Blood Pressure Monitor", "price": 4995, "quantity": 1, "currency": "USD" } ], "shipping_info": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "shipping": 500, "tax": 410, "success_url": "https://yoursite.com/order/success", "failure_url": "https://yoursite.com/order/failed" }' ``` > [!NOTE] > > To charge a customer's card again on a schedule you run yourself, such as refills or renewals from your own system, add `setup_future_usage` to a normal checkout. See [Saved Payment Methods](/integration/saved-payment-methods). ### Checkout that stores a card Add `setup_future_usage` to a normal checkout request. ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/checkout \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reference_id": "order-1001", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [ { "product_id": "RX-100", "name": "Monthly prescription", "price": 4500, "quantity": 1, "currency": "USD" } ], "shipping_info": { "address_line_1": "1 Main St", "city": "Austin", "state": "TX", "postal_code": "78701", "country": "US" }, "success_url": "https://yoursite.com/order/success", "failure_url": "https://yoursite.com/order/failed", "setup_future_usage": "off_session" }' ``` The response carries `"setup_future_usage": "off_session"`. Once the shopper has paid, the stored card is returned as `payment_method` on [Get Checkout Status](/api-reference/endpoint/get-checkout), on the `order.completed` webhook and on the `payment_method.saved` webhook. Charge it later with [Charge a Payment Method](/api-reference/endpoint/charge-payment-method). ### Checkout from a Stripe Payment Element When Pay with HSA/FSA is in your Stripe Payment Element, add `payment_source` to `metadata`. The payment is then written to your Stripe account as a payment record. The restricted key has to be saved on [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe) first. ```json theme={null} { "metadata": { "payment_source": "stripe_elements_cpm" } } ``` This works together with `setup_future_usage`. See [Stripe Payment Element](/custom-payment-methods/elements-payment-intent). ### Subscription Checkout Beta ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/checkout \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reference_id": "membership-456", "customer": { "email": "member@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [ { "product_id": "MEMBERSHIP-PREMIUM", "name": "Premium Membership", "price": 9900, "quantity": 1, "currency": "USD" } ], "payment_type": "subscription", "subscription": { "interval": "monthly", "trial_period_days": 14 }, "success_url": "https://yoursite.com/welcome", "failure_url": "https://yoursite.com/pricing" }' ``` ## Checkout Types Gale automatically determines the checkout type based on product eligibility: | Type | Description | | :- | :- | | `eligible` | All items are HSA/FSA eligible | | `split` | Mix of eligible and non-eligible items | | `regular` | No items are eligible | You don't need to specify the type — Gale handles this automatically based on the products in the checkout. ## Checkout Status | Status | Description | | :- | :- | | `open` | Checkout session created, awaiting customer | | `paid` | Customer completed payment, order created | | `expired` | Session expired (24 hours) | ## Webhooks When payment completes, you receive an `order.completed` webhook: ```json theme={null} { "type": "order.completed", "data": { "id": "ord_abc123", "checkout_id": "01HXYZ...", "reference_id": "your-order-123", "status": "completed", "customer": { "email": "jane@example.com" } } } ``` See [Webhooks Reference](/developer-manual/webhooks) for setup and all event types. ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 400 | `bad_request` | Missing or invalid parameters | | 401 | `unauthorized` | Invalid API key | | 422 | `validation_error` | Field validation failed | | 422 | `CHECKOUT_002` | `setup_future_usage` was sent and saved payment methods are not enabled for this account | | 422 | `CHECKOUT_003` | `setup_future_usage` was sent and the order mixes HSA/FSA eligible and non-eligible items | | 422 | `CHECKOUT_004` | The request names a Stripe invoice (`metadata.stripe_invoice_id`) that this payment cannot settle. See [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing#when-a-payment-is-refused-before-charging) | See [Error Reference](/developer-manual/errors) for details. ## Related * [Get Checkout Session](/api-reference/endpoint/get-checkout) * [Checkout Session Object](/api-reference/objects/checkout-session) * [Checkout Integration Guide](/integration/checkout) * [Saved Payment Methods](/integration/saved-payment-methods) * [Order Object](/api-reference/objects/order) * [Webhooks](/developer-manual/webhooks) # Create Payment Link Source: https://docs.withgale.com/api-reference/endpoint/create-payment-link POST /api/v2/payment-links Generate a payment link for one-time or recurring payments # Create Payment Link Generate a payment link that customers can use to complete checkout. Payment links automatically handle HSA/FSA eligibility detection and can be used for both one-time and recurring payments. > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Request Body ```json theme={null} { "amount": 4995, "currency": "USD", "description": "Premium Blood Pressure Monitor", "customer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe" }, "products": [ { "merchant_product_id": "BP-MONITOR-001", "name": "Blood Pressure Monitor", "quantity": 1, "price": 4995 } ], "payment_type": "one_time", "success_url": "https://yoursite.com/success", "cancel_url": "https://yoursite.com/cancel", "metadata": { "order_id": "ORD-12345" } } ``` ## Parameters | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `amount` | integer | Yes | Total amount in cents | | `currency` | string | Yes | ISO 4217 currency code (e.g., `"USD"`) | | `description` | string | Yes | Description of the payment | | `customer` | object | No | Pre-fill customer information | | `customer.email` | string | No | Customer email | | `customer.first_name` | string | No | Customer first name | | `customer.last_name` | string | No | Customer last name | | `products` | array | No | Product line items | | `products[].merchant_product_id` | string | Yes\* | Your product reference ID | | `products[].name` | string | Yes\* | Product name | | `products[].quantity` | integer | Yes\* | Quantity | | `products[].price` | integer | Yes\* | Unit price in cents | | `payment_type` | enum | No | `one_time` or `subscription` (default: `one_time`) | | `subscription` | object | No | Required if `payment_type` is `subscription` | | `subscription.interval` | enum | Yes\* | `daily`, `weekly`, `monthly`, `yearly` | | `subscription.interval_count` | integer | No | Number of intervals (default: 1) | | `subscription.trial_period_days` | integer | No | Free trial days | | `success_url` | string | Yes | Redirect URL after successful payment | | `cancel_url` | string | No | Redirect URL if customer cancels | | `metadata` | object | No | Custom key-value pairs | | `expires_at` | timestamp | No | When link expires (default: 15 days) | ## Response ```json theme={null} { "id": "plink_abc123xyz", "url": "https://checkout.withgale.com/pay/plink_abc123xyz", "amount": 4995, "currency": "USD", "description": "Premium Blood Pressure Monitor", "payment_type": "one_time", "status": "active", "customer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe" }, "products": [ { "merchant_product_id": "BP-MONITOR-001", "name": "Blood Pressure Monitor", "quantity": 1, "price": 4995, "hsa_fsa_eligible": true } ], "success_url": "https://yoursite.com/success", "cancel_url": "https://yoursite.com/cancel", "metadata": { "order_id": "ORD-12345" }, "expires_at": "2026-03-12T14:30:00Z", "created_at": "2026-02-25T14:30:00Z" } ``` ## Example ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/payment-links \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "amount": 2995, "currency": "USD", "description": "Digital Thermometer", "products": [ { "merchant_product_id": "THERM-001", "name": "Digital Thermometer", "quantity": 1, "price": 2995 } ], "success_url": "https://yoursite.com/success" }' ``` ## Subscription Intervals | Interval | `interval_count` | Billing Frequency | | :- | :- | :- | | `monthly` | 1 | Every month | | `monthly` | 3 | Every 3 months (quarterly) | | `weekly` | 1 | Every week | | `weekly` | 2 | Every 2 weeks (bi-weekly) | | `yearly` | 1 | Every year | ## Payment Link Status | Status | Description | | :- | :- | | `active` | Link is active and ready for payment | | `expired` | Link has expired (past `expires_at` time) | | `paid` | Payment completed successfully | | `cancelled` | Link was cancelled | ## Webhooks When a customer completes payment on a payment link, Gale sends webhook events to your registered endpoints: * `order.completed` — Payment captured successfully * `order.failed` — Payment failed or declined See [Webhooks Reference](/developer-manual/webhooks) for payload examples and setup instructions. ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 400 | `invalid_request` | Missing or invalid parameters | | 400 | `invalid_amount` | Amount must be positive integer in cents | | 401 | `unauthorized` | Invalid or missing API key | | 422 | `validation_error` | Field validation failed | ## Related * [Get Payment Link](/api-reference/endpoint/get-payment-link) * [List Payment Links](/api-reference/endpoint/list-payment-links) * [Cancel Payment Link](/api-reference/endpoint/cancel-payment-link) * [Payment Links Integration Guide](/integration/payment-links) # Create Product Source: https://docs.withgale.com/api-reference/endpoint/create-product-v2 POST /api/v2/products Add a product to your catalog. Gale checks HSA/FSA eligibility from the UPC or GTIN when you send one. # Create Product Creates a product for your merchant site and returns it with its HSA/FSA eligibility. Gale checks eligibility only when you send `upc_code_or_gtin`. Create does not look for an existing `merchant_product_id`, so calling create twice for the same SKU makes two products. Send each SKU once, and store the Gale `id` from the response. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Request Body ```json theme={null} { "name": "Digital Blood Pressure Monitor", "tagline": "FDA-approved automatic BP monitor", "description": "Clinically validated blood pressure monitor with Bluetooth connectivity.", "price_cents": 4995, "currency": "USD", "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "images": [ "https://cdn.example.com/bp-monitor-1.jpg", "https://cdn.example.com/bp-monitor-2.jpg" ] } ``` ## Parameters > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). | Parameter | Type | Required | Description | | - | - | - | - | | `name` | string | Yes | Product name (max 255 chars) | | `price_cents` | integer | Yes | Price in cents. Minimum 1, maximum 999999999. Send `price_cents`, not `price` | | `currency` | string | Yes | Three-letter ISO 4217 code, for example `USD` | | `tagline` | string | No | Short description (max 255 chars) | | `description` | string | No | Full product description | | `merchant_product_id` | string | No | Your SKU or product ID (max 255 chars). Checkout matches cart items on this value. Send it on every product. Without it, you cannot find the product by your SKU later. | | `upc_code_or_gtin` | string | No | UPC or GTIN barcode (max 255 chars). Used for SIGIS eligibility. See [Eligibility](#eligibility) | | `images` | array of strings | No | Up to 10 image URLs | Fields that are not listed here, such as `metadata`, are ignored and not stored. ## Response Returns `201 Created`. The product is in `data`. See [Product Object](/api-reference/objects/product) for every field. ```json theme={null} { "success": true, "message": "Product created successfully", "data": { "id": 12345, "name": "Digital Blood Pressure Monitor", "tagline": "FDA-approved automatic BP monitor", "description": "Clinically validated blood pressure monitor with Bluetooth connectivity.", "price_cents": 4995, "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "status": "active", "eligibility": { "hsa_fsa_eligible": true, "eligibility_type": "auto_substantiation", "reason": "SIGIS auto-substantiation", "checked_at": "2026-11-05T12:00:00+00:00" }, "images": [ "https://cdn.example.com/bp-monitor-1.jpg", "https://cdn.example.com/bp-monitor-2.jpg" ], "created_at": "2026-11-05T12:00:00+00:00", "updated_at": "2026-11-05T12:00:00+00:00" }, "metadata": { "processing_time_ms": 12 } } ``` ## Eligibility Eligibility is decided from `upc_code_or_gtin` only. The product name and description are not used. * A UPC or GTIN that matches an active SIGIS entry sets `hsa_fsa_eligible` to `true` and `eligibility_type` to `auto_substantiation`. * A product with no UPC or GTIN, or with a code that is not in SIGIS, has `hsa_fsa_eligible: false` and `eligibility_type: null`. Gale reviews these products and sets any other eligibility type. You cannot set an eligibility type in this request. * Use an 11-digit UPC, a 12-digit UPC-A, or a 14-digit GTIN. Other lengths, such as the 13-digit EAN-13, do not match SIGIS. ## Idempotency Send an `Idempotency-Key` header to make a retry safe. Use a unique value for each logical create, such as a UUID v4. * The key must be 22 to 255 characters. Allowed characters are letters, digits, `-`, `_`, and `.`. * A key in any other format is ignored. The request still runs, and no error is returned. * A repeat with the same key and the same body within 24 hours returns the original response with the header `X-Idempotent-Replayed: true`. * The same key with a different body runs as a new request. * A repeat sent while the first request is still running returns `409 DUPLICATE_REQUEST`. ## Examples ### Basic product ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/products \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: 6f1c2a9e-4b7d-4e8a-9c3f-2d5b8e1a7f40" \ -d '{ "name": "Digital Thermometer", "price_cents": 2995, "currency": "USD", "merchant_product_id": "THERM-001" }' ``` ### Product with a UPC ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/products \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Premium Blood Pressure Monitor", "price_cents": 4995, "currency": "USD", "merchant_product_id": "BP-MONITOR-PRO", "upc_code_or_gtin": "14567890123456" }' ``` ## Errors | HTTP status | `error.code` | When | | - | - | - | | 401 | | Missing, malformed, or invalid API key | | 409 | `DUPLICATE_REQUEST` | The same `Idempotency-Key` is still being processed | | 422 | `VALIDATION_FAILED` | A required field is missing or a value is invalid. `error.details` maps each field to its messages | | 429 | `RATE_LIMIT_EXCEEDED` | More than 100 product writes per minute for this merchant | | 500 | `INTERNAL_ERROR` | Gale could not save the product. Retry later | Validation error example: ```json theme={null} { "success": false, "error": { "code": "VALIDATION_FAILED", "message": "Request validation failed", "type": "validation", "details": { "price_cents": ["Product price is required"] } } } ``` ## Rate Limits Product writes (create, update, and delete) are limited to 100 requests per minute. Product reads (get and list) are limited to 500 requests per minute. ## Related * [Get Product](/api-reference/endpoint/get-product-v2) - GET /api/v2/products/ * [Update Product](/api-reference/endpoint/update-product-v2) - PUT /api/v2/products/ * [List Products](/api-reference/endpoint/list-products-v2) - GET /api/v2/products * [Delete Product](/api-reference/endpoint/delete-product) - DELETE /api/v2/products/ * [Product Object](/api-reference/objects/product) # Create Refund Source: https://docs.withgale.com/api-reference/endpoint/create-refund POST /api/v2/refunds Refund a completed order (full or partial) # Create Refund Issue a full or partial refund for a completed order. Refunds are processed back to the original payment method (HSA/FSA card or regular card). ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Request Body ```json theme={null} { "order_id": "ord_abc123xyz", "amount": 4235, "reason": "customer_request", "notes": "Customer requested refund due to delayed shipping", "metadata": { "support_ticket": "TICKET-12345" } } ``` > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ## Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `order_id` | string | Yes | ID of the order to refund | | `amount` | integer | No | Amount to refund in cents (omit for full refund) | | `reason` | enum | Yes | Refund reason (see below) | | `notes` | string | No | Additional notes (max 500 chars) | | `metadata` | object | No | Custom key-value pairs | > [!NOTE] > > **Finding Order ID**: You can get the `order_id` from: > > * Webhook event data (`order.completed` event) > * Order API response (`GET /api/v2/orders`) > * Your database (store it when receiving `order.completed` webhook) > * Dashboard order details ## Refund Reasons | Reason | Description | Example Use Case | | - | - | - | | `customer_request` | Customer requested refund | Customer changed mind, no longer needed | | `duplicate` | Duplicate payment | Customer accidentally paid twice | | `fraudulent` | Fraudulent order | Detected fraudulent transaction | | `product_unavailable` | Product out of stock | Item went out of stock after order | | `damaged_product` | Product arrived damaged | Item damaged during shipping | | `wrong_product` | Wrong product shipped | Fulfillment error, sent wrong item | | `other` | Other reason | Any other reason (explain in `notes`) | ## Request ```bash theme={null} POST /api/v2/refunds ``` ## Response ```json theme={null} { "success": true, "message": "Refund created", "data": { "id": "re_3Toy...", "order_id": "ord_abc123xyz", "amount": 4235, "reason": "customer_request", "notes": "Customer requested refund due to delayed shipping", "status": "succeeded", "refund_breakdown": { "hsa_amount": 2995, "regular_amount": 1240 }, "refunds": [ { "refund_id": "re_3Toy...", "success": true } ], "metadata": { "support_ticket": "TICKET-12345" }, "created_at": "2026-07-23T16:00:00Z" }, "metadata": { "request_id": "..." } } ``` Fields are returned under `data`. ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Processor refund reference | | `status` | enum | Refund status: `pending`, `succeeded`, `failed`, `cancelled` | | `refund_breakdown` | object | Refund amount per payment type (`hsa_amount`, `regular_amount`) | | `refunds` | array | Per-payment refund results | ## Examples ### Full Refund ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/refunds \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "order_id": "ord_abc123xyz", "reason": "customer_request", "notes": "Customer not satisfied with product" }' ``` ### Partial Refund ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/refunds \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "order_id": "ord_abc123xyz", "amount": 1000, "reason": "damaged_product", "notes": "Partial refund for damaged item" }' ``` ## Refund Status | Status | Description | | - | - | | `pending` | Refund initiated, processing | | `succeeded` | Refund processed successfully | | `failed` | Refund failed | | `cancelled` | Refund cancelled | ## Split Card Refunds (Automatic) **Gale automatically handles split card refunds.** You don't need to specify how much goes to each card. When an order is paid with both HSA/FSA and regular card: ```json theme={null} { "order": { "amounts": { "hsa_amount": 4995, // Paid with HSA/FSA card "regular_amount": 895, // Paid with regular card "total": 5890 } } } ``` ### Full Refund Just provide the `order_id` - Gale splits automatically: ```bash theme={null} POST /api/v2/refunds { "order_id": "ord_abc123", "reason": "customer_request" } ``` **Response shows the breakdown:** ```json theme={null} { "id": "ref_xyz789", "amount": 5890, "refund_breakdown": { "hsa_amount": 4995, // Refunded to HSA/FSA card "regular_amount": 895 // Refunded to regular card } } ``` ### Partial Refund Gale splits proportionally based on the original payment ratio: ```bash theme={null} POST /api/v2/refunds { "order_id": "ord_abc123", "amount": 2945, // Partial refund "reason": "damaged_product" } ``` **Response:** ```json theme={null} { "id": "ref_xyz789", "amount": 2945, "refund_breakdown": { "hsa_amount": 2498, // ~84.7% (same ratio as original) "regular_amount": 447 // ~15.3% } } ``` **Key Points:** * You only specify total `amount` * Gale calculates the split automatically * Each amount refunds to its original payment method * Response shows the breakdown for your records ## Webhooks Refunds trigger the following webhook events: ```json theme={null} { "type": "refund.created", "data": { "id": "ref_xyz789", "order_id": "ord_abc123xyz", "amount": 4235, "status": "pending" } } ``` ```json theme={null} { "type": "refund.succeeded", "data": { "id": "ref_xyz789", "order_id": "ord_abc123xyz", "status": "succeeded", "processed_at": "2025-10-18T16:05:00Z" } } ``` See [Webhooks Reference](/developer-manual/webhooks) for all refund events. ## Errors | Status Code | Error Code | Description | | - | - | - | | 400 | `invalid_amount` | Refund amount exceeds order total | | 400 | `already_refunded` | Order already fully refunded | | 400 | `invalid_state` | Order not in refundable state | | 401 | `unauthorized` | Invalid or missing API key | | 404 | `not_found` | Order not found | | 422 | `validation_error` | Field validation failed | ### Amount Too Large ```json theme={null} { "error": { "code": "invalid_amount", "message": "Refund amount exceeds order total", "details": { "requested": 10000, "maximum": 4235 } } } ``` ### Already Refunded ```json theme={null} { "error": { "code": "already_refunded", "message": "Order has already been fully refunded" } } ``` ### Invalid State ```json theme={null} { "error": { "code": "invalid_state", "message": "Cannot refund order with payment status 'pending'" } } ``` ## Refund Timeline | Payment Method | Typical Arrival Time | | - | - | | HSA/FSA Card | 5-10 business days | | Regular Card | 5-10 business days | **Note:** Actual timing depends on the customer's card issuer. ## Important Notes > [!WARNING] > > **Refunds cannot be undone.** Once a refund is processed, it cannot be reversed. Double-check order ID and amount before submitting. > [!NOTE] > > **Partial refunds are supported.** You can issue multiple partial refunds up to the order total. The remaining refundable amount is tracked automatically. ## Related Endpoints * [Get Order](/api-reference/endpoint/get-order) - GET /api/v2/orders/ * [List Orders](/api-reference/endpoint/list-orders) - GET /api/v2/orders ## Related Resources * [Order Object](/api-reference/objects/order) * [Webhooks Reference](/developer-manual/webhooks) # Create Subscription Source: https://docs.withgale.com/api-reference/endpoint/create-subscription POST /api/v2/subscriptions Create a recurring payment subscription # Create Subscription Create a new subscription for recurring payments. Subscriptions are typically created after a customer completes checkout via a payment link with `payment_type: "subscription"`. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Request Body ```json theme={null} { "customer_id": "cus_xyz789", "product_id": 12345, "amount_cents": 9900, "currency": "USD", "interval": "monthly", "interval_count": 1, "trial_period_days": 7, "payment_method_id": "pm_abc123", "metadata": { "tier": "premium", "source": "website" } } ``` ## Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `customer_id` | string | Yes | Customer ID | | `product_id` | integer | No | Associated product ID | | `merchant_product_id` | string | No | Your product reference ID | | `amount_cents` | integer | Yes | Recurring charge amount in cents | | `currency` | string | Yes | ISO 4217 currency code (e.g., "USD") | | `interval` | enum | Yes | `daily`, `weekly`, `monthly`, or `yearly` | | `interval_count` | integer | No | Number of intervals (default: 1) | | `trial_period_days` | integer | No | Free trial duration in days | | `payment_method_id` | string | Yes | ID of stored payment method | | `metadata` | object | No | Custom key-value pairs | ## Response ```json theme={null} { "id": "sub_abc123xyz", "customer_id": "cus_xyz789", "status": "trialing", "product_id": 12345, "merchant_product_id": "MEMBERSHIP-PREMIUM", "amount_cents": 9900, "currency": "USD", "interval": "monthly", "interval_count": 1, "trial_period_days": 7, "trial_end": "2025-10-25T14:30:00Z", "current_period_start": "2025-10-18T14:30:00Z", "current_period_end": "2025-11-18T14:30:00Z", "next_billing_date": "2025-10-25T14:30:00Z", "cancel_at_period_end": false, "payment_method": { "type": "hsa_fsa_card", "last4": "1111", "brand": "visa" }, "metadata": { "tier": "premium", "source": "website" }, "created_at": "2025-10-18T14:30:00Z", "updated_at": "2025-10-18T14:30:00Z" } ``` See [Subscription Object](/api-reference/objects/subscription) for complete field descriptions. ## Examples ### Monthly Subscription with Trial ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/subscriptions \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cus_xyz789", "product_id": 12345, "amount_cents": 9900, "currency": "USD", "interval": "monthly", "trial_period_days": 14, "payment_method_id": "pm_abc123" }' ``` ### Annual Subscription ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/subscriptions \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cus_xyz789", "product_id": 12346, "amount_cents": 99900, "currency": "USD", "interval": "yearly", "payment_method_id": "pm_abc123" }' ``` ### Bi-weekly Subscription ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/subscriptions \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cus_xyz789", "merchant_product_id": "COACHING-BIWEEKLY", "amount_cents": 4900, "currency": "USD", "interval": "weekly", "interval_count": 2, "payment_method_id": "pm_abc123" }' ``` ### With JavaScript ```javascript theme={null} const createSubscription = async (customerId, planDetails) => { const response = await fetch('https://api.withgale.com/api/v2/subscriptions', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.GALE_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ customer_id: customerId, product_id: planDetails.productId, amount_cents: planDetails.price * 100, currency: 'USD', interval: planDetails.interval, trial_period_days: planDetails.trialDays, payment_method_id: planDetails.paymentMethodId, metadata: { tier: planDetails.tier, source: 'web_app' } }) }); if (!response.ok) { throw new Error('Failed to create subscription'); } const subscription = await response.json(); console.log(`Subscription created: ${subscription.id}`); console.log(`Status: ${subscription.status}`); console.log(`Next billing: ${subscription.next_billing_date}`); return subscription; }; // Usage const subscription = await createSubscription('cus_xyz789', { productId: 12345, price: 99, interval: 'monthly', trialDays: 7, paymentMethodId: 'pm_abc123', tier: 'premium' }); ``` ## Use Cases ### Membership Tiers ```javascript theme={null} // Create subscription based on selected tier const membershipTiers = { basic: { productId: 12345, amount_cents: 4900, features: 'basic_access' }, premium: { productId: 12346, amount_cents: 9900, features: 'unlimited_access,priority_support' }, elite: { productId: 12347, amount_cents: 19900, features: 'unlimited_access,priority_support,1on1_coaching' } }; const subscribeMember = async (customerId, tier, paymentMethodId) => { const plan = membershipTiers[tier]; return await createSubscription({ customer_id: customerId, product_id: plan.productId, amount_cents: plan.amount_cents, currency: 'USD', interval: 'monthly', trial_period_days: 14, payment_method_id: paymentMethodId, metadata: { tier: tier, features: plan.features } }); }; ``` ### Post-Checkout Subscription Creation ```javascript theme={null} // Create subscription after payment link is paid app.post('/webhooks/gale', async (req, res) => { const event = req.body; if (event.type === 'payment_link.paid') { const { payment_link, customer, payment_method } = event.data; // Check if this was a subscription payment link if (payment_link.payment_type === 'subscription') { const subscription = await createSubscription({ customer_id: customer.id, product_id: payment_link.product_id, amount_cents: payment_link.amount_cents, currency: payment_link.currency, interval: payment_link.subscription.interval, interval_count: payment_link.subscription.interval_count, trial_period_days: payment_link.subscription.trial_period_days, payment_method_id: payment_method.id }); console.log(`Subscription ${subscription.id} created for customer ${customer.email}`); } } res.status(200).send('OK'); }); ``` ### Upgrade/Downgrade Flow ```javascript theme={null} // Cancel old subscription and create new one const changeSubscriptionTier = async (customerId, oldSubId, newTier) => { // Cancel existing subscription at period end await cancelSubscription(oldSubId, { cancel_at_period_end: true }); // Create new subscription const newSub = await subscribeMember( customerId, newTier, paymentMethodId ); return { oldSubscription: oldSubId, newSubscription: newSub.id, effectiveDate: newSub.current_period_start }; }; ``` ## Webhooks Subscription creation triggers the following webhook event: ```json theme={null} { "type": "subscription.created", "data": { "id": "sub_abc123xyz", "customer_id": "cus_xyz789", "status": "trialing", "amount_cents": 9900, "interval": "monthly", "trial_end": "2025-10-25T14:30:00Z" } } ``` See [Webhooks Reference](/developer-manual/webhooks) for all subscription events. ## Errors | Status Code | Error Code | Description | | - | - | - | | 400 | `invalid_request` | Missing or invalid parameters | | 400 | `invalid_payment_method` | Payment method not valid | | 401 | `unauthorized` | Invalid or missing API key | | 404 | `customer_not_found` | Customer ID not found | | 422 | `validation_error` | Field validation failed | | 429 | `rate_limit_exceeded` | Too many requests | Example error: ```json theme={null} { "error": { "code": "validation_error", "message": "Invalid subscription parameters", "details": [ { "field": "amount_cents", "message": "Amount must be a positive integer" } ] } } ``` ## Best Practices > [card] Offer Trial Periods > > Use trials to reduce friction for new subscribers > [card] Store Payment Method > > Collect and verify payment method before trial ends > [card] Handle Webhooks > > Listen for subscription events for lifecycle management > [card] Use Metadata > > Track features and tiers in metadata ## Important Notes > [!NOTE] > > **Payment method required.** Even with a trial period, a valid payment method must be provided and will be verified during subscription creation. > [!WARNING] > > **HSA/FSA subscriptions.** Ensure recurring charges are for eligible products/services. Some HSA/FSA administrators restrict recurring charges. ## Related Endpoints * [Get Subscription](/api-reference/endpoint/get-subscription) - GET /api/v2/subscriptions/ * [List Subscriptions](/api-reference/endpoint/list-subscriptions) - GET /api/v2/subscriptions * [Update Subscription](/api-reference/endpoint/update-subscription) - PUT /api/v2/subscriptions/ * [Cancel Subscription](/api-reference/endpoint/cancel-subscription) - POST /api/v2/subscriptions//cancel ## Related Resources * [Subscription Object](/api-reference/objects/subscription) * [Webhooks Reference](/developer-manual/webhooks) * [Payment Links](/api-reference/endpoint/create-payment-link) # Remove a Payment Method Source: https://docs.withgale.com/api-reference/endpoint/delete-payment-method DELETE /api/v2/payment-methods/{payment_method_id} Remove a stored card so it can no longer be charged # Remove a Payment Method Removes the stored card. Call this when the shopper asks you to stop using their card. A removed payment method cannot be charged or restored. Calling it again for the same ID returns the same result. ## Endpoint ``` DELETE /api/v2/payment-methods/{payment_method_id} ``` ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Description | | :- | :- | :- | | `payment_method_id` | string | The payment method ID (`pm_...`) | ## Response The payment method, with `status` set to `disabled`. ```json theme={null} { "success": true, "message": "Payment method removed", "data": { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "disabled", "checkout_id": "cs_abc123", "customer_email": "jane@example.com", "last_used_at": "2026-12-10T09:15:02Z", "created_at": "2026-11-10T21:04:11Z" } } ``` ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 401 | `unauthorized` | Invalid API key | | 404 | `PAYMENT_METHOD_001` | Unknown ID, or a payment method stored in the other mode | | 503 | `PAYMENT_METHOD_014` | The payment method could not be removed right now. Safe to retry | ## Related * [Payment Method Object](/api-reference/objects/payment-method) * [Saved Payment Methods guide](/integration/saved-payment-methods) # Delete Product Source: https://docs.withgale.com/api-reference/endpoint/delete-product DELETE /api/v2/products/{id} Remove a product from your catalog. The product no longer appears in get or list responses. # Delete Product Removes a product from your catalog. After a delete, [Get Product](/api-reference/endpoint/get-product-v2) and [List Products](/api-reference/endpoint/list-products-v2) no longer return the product. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `id` | integer | Yes | Gale product ID | ## Request ```bash theme={null} DELETE /api/v2/products/{id} ``` ## Response Returns `200 OK`. The response has no `data` field. ```json theme={null} { "success": true, "message": "Product deleted successfully", "metadata": { "processing_time_ms": 9 } } ``` ## Examples ```bash theme={null} curl -X DELETE https://api.withgale.com/api/v2/products/12345 \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | HTTP status | `error.code` | When | | - | - | - | | 401 | | Missing, malformed, or invalid API key | | 404 | `NOT_FOUND` | No product with this `id` on your merchant site, or the product was already deleted | | 429 | `RATE_LIMIT_EXCEEDED` | More than 100 product writes per minute for this merchant | | 500 | `INTERNAL_ERROR` | Something went wrong on Gale's side. Retry later | ## Related * [Create Product](/api-reference/endpoint/create-product-v2) - POST /api/v2/products * [Get Product](/api-reference/endpoint/get-product-v2) - GET /api/v2/products/ * [List Products](/api-reference/endpoint/list-products-v2) - GET /api/v2/products # Get Checkout Status Source: https://docs.withgale.com/api-reference/endpoint/get-checkout GET /api/v2/checkout/{checkout_id} Retrieve the status and order details for a checkout session or payment link # Get Checkout Status Universal status polling endpoint for both checkout sessions and payment link flows. Use this when you need to check whether a payment has completed — for example, if a webhook was missed or you want to confirm status on page load. ## Endpoint ``` GET /api/v2/checkout/{checkout_id} ``` The `checkout_id` is the `cs_xxx` value returned when the cart was created. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Description | | :- | :- | :- | | `checkout_id` | string | The checkout ID (`cs_xxx`) | ## Response Fields are returned under `data`. **Before payment (awaiting customer):** ```json theme={null} { "success": true, "data": { "checkout_id": "cs_abc123", "status": "pending", "order": null } } ``` **After successful payment:** ```json theme={null} { "success": true, "data": { "checkout_id": "cs_abc123", "status": "completed", "order": { "id": "ord_01ABC...", "status": "completed", "is_recurring": false, "payment_status": "captured", "amount": 4995, "currency": "usd", "payment_link_id": "pl_abc123", "client_reference_id": "your-order-123", "reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "line_items": [ { "product_id": "PROD-001", "name": "Digital Thermometer", "quantity": 1, "unit_amount": 4995, "amount": 4995, "currency": "usd", "is_recurring": false } ], "created_at": "2026-03-31T12:00:00Z" } } } ``` **After failed payment:** ```json theme={null} { "success": true, "data": { "checkout_id": "cs_abc123", "status": "failed", "order": { "id": "ord_01DEF...", "status": "failed", "is_recurring": false, "payment_status": "failed", "amount": 4995, "currency": "usd", "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "created_at": "2026-03-31T12:01:00Z" } } } ``` ## Stored card A checkout created with `setup_future_usage: "off_session"` also returns `payment_method`. It is `null` until the shopper has paid, then it holds the [payment method object](/api-reference/objects/payment-method). Checkouts that did not ask for storage have no `payment_method` field. ```json theme={null} { "success": true, "data": { "checkout_id": "cs_abc123", "status": "completed", "payment_method": { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "active" } } } ``` ## Status Values | Status | Description | | :- | :- | | `pending` | Cart exists, no payment attempted yet | | `completed` | Payment captured successfully | | `failed` | Payment failed or declined | | `expired` | The checkout expired before a payment was attempted | > [!NOTE] > > These values differ from the `status` on the object returned by [Create Checkout Session](/api-reference/endpoint/create-checkout-v2), which is `open` when the checkout is created. ## Example ```bash theme={null} curl https://api.withgale.com/api/v2/checkout/cs_abc123 \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 401 | `unauthorized` | Invalid API key | | 404 | `not_found` | Checkout ID not found | ## Related * [Webhooks](/developer-manual/webhooks) * [Order Object](/api-reference/objects/order) * [Create Checkout Session](/api-reference/endpoint/create-checkout-v2) # Get Order Source: https://docs.withgale.com/api-reference/endpoint/get-order GET /api/v2/orders/{id} Retrieve details about a specific order # Get Order Retrieve information about an order, including payment status, customer details, and line items. Orders are created when a checkout session or payment link is successfully paid. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Order ID (e.g., `ord_abc123xyz`) | ## Request ```bash theme={null} GET /api/v2/orders/{id} ``` ## Response > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ```json theme={null} { "id": "ord_abc123xyz", "order_number": "ORD-2025-001234", "checkout_id": "01HXYZ...", "status": "completed", "payment_status": "captured", "receipt_url": "https://files.withgale.com/receipts/ord_abc123xyz.pdf?expires=...&signature=...", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe", "phone": "+1-555-123-4567", "shipping_address": { "address_line_1": "123 Main St", "address_line_2": "Apt 4B", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "billing_address": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" } }, "line_items": [ { "id": "li_123", "product_id": "PROD-001", "name": "Digital Thermometer", "quantity": 1, "price": 2995, "hsa_fsa_eligible": true } ], "amounts": { "subtotal": 2995, "hsa_amount": 2995, "regular_amount": 0, "shipping": 995, "tax": 245, "discount": 0, "total": 4235 }, "payment": { "payment_id": "pay_xyz789", "payment_method": "hsa_fsa_card", "last4": "1111", "brand": "visa", "captured_at": "2025-10-18T15:30:00Z" }, "metadata": { "order_number": "ORDER-12345", "platform": "SHOPIFY" }, "created_at": "2025-10-18T15:00:00Z", "completed_at": "2025-10-18T15:30:00Z", "status_history": [ { "status": "pending", "timestamp": "2025-10-18T15:00:00Z", "reason": "Order created" }, { "status": "processing", "timestamp": "2025-10-18T15:01:00Z", "reason": "Payment processing" }, { "status": "completed", "timestamp": "2025-10-18T15:30:00Z", "reason": "Payment captured" } ] } ``` > [!NOTE] > > `receipt_url` is a temporary link to the order's receipt PDF. It is `null` until the receipt is generated and expires after one hour. Request the order again for a new link. ## Response Fields See [Order Object](/api-reference/objects/order) for complete field descriptions. ## Examples ### Basic Retrieval ```bash theme={null} curl https://api.withgale.com/api/v2/orders/ord_abc123xyz \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Order Status | Status | Description | | - | - | | `pending` | Order created, awaiting payment | | `processing` | Payment being processed | | `completed` | Payment successful, order complete | | `failed` | Payment failed | | `cancelled` | Order cancelled | ## Payment Status | Status | Description | | - | - | | `pending` | Payment not yet attempted | | `authorized` | Payment authorized (not captured) | | `captured` | Payment captured successfully | | `failed` | Payment failed | | `refunded` | Payment refunded (full or partial) | | `disputed` | Payment disputed/chargebacked | ## Errors | Status Code | Error Code | Description | | - | - | - | | 401 | `unauthorized` | Invalid or missing API key | | 404 | `not_found` | Order not found | | 429 | `rate_limit_exceeded` | Too many requests | Example error: ```json theme={null} { "error": { "code": "not_found", "message": "Order not found", "param": "id" } } ``` ## Related * [List Orders](/api-reference/endpoint/list-orders) * [Create Refund](/api-reference/endpoint/create-refund) * [Order Object](/api-reference/objects/order) * [Webhooks Reference](/developer-manual/webhooks) # Get Payment Link Source: https://docs.withgale.com/api-reference/endpoint/get-payment-link GET /api/v2/payment-links/{id} Retrieve details about a specific payment link # Get Payment Link Retrieve information about a payment link, including its current status and payment details. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `id` | string | Yes | Payment link ID (e.g., `plink_abc123xyz`) | ## Response > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ```json theme={null} { "id": "plink_abc123xyz", "url": "https://checkout.withgale.com/pay/plink_abc123xyz", "amount": 4995, "currency": "USD", "description": "Premium Blood Pressure Monitor", "payment_type": "one_time", "status": "paid", "customer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe" }, "products": [ { "merchant_product_id": "BP-MONITOR-001", "name": "Blood Pressure Monitor", "quantity": 1, "price": 4995, "hsa_fsa_eligible": true } ], "order": { "id": "ord_xyz789", "status": "completed", "paid_at": "2026-02-25T15:30:00Z" }, "success_url": "https://yoursite.com/success", "cancel_url": "https://yoursite.com/cancel", "metadata": { "order_id": "ORD-12345" }, "expires_at": "2026-03-12T14:30:00Z", "created_at": "2026-02-25T14:30:00Z", "paid_at": "2026-02-25T15:30:00Z" } ``` ## Response Fields | Field | Type | Description | | :- | :- | :- | | `id` | string | Unique payment link identifier | | `url` | string | Checkout URL for the payment link | | `amount` | integer | Total amount in cents | | `status` | enum | `active`, `paid`, `expired`, or `cancelled` | | `order` | object | Associated order (present when `status` is `paid`) | | `order.id` | string | Order ID | | `order.status` | enum | Order status | | `order.paid_at` | timestamp | When payment was completed | | `paid_at` | timestamp | When link was paid (null if not paid) | ## Example ```bash theme={null} curl https://api.withgale.com/api/v2/payment-links/plink_abc123xyz \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Payment Link Status | Status | Description | | :- | :- | | `active` | Link is ready to accept payment | | `paid` | Payment completed, order created | | `expired` | Link expired without payment | | `cancelled` | Link was manually cancelled | ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 401 | `unauthorized` | Invalid or missing API key | | 404 | `not_found` | Payment link not found | ## Related * [Create Payment Link](/api-reference/endpoint/create-payment-link) * [List Payment Links](/api-reference/endpoint/list-payment-links) * [Cancel Payment Link](/api-reference/endpoint/cancel-payment-link) * [Order Object](/api-reference/objects/order) # Get a Payment Method Source: https://docs.withgale.com/api-reference/endpoint/get-payment-method GET /api/v2/payment-methods/{payment_method_id} Read one stored card # Get a Payment Method Returns one payment method. ## Endpoint ``` GET /api/v2/payment-methods/{payment_method_id} ``` ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Description | | :- | :- | :- | | `payment_method_id` | string | The payment method ID (`pm_...`) | ## Response ```json theme={null} { "success": true, "data": { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "active", "checkout_id": "cs_abc123", "customer_email": "jane@example.com", "last_used_at": null, "created_at": "2026-11-10T21:04:11Z" } } ``` ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 401 | `unauthorized` | Invalid API key | | 404 | `PAYMENT_METHOD_001` | Unknown ID, or a payment method stored in the other mode (test or live) | ## Related * [Payment Method Object](/api-reference/objects/payment-method) * [Charge a Payment Method](/api-reference/endpoint/charge-payment-method) # Get Product Source: https://docs.withgale.com/api-reference/endpoint/get-product-v2 GET /api/v2/products/{id} Retrieve a product, including its current HSA/FSA eligibility and image URLs # Get Product Returns one product from your merchant site. Use it to read the current eligibility and images. > [!NOTE] > > Use the Gale product `id` from the create response. This endpoint does not accept your `merchant_product_id`. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `id` | integer | Yes | Gale product ID, from the create response | ## Request ```bash theme={null} GET /api/v2/products/{id} ``` ## Response Returns `200 OK` with the product in `data`. See [Product Object](/api-reference/objects/product) for every field. ```json theme={null} { "success": true, "message": "Product retrieved successfully", "data": { "id": 12345, "name": "Digital Blood Pressure Monitor", "tagline": "FDA-approved automatic BP monitor", "description": "Clinically validated blood pressure monitor with Bluetooth connectivity.", "price_cents": 4995, "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "status": "active", "eligibility": { "hsa_fsa_eligible": true, "eligibility_type": "auto_substantiation", "reason": "SIGIS auto-substantiation", "checked_at": "2026-11-05T12:05:00+00:00" }, "images": [ "https://cdn.example.com/bp-monitor-1.jpg", "https://cdn.example.com/bp-monitor-2.jpg" ], "created_at": "2026-11-05T12:00:00+00:00", "updated_at": "2026-11-05T12:05:00+00:00" }, "metadata": { "processing_time_ms": 8 } } ``` `eligibility.checked_at` is the time the product was last updated. It is not a separate eligibility check time. ## Examples ```bash theme={null} curl https://api.withgale.com/api/v2/products/12345 \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | HTTP status | `error.code` | When | | - | - | - | | 401 | | Missing, malformed, or invalid API key | | 404 | `NOT_FOUND` | No product with this `id` on your merchant site. Deleted products also return 404 | | 429 | `RATE_LIMIT_EXCEEDED` | More than 500 product reads per minute for this merchant | | 500 | `INTERNAL_ERROR` | Something went wrong on Gale's side. Retry later | Example error: ```json theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Product not found", "type": "client_error" } } ``` ## Related * [Create Product](/api-reference/endpoint/create-product-v2) - POST /api/v2/products * [Update Product](/api-reference/endpoint/update-product-v2) - PUT /api/v2/products/ * [List Products](/api-reference/endpoint/list-products-v2) - GET /api/v2/products * [Product Object](/api-reference/objects/product) # Get Subscription Source: https://docs.withgale.com/api-reference/endpoint/get-subscription GET /api/v2/subscriptions/{id} Retrieve details about a specific subscription # Get Subscription Retrieve information about a subscription, including its current status and next billing date. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Subscription ID (e.g., `sub_abc123xyz`) | ## Request ```bash theme={null} GET /api/v2/subscriptions/{id} ``` ## Response ```json theme={null} { "id": "sub_abc123xyz", "customer_id": "cus_xyz789", "status": "active", "product_id": 12345, "amount_cents": 9900, "currency": "USD", "interval": "monthly", "interval_count": 1, "current_period_start": "2025-10-18T14:30:00Z", "current_period_end": "2025-11-18T14:30:00Z", "next_billing_date": "2025-11-18T14:30:00Z", "cancel_at_period_end": false, "payment_method": { "type": "hsa_fsa_card", "last4": "1111", "brand": "visa" }, "created_at": "2025-10-18T14:30:00Z", "updated_at": "2025-10-18T14:30:00Z" } ``` See [Subscription Object](/api-reference/objects/subscription) for complete field descriptions. ## Examples ### Basic Retrieval ```bash theme={null} curl https://api.withgale.com/api/v2/subscriptions/sub_abc123xyz \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### With JavaScript ```javascript theme={null} const getSubscription = async (subscriptionId) => { const response = await fetch( `https://api.withgale.com/api/v2/subscriptions/${subscriptionId}`, { headers: { 'Authorization': `Bearer ${process.env.GALE_API_KEY}` } } ); return await response.json(); }; // Check subscription status const sub = await getSubscription('sub_abc123xyz'); console.log(`Status: ${sub.status}`); console.log(`Next billing: ${sub.next_billing_date}`); ``` ## Related Endpoints * [Create Subscription](/api-reference/endpoint/create-subscription) * [List Subscriptions](/api-reference/endpoint/list-subscriptions) * [Cancel Subscription](/api-reference/endpoint/cancel-subscription) # List Orders Source: https://docs.withgale.com/api-reference/endpoint/list-orders GET /api/v2/orders Retrieve a list of all orders with optional filtering # List Orders Returns a paginated list of orders, ordered by creation date (most recent first). Supports filtering by status, customer, payment status, and date range. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Description | | - | - | - | | `limit` | integer | Number of results per page (default: 10, max: 100) | | `starting_after` | string | Cursor for pagination (order ID) | | `status` | enum | Filter by status: `pending`, `processing`, `completed`, `failed`, `cancelled` | | `payment_status` | enum | Filter by payment status: `pending`, `authorized`, `captured`, `failed`, `refunded`, `disputed` | | `customer_email` | string | Filter by customer email | | `created_after` | timestamp | Filter orders created after this date | | `created_before` | timestamp | Filter orders created before this date | ## Request ```bash theme={null} GET /api/v2/orders?limit=10&status=completed ``` ## Response > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ```json theme={null} { "data": [ { "id": "ord_abc123", "order_number": "ORD-2025-001234", "status": "completed", "payment_status": "captured", "customer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe" }, "amounts": { "total": 4235, "hsa_amount": 2995, "regular_amount": 0 }, "payment": { "payment_method": "hsa_fsa_card", "last4": "1111" }, "created_at": "2025-10-18T15:00:00Z", "completed_at": "2025-10-18T15:30:00Z" }, { "id": "ord_def456", "order_number": "ORD-2025-001235", "status": "completed", "payment_status": "captured", "customer": { "email": "member@example.com", "first_name": "John", "last_name": "Smith" }, "amounts": { "total": 9900, "hsa_amount": 9900, "regular_amount": 0 }, "payment": { "payment_method": "hsa_fsa_card", "last4": "2222" }, "created_at": "2025-10-17T10:00:00Z", "completed_at": "2025-10-17T10:15:00Z" } ], "has_more": true, "next_cursor": "ord_def456" } ``` ## Response Fields | Field | Type | Description | | - | - | - | | `data` | array | Array of order objects | | `has_more` | boolean | Whether more results are available | | `next_cursor` | string | Cursor for next page (use as `starting_after`) | ## Examples ### List All Orders ```bash theme={null} curl https://api.withgale.com/api/v2/orders \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Filter by Status ```bash theme={null} curl "https://api.withgale.com/api/v2/orders?status=completed&limit=50" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Filter by Payment Status ```bash theme={null} curl "https://api.withgale.com/api/v2/orders?payment_status=captured" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Filter by Customer ```bash theme={null} curl "https://api.withgale.com/api/v2/orders?customer_email=jane@example.com" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | Status Code | Error Code | Description | | - | - | - | | 400 | `invalid_request` | Invalid query parameters | | 401 | `unauthorized` | Invalid or missing API key | | 429 | `rate_limit_exceeded` | Too many requests | Example error: ```json theme={null} { "error": { "code": "invalid_request", "message": "Invalid status value", "param": "status" } } ``` ## Related * [Get Order](/api-reference/endpoint/get-order) * [Create Refund](/api-reference/endpoint/create-refund) * [Order Object](/api-reference/objects/order) * [Webhooks Reference](/developer-manual/webhooks) # List Payment Links Source: https://docs.withgale.com/api-reference/endpoint/list-payment-links GET /api/v2/payment-links Retrieve a list of all payment links with optional filtering # List Payment Links Returns a paginated list of payment links, ordered by creation date (most recent first). Supports filtering by status, customer, and date range. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Description | | :- | :- | :- | | `limit` | integer | Number of results per page (default: 10, max: 100) | | `starting_after` | string | Cursor for pagination (payment link ID) | | `status` | enum | Filter by status: `active`, `paid`, `expired`, `cancelled` | | `customer_email` | string | Filter by customer email | | `payment_type` | enum | Filter by type: `one_time`, `subscription` | | `created_after` | timestamp | Filter links created after this date | | `created_before` | timestamp | Filter links created before this date | ## Response > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ```json theme={null} { "data": [ { "id": "plink_abc123", "url": "https://checkout.withgale.com/pay/plink_abc123", "amount": 4995, "currency": "USD", "description": "Blood Pressure Monitor", "payment_type": "one_time", "status": "paid", "customer": { "email": "customer@example.com" }, "order": { "id": "ord_xyz789" }, "created_at": "2026-02-25T14:30:00Z", "paid_at": "2026-02-25T15:30:00Z" } ], "has_more": true, "next_cursor": "plink_abc123" } ``` ## Response Fields | Field | Type | Description | | :- | :- | :- | | `data` | array | Array of payment link objects | | `has_more` | boolean | Whether more results are available | | `next_cursor` | string | Cursor for next page (use as `starting_after`) | ## Examples ### List All ```bash theme={null} curl https://api.withgale.com/api/v2/payment-links \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Filter by Status ```bash theme={null} curl "https://api.withgale.com/api/v2/payment-links?status=paid&limit=50" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Filter by Customer ```bash theme={null} curl "https://api.withgale.com/api/v2/payment-links?customer_email=jane@example.com" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 400 | `invalid_request` | Invalid query parameters | | 401 | `unauthorized` | Invalid or missing API key | ## Related * [Create Payment Link](/api-reference/endpoint/create-payment-link) * [Get Payment Link](/api-reference/endpoint/get-payment-link) * [Cancel Payment Link](/api-reference/endpoint/cancel-payment-link) # List Payment Methods Source: https://docs.withgale.com/api-reference/endpoint/list-payment-methods GET /api/v2/payment-methods List the cards your shoppers have stored # List Payment Methods Returns the payment methods stored for your account in the mode of the API key (test or live). ## Endpoint ``` GET /api/v2/payment-methods ``` ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `checkout_id` | string | No | Only the payment method stored by this checkout | | `customer_email` | string | No | Only payment methods stored by this customer | | `limit` | integer | No | Maximum number to return, 1 to 100 | ## Response ```json theme={null} { "success": true, "data": [ { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "active", "checkout_id": "cs_abc123", "customer_email": "jane@example.com", "last_used_at": "2026-12-10T09:15:02Z", "created_at": "2026-11-10T21:04:11Z" } ] } ``` ## Example ```bash theme={null} curl "https://api.withgale.com/api/v2/payment-methods?customer_email=jane@example.com" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | Status Code | Error Code | Description | | :- | :- | :- | | 401 | `unauthorized` | Invalid API key | | 404 | `PAYMENT_METHOD_001` | Saved payment methods are not enabled for this account | ## Related * [Payment Method Object](/api-reference/objects/payment-method) * [Get a Payment Method](/api-reference/endpoint/get-payment-method) # List Products Source: https://docs.withgale.com/api-reference/endpoint/list-products-v2 GET /api/v2/products List the products in your catalog, with page-based pagination and filters for search, eligibility, and status # List Products Returns one page of products from your merchant site, newest first by default. Use `page` and `per_page` to move through the catalog. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `page` | integer | `1` | Page number | | `per_page` | integer | `50` | Products per page. Maximum 100 | | `search` | string | | Partial match on the product `name` or `description`. Does not search `merchant_product_id` or the UPC | | `hsa_fsa_eligible` | boolean | | `true` or `false` | | `status` | string | | `ACTIVE` or `INACTIVE`. Send the uppercase value, as it is stored | | `sort` | string | `created_at` | Field to sort by, for example `created_at`, `updated_at`, or `name` | | `order` | string | `desc` | `asc` or `desc` | > [!NOTE] > > This endpoint uses `page` and `per_page`. It does not support `limit`, `starting_after`, or a cursor. There is no filter by `merchant_product_id`. To find a product by your SKU, store the Gale `id` from the create response. ## Request ```bash theme={null} GET /api/v2/products?per_page=50&hsa_fsa_eligible=true ``` ## Response Returns `200 OK`. The products are in `data.products`, and the paging details are in `data.pagination`. ```json theme={null} { "success": true, "message": "Success", "data": { "products": [ { "id": 12345, "name": "Digital Blood Pressure Monitor", "tagline": "FDA-approved automatic BP monitor", "description": "Clinically validated blood pressure monitor with Bluetooth connectivity.", "price_cents": 4995, "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "status": "active", "eligibility": { "hsa_fsa_eligible": true, "eligibility_type": "auto_substantiation", "reason": "SIGIS auto-substantiation", "checked_at": "2026-11-05T12:05:00+00:00" }, "images": [ "https://cdn.example.com/bp-monitor-1.jpg" ], "created_at": "2026-11-05T12:00:00+00:00", "updated_at": "2026-11-05T12:05:00+00:00" } ], "pagination": { "current_page": 1, "per_page": 50, "total": 120, "total_pages": 3 } }, "metadata": { "processing_time_ms": 21 } } ``` | Field | Type | Description | | - | - | - | | `data.products` | array | Product objects on this page | | `data.pagination.current_page` | integer | The page returned | | `data.pagination.per_page` | integer | Products per page used for this response | | `data.pagination.total` | integer | Total products that match the filters | | `data.pagination.total_pages` | integer | Number of pages | To read every product, start at `page=1` and increase `page` until it passes `total_pages`. ## Examples ### List all products ```bash theme={null} curl https://api.withgale.com/api/v2/products \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Search active products ```bash theme={null} curl "https://api.withgale.com/api/v2/products?search=thermometer&status=ACTIVE&per_page=100" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Filter by HSA/FSA eligibility ```bash theme={null} curl "https://api.withgale.com/api/v2/products?hsa_fsa_eligible=true&page=2" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Errors | HTTP status | `error.code` | When | | - | - | - | | 401 | | Missing, malformed, or invalid API key | | 429 | `RATE_LIMIT_EXCEEDED` | More than 500 product reads per minute for this merchant | | 500 | `INTERNAL_ERROR` | Something went wrong on Gale's side. Retry later | ## Related * [Create Product](/api-reference/endpoint/create-product-v2) - POST /api/v2/products * [Get Product](/api-reference/endpoint/get-product-v2) - GET /api/v2/products/ * [Update Product](/api-reference/endpoint/update-product-v2) - PUT /api/v2/products/ * [Product Object](/api-reference/objects/product) # List Subscriptions Source: https://docs.withgale.com/api-reference/endpoint/list-subscriptions GET /api/v2/subscriptions Retrieve a list of all subscriptions with optional filtering # List Subscriptions Returns a paginated list of subscriptions, ordered by creation date (most recent first). ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Description | | - | - | - | | `limit` | integer | Number of results per page (default: 10, max: 100) | | `starting_after` | string | Cursor for pagination (subscription ID) | | `status` | enum | Filter by status: `trialing`, `active`, `past_due`, `cancelled`, `ended` | | `customer_id` | string | Filter by customer ID | ## Request ```bash theme={null} GET /api/v2/subscriptions?limit=10&status=active ``` ## Response ```json theme={null} { "data": [ { "id": "sub_abc123", "customer_id": "cus_xyz789", "status": "active", "amount_cents": 9900, "interval": "monthly", "next_billing_date": "2025-11-18T14:30:00Z", "created_at": "2025-10-18T14:30:00Z" } ], "has_more": true, "next_cursor": "sub_abc123" } ``` ## Examples ```bash theme={null} curl "https://api.withgale.com/api/v2/subscriptions?status=active" \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Related Endpoints * [Get Subscription](/api-reference/endpoint/get-subscription) * [Create Subscription](/api-reference/endpoint/create-subscription) # Update Product Source: https://docs.withgale.com/api-reference/endpoint/update-product-v2 PUT /api/v2/products/{id} Update a product's name, price, status, UPC, or merchant product ID. Changing the UPC checks eligibility again. # Update Product Changes the fields you send on an existing product. Fields you leave out keep their current values. > [!NOTE] > > Use the Gale product `id` from the create response in the path. ## Authentication ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` ## Path Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `id` | integer | Yes | Gale product ID | ## Request Body ```json theme={null} { "name": "Premium Blood Pressure Monitor", "tagline": "Professional-grade automatic BP monitoring", "description": "Updated description with new features", "price_cents": 5495, "status": "ACTIVE" } ``` ## Parameters All parameters are optional. Send only the fields you want to change. | Parameter | Type | Description | | - | - | - | | `name` | string | Product name | | `tagline` | string | Short description | | `description` | string | Full product description | | `price_cents` | integer | Price in cents | | `merchant_product_id` | string | Your SKU or product ID. Checkout matches on this value | | `upc_code_or_gtin` | string | UPC or GTIN. Sending a value checks eligibility again | | `status` | string | `ACTIVE` or `INACTIVE`. Send the uppercase value, as it is stored | Update does not change `images` or `currency`. Fields that are not listed here, such as `metadata`, are ignored. Send `price_cents`, not `price`. A `price` field is ignored and the request still returns `200`. Update does not run the create validation rules, so send values in the same format as on create. ## Response Returns `200 OK` with the updated product in `data`. ```json theme={null} { "success": true, "message": "Product updated successfully", "data": { "id": 12345, "name": "Premium Blood Pressure Monitor", "tagline": "Professional-grade automatic BP monitoring", "description": "Updated description with new features", "price_cents": 5495, "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "status": "active", "eligibility": { "hsa_fsa_eligible": true, "eligibility_type": "auto_substantiation", "reason": "SIGIS auto-substantiation", "checked_at": "2026-11-05T16:00:00+00:00" }, "images": [], "created_at": "2026-11-05T12:00:00+00:00", "updated_at": "2026-11-05T16:00:00+00:00" }, "metadata": { "processing_time_ms": 10 } } ``` The response returns `"images": []` even when the product has images. Call [Get Product](/api-reference/endpoint/get-product-v2) to read the current image URLs. ## Examples ### Update price ```bash theme={null} curl -X PUT https://api.withgale.com/api/v2/products/12345 \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "price_cents": 5495 }' ``` ### Deactivate a product ```bash theme={null} curl -X PUT https://api.withgale.com/api/v2/products/12345 \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "status": "INACTIVE" }' ``` ## Errors | HTTP status | `error.code` | When | | - | - | - | | 401 | | Missing, malformed, or invalid API key | | 404 | `NOT_FOUND` | No product with this `id` on your merchant site | | 409 | `DUPLICATE_REQUEST` | The same `Idempotency-Key` is still being processed | | 429 | `RATE_LIMIT_EXCEEDED` | More than 100 product writes per minute for this merchant | | 500 | `INTERNAL_ERROR` | Something went wrong on Gale's side. Retry later | Update accepts an `Idempotency-Key` header. The rules are the same as on [Create Product](/api-reference/endpoint/create-product-v2#idempotency). ## Related * [Create Product](/api-reference/endpoint/create-product-v2) - POST /api/v2/products * [Get Product](/api-reference/endpoint/get-product-v2) - GET /api/v2/products/ * [List Products](/api-reference/endpoint/list-products-v2) - GET /api/v2/products * [Product Object](/api-reference/objects/product) # Introduction Source: https://docs.withgale.com/api-reference/introduction Complete reference for all Gale API endpoints - products, checkout, orders, payments, and subscriptions. # API Reference Complete documentation for Gale's REST API. Each endpoint includes request/response formats, authentication details, and working code examples. See [Authentication](/developer-manual/authentication) for API keys and setup. *** > [card] [Products](/api-reference/endpoint/list-products-v2) > > Create, list, update, and check HSA/FSA eligibility for products. > [card] [Checkout](/api-reference/endpoint/create-checkout-v2) > > Create checkout sessions for hosted payment pages. > [card] [Orders](/api-reference/endpoint/list-orders) > > View orders, process refunds, and track payment status. > [card] [Payment Links](/api-reference/endpoint/create-payment-link) > > Generate shareable payment URLs for off-platform payments. > [card] [Subscriptions](/api-reference/endpoint/create-subscription) > > Create and manage recurring billing subscriptions. > [card] [Webhooks](/developer-manual/webhooks) > > Receive real-time events for orders, payments, and subscriptions. # Checkout Session Object Source: https://docs.withgale.com/api-reference/objects/checkout-session A temporary checkout session that leads to an Order when paid # Checkout Session Object A checkout session represents a temporary payment intent created when you redirect customers to Gale's hosted checkout page. When the customer completes payment, the session converts to an **Order**. > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). **Checkout sessions are ephemeral** — they expire after 24 hours. The **Order** object is your permanent payment record. ## The Checkout Session Object ```json theme={null} { "checkout_id": "01HXYZ...", "checkout_url": "https://checkout.withgale.com/checkout/01HXYZ...", "reference_id": "your-order-123", "status": "open", "type": "eligible", "customer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe", "phone": "+1-555-123-4567" }, "line_items": [ { "product_id": "PROD-001", "name": "Digital Thermometer", "image_url": "https://yourcdn.com/thermometer.jpg", "price": 2995, "quantity": 1, "total": 2995, "currency": "USD", "hsa_fsa_eligible": true } ], "shipping_info": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "amounts": { "subtotal": 2995, "hsa_amount": 2995, "regular_amount": 0, "shipping": 995, "tax": 245, "discount": 0, "total": 4235 }, "success_url": "https://yoursite.com/order/success", "failure_url": "https://yoursite.com/order/failed", "metadata": { "platform": "custom" }, "order_id": null, "expires_at": "2026-02-26T14:30:00Z", "created_at": "2026-02-25T14:30:00Z" } ``` ## Attributes | Attribute | Type | Description | | - | - | - | | `checkout_id` | string | Unique checkout session identifier | | `checkout_url` | string | Hosted checkout page URL to redirect customer | | `reference_id` | string | Your order/cart ID for correlation | | `status` | enum | Session status (see below) | | `type` | enum | Checkout type: `eligible`, `split`, or `regular` | | `customer` | object | Customer information | | `line_items` | array | Products being purchased | | `shipping_info` | object | Shipping address | | `billing_info` | object | Billing address | | `amounts` | object | Price breakdown | | `success_url` | string | Redirect URL after successful payment | | `failure_url` | string | Redirect URL if payment fails or customer cancels | | `metadata` | object | Custom key-value pairs | | `setup_future_usage` | string | `off_session` when the checkout stores the shopper's card for later charges. Absent otherwise | | `payment_method` | object | The stored card, on a checkout that asked for storage. `null` until paid. See [Payment Method Object](/api-reference/objects/payment-method) | | `order_id` | string | Created order ID (null until paid) | | `expires_at` | timestamp | When session expires (24 hours) | | `created_at` | timestamp | When session was created | ### On a checkout that stores a card A checkout created with `setup_future_usage: "off_session"` carries two more fields, on two different calls. [Create Checkout Session](/api-reference/endpoint/create-checkout-v2) returns `setup_future_usage`: ```json theme={null} { "checkout_id": "cs_abc123", "status": "open", "setup_future_usage": "off_session" } ``` [Get Checkout Status](/api-reference/endpoint/get-checkout) returns `payment_method`. It is `null` until the shopper has paid, then it holds the stored card: ```json theme={null} { "checkout_id": "cs_abc123", "status": "completed", "payment_method": { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "active" } } ``` The same `payment_method` is sent on the `order.completed` and `payment_method.saved` webhooks. See [Saved Payment Methods](/integration/saved-payment-methods). ### Metadata that Gale reads `metadata` holds your own key-value pairs. Gale acts on these keys: | Key | Value | Effect | | - | - | - | | `payment_source` | `stripe_elements_cpm` | Pay with HSA/FSA is in your Stripe Payment Element. The payment is written to your Stripe account as a payment record. See [Stripe Payment Element](/custom-payment-methods/elements-payment-intent) | | `stripe_customer_id` | `cus_...` | With `stripe_invoice_id`, ties the payment to a Stripe Billing invoice. See [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing) | | `stripe_invoice_id` | `in_...` | The open Stripe invoice this payment settles | ## Line Item Attributes | Attribute | Type | Description | | - | - | - | | `product_id` | string | Your product ID | | `name` | string | Product name | | `image_url` | string | Product image URL | | `price` | integer | Unit price in cents | | `quantity` | integer | Quantity ordered | | `total` | integer | Line total in cents (price x quantity) | | `currency` | string | Currency code | | `hsa_fsa_eligible` | boolean | Whether this item is HSA/FSA eligible | ## Checkout Session Status | Status | Description | | - | - | | `open` | Session created, awaiting customer | | `paid` | Customer completed payment, order created | | `expired` | Session expired (24 hours passed) | > [!NOTE] > > These are the values on the object returned when you create a checkout. `GET /api/v2/checkout/{checkout_id}` reports progress with its own values: `pending`, `completed`, `failed` and `expired`. See [Get Checkout Status](/api-reference/endpoint/get-checkout). ## Checkout Type Gale automatically determines the type based on product eligibility: | Type | Description | | - | - | | `eligible` | All items are HSA/FSA eligible | | `split` | Mix of eligible and non-eligible items | | `regular` | No items are eligible | ## Lifecycle ``` open → paid (payment succeeds, Order created) ↓ expired (24 hours, no payment) ``` When status becomes `paid`: * An **Order** is created * `order_id` field is populated * `order.completed` webhook fires * Customer redirects to `success_url` ## Tracking Checkout Status ```bash theme={null} GET /api/v2/checkout/{checkout_id} ``` The full response, with the `order` object and the stored card, is on [Get Checkout Status](/api-reference/endpoint/get-checkout). **Response when open:** ```json theme={null} { "checkout_id": "01HXYZ...", "status": "open", "order_id": null, "expires_at": "2026-02-26T14:30:00Z" } ``` **Response when paid:** ```json theme={null} { "checkout_id": "01HXYZ...", "status": "paid", "order_id": "ord_abc123", "paid_at": "2026-02-25T15:30:00Z" } ``` Once paid, query the **Order** for full payment details: ```bash theme={null} GET /api/v2/orders/{order_id} ``` ## Amounts Object ```json theme={null} { "amounts": { "subtotal": 2995, "hsa_amount": 2995, "regular_amount": 0, "shipping": 995, "tax": 245, "discount": 0, "total": 4235 } } ``` | Field | Description | | - | - | | `subtotal` | Sum of all line item totals | | `hsa_amount` | Amount payable with HSA/FSA | | `regular_amount` | Amount requiring regular payment | | `shipping` | Shipping cost | | `tax` | Tax amount | | `discount` | Discount applied | | `total` | Final total charged | Gale automatically calculates how much can be paid with HSA/FSA vs regular payment methods based on product eligibility. ## Subscription Sessions For subscription checkouts, include subscription details: ```json theme={null} { "payment_type": "subscription", "subscription": { "interval": "monthly", "interval_count": 1, "trial_period_days": 14 } } ``` When paid, creates both an **Order** and a **Subscription** object. > [!NOTE] > > Subscription checkout is currently in Beta. ## Webhooks Checkout sessions trigger these webhooks: * `order.completed` — Payment succeeded, order created (this is what you should listen to) * `order.failed` — Payment failed **Note:** Listen to `order.completed` to confirm payment. ## Best Practices **Don't poll for status** — Use webhooks instead: ```javascript theme={null} // Prefer: Webhooks app.post('/webhooks/gale', (req, res) => { if (req.body.type === 'order.completed') { await fulfillOrder(req.body.data); } res.status(200).send('OK'); }); ``` **Sessions expire** — Don't store checkout URLs. Create new sessions for each purchase attempt. **Order is your source of truth** — Once paid, always reference the Order object, not the checkout session. ## Related Endpoints * [Create Checkout Session](/api-reference/endpoint/create-checkout-v2) — POST /api/v2/checkout * [Get Checkout Session](/api-reference/endpoint/get-checkout) — GET /api/v2/checkout/ * [List Orders](/api-reference/endpoint/list-orders) — GET /api/v2/orders ## Related Objects * [Order Object](/api-reference/objects/order) — Permanent payment record * [Product Object](/api-reference/objects/product) — Items being purchased * [Subscription Object](/api-reference/objects/subscription) — For recurring payments # Order Object Source: https://docs.withgale.com/api-reference/objects/order The Order object represents a completed or in-progress purchase created from a checkout session or payment link # Order Object When a payment is successfully processed — via checkout session or payment link — an Order is created. Orders track payment status, fulfillment, and provide an immutable record of the transaction. > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ## The Order Object ```json theme={null} { "id": "ord_01ABC...", "checkout_id": "cs_abc123", "reference_id": "your-order-123", "payment_link_id": null, "client_reference_id": null, "status": "completed", "is_recurring": false, "payment_status": "captured", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe", "phone": "+1-555-123-4567", "shipping_address": { "address_line_1": "123 Main St", "address_line_2": "Apt 4B", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "billing_address": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" } }, "line_items": [ { "id": "li_123", "product_id": "PROD-001", "name": "Digital Thermometer", "quantity": 1, "price": 2995, "hsa_fsa_eligible": true, "is_recurring": false } ], "amounts": { "subtotal": 2995, "hsa_amount": 2995, "regular_amount": 0, "shipping": 995, "tax": 245, "discount": 0, "total": 4235 }, "payment": { "payment_id": "pay_xyz789", "payment_method": "hsa_fsa_card", "last4": "1111", "brand": "visa", "captured_at": "2026-02-25T15:30:00Z" }, "metadata": { "order_number": "ORDER-12345", "platform": "CUSTOM" }, "created_at": "2026-02-25T15:00:00Z", "completed_at": "2026-02-25T15:30:00Z", "status_history": [ { "status": "pending", "timestamp": "2026-02-25T15:00:00Z", "reason": "Order created" }, { "status": "processing", "timestamp": "2026-02-25T15:01:00Z", "reason": "Payment processing" }, { "status": "completed", "timestamp": "2026-02-25T15:30:00Z", "reason": "Payment captured" } ] } ``` ## Attributes | Attribute | Type | Description | | - | - | - | | `id` | string | Unique order identifier (`ord_xxx`) | | `checkout_id` | string | Checkout session ID (`cs_xxx`) | | `reference_id` | string | Your order/cart reference — set for checkout session orders, null for payment link orders | | `payment_link_id` | string | Payment link ID — set for payment link orders, null for checkout session orders | | `client_reference_id` | string | Your reference passed via payment link — set for payment link orders, null for checkout session orders | | `status` | enum | Fulfillment status (see below) | | `is_recurring` | boolean | `true` if this is a subscription/recurring order, `false` for one-time purchases | | `payment_status` | enum | Payment state (see below) | | `amount` | integer | Order total in cents | | `currency` | string | Lowercase ISO currency code (e.g. `usd`) | | `customer` | object | Customer name and email | | `line_items` | array | Ordered items (snapshot at time of purchase) | | `created_at` | timestamp | When order was created | ## Amounts Object | Field | Type | Description | | - | - | - | | `subtotal` | integer | Sum of all line item totals | | `hsa_amount` | integer | Amount payable with HSA/FSA | | `regular_amount` | integer | Amount requiring regular payment | | `shipping` | integer | Shipping cost | | `tax` | integer | Tax amount | | `discount` | integer | Discount applied | | `total` | integer | Final total charged | ## Line Item Attributes | Attribute | Type | Description | | - | - | - | | `id` | string | Line item identifier | | `product_id` | string | Your product ID | | `name` | string | Product name | | `quantity` | integer | Quantity ordered | | `price` | integer | Unit price in cents | | `hsa_fsa_eligible` | boolean | Whether this item is HSA/FSA eligible | | `is_recurring` | boolean | Whether this line item is a recurring/subscription item | ## Order Status | Status | Description | | - | - | | `pending` | Order created, awaiting payment | | `processing` | Payment being processed | | `completed` | Payment successful, order complete | | `failed` | Payment failed | | `cancelled` | Order cancelled | ## Payment Status | Status | Description | | - | - | | `pending` | Payment not yet attempted | | `authorized` | Payment authorized (not captured) | | `captured` | Payment captured successfully | | `failed` | Payment failed | | `refunded` | Payment refunded (full or partial) | | `disputed` | Payment disputed/chargebacked | ## Order Lifecycle An order moves through these states: * **pending** - Order created, awaiting payment * **processing** - Payment initiated * **completed** - Payment captured successfully * **failed** - Payment declined or failed * **cancelled** - Order cancelled by customer or merchant * **refunded** - Completed order was refunded (full or partial) * **disputed** - Completed order has a chargeback filed ## Status History Track all status changes: ```json theme={null} { "status_history": [ { "status": "pending", "timestamp": "2026-02-25T15:00:00Z", "reason": "Order created" }, { "status": "processing", "timestamp": "2026-02-25T15:01:00Z", "reason": "Customer submitted payment" }, { "status": "completed", "timestamp": "2026-02-25T15:30:00Z", "reason": "Payment captured successfully" } ] } ``` ## Related Endpoints * [Get Order](/api-reference/endpoint/get-order) - GET /api/v2/orders/ * [List Orders](/api-reference/endpoint/list-orders) - GET /api/v2/orders * [Refund Order](/api-reference/endpoint/create-refund) - POST /api/v2/refunds # Payment Method Object Source: https://docs.withgale.com/api-reference/objects/payment-method A shopper's card stored for charges you start later # Payment Method Object A payment method is a card a shopper stored during a checkout created with `setup_future_usage: "off_session"`. You charge it later with [Charge a Payment Method](/api-reference/endpoint/charge-payment-method). The card number is never returned. ## The Payment Method Object ```json theme={null} { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "active", "checkout_id": "cs_abc123", "customer_email": "jane@example.com", "last_used_at": null, "created_at": "2026-11-10T21:04:11Z" } ``` ## Attributes | Attribute | Type | Description | | :- | :- | :- | | `id` | string | Payment method identifier (`pm_...`). Use it in the charge, read and remove calls | | `type` | string | Always `card` | | `brand` | string | Card brand, for example `visa` or `mc` | | `last4` | string | Last four digits of the card | | `exp_month` | string | Expiry month, two digits | | `exp_year` | string | Expiry year, four digits | | `usage` | enum | `off_session` when the shopper agreed to charges you start later | | `status` | enum | `active` or `disabled`. A disabled payment method cannot be charged | | `checkout_id` | string | The checkout session that stored the card | | `customer_email` | string | Email of the customer on that checkout | | `last_used_at` | timestamp | Time of the last successful charge, or `null` | | `created_at` | timestamp | When the card was stored | ## Where it appears * `GET /api/v2/checkout/{checkout_id}` for a checkout that asked for storage * The `payment_method.saved` webhook * The `order.completed` webhook for the order that stored the card, and for every order charged to it * Every response from the payment method endpoints ## Test and live A payment method stored with a `glm_test_` key exists only in test mode, and one stored with a `glm_live_` key exists only in live mode. A key from the other mode gets `404`. ## Related * [Saved Payment Methods guide](/integration/saved-payment-methods) * [Charge a Payment Method](/api-reference/endpoint/charge-payment-method) * [List Payment Methods](/api-reference/endpoint/list-payment-methods) * [Webhooks](/developer-manual/webhooks) # Product Object Source: https://docs.withgale.com/api-reference/objects/product The Product object represents an item you sell, with HSA/FSA eligibility from its UPC or GTIN # Product Object The Product object is an item in your catalog. Gale sets its HSA/FSA eligibility from the UPC or GTIN. > [!NOTE] > > All monetary amounts are integers in cents (e.g., 4995 = \$49.95). ## The Product Object ```json theme={null} { "id": 12345, "name": "Digital Blood Pressure Monitor", "tagline": "FDA-approved automatic BP monitor", "description": "Clinically validated blood pressure monitor with Bluetooth connectivity.", "price_cents": 4995, "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "status": "active", "eligibility": { "hsa_fsa_eligible": true, "eligibility_type": "auto_substantiation", "reason": "SIGIS auto-substantiation", "checked_at": "2026-11-05T12:00:00+00:00" }, "images": [ "https://cdn.example.com/bp-monitor-1.jpg", "https://cdn.example.com/bp-monitor-2.jpg" ], "created_at": "2026-11-05T12:00:00+00:00", "updated_at": "2026-11-05T12:00:00+00:00" } ``` ## Attributes | Attribute | Type | Description | | - | - | - | | `id` | integer | Gale product ID. Use it in the path for get, update, and delete | | `name` | string | Product name (max 255 chars) | | `tagline` | string or null | Short description (max 255 chars) | | `description` | string or null | Full product description | | `price_cents` | integer | Price in cents | | `merchant_product_id` | string or null | Your SKU or product ID. Checkout matches `line_items[].product_id` to this value | | `upc_code_or_gtin` | string or null | UPC or GTIN barcode used for SIGIS eligibility | | `status` | string | `active` or `inactive` in responses. Send `ACTIVE` or `INACTIVE` in requests | | `eligibility` | object | HSA/FSA eligibility. See [Eligibility Object](#eligibility-object) | | `images` | array of strings | Image URLs. Empty when the product has no images | | `created_at` | string | When the product was created, in ISO 8601 | | `updated_at` | string | When the product was last updated, in ISO 8601 | Currency is accepted when you create a product, but the API does not return it. ## Eligibility Object | Field | Type | Description | | - | - | - | | `hsa_fsa_eligible` | boolean | Whether the product is HSA/FSA eligible | | `eligibility_type` | string or null | The basis for eligibility, such as `auto_substantiation`. `null` when no type is set | | `reason` | string | Short, human-readable reason for the result | | `checked_at` | string | The product's last update time. This is not a separate eligibility check time | ### How eligibility is set | Situation | Result | | - | - | | UPC or GTIN matches an active SIGIS entry | `hsa_fsa_eligible: true`, `eligibility_type: "auto_substantiation"` | | No UPC or GTIN, or the code is not in SIGIS | `hsa_fsa_eligible: false`, `eligibility_type: null`. Gale reviews the product and can set a type | | Gale sets a manual type | The type is kept when the UPC changes. You cannot set it through the API | Gale can set these eligibility types: `auto_substantiation`, `vision`, `rx`, `dual_purpose`, `prescription`, `medical_mcc`, and `partially_eligible`. Eligibility is checked against the UPC or GTIN only. The product name and description are not used. Use an 11-digit UPC, a 12-digit UPC-A, or a 14-digit GTIN. Other lengths, such as the 13-digit EAN-13, do not match SIGIS. ## Status Create always stores `ACTIVE` and does not read `status` from the request. To change status, use [Update Product](/api-reference/endpoint/update-product-v2). Update stores the value you send, so use the uppercase form, `ACTIVE` or `INACTIVE`. Responses return the value in lowercase. Filters on [List Products](/api-reference/endpoint/list-products-v2) use the same uppercase values. ## Examples ### Required fields only ```json theme={null} { "name": "Digital Thermometer", "price_cents": 2995, "currency": "USD" } ``` ### Complete product ```json theme={null} { "name": "Premium Blood Pressure Monitor", "tagline": "Professional-grade BP monitoring", "description": "Clinically validated automatic blood pressure monitor with irregular heartbeat detection and Bluetooth connectivity.", "price_cents": 4995, "currency": "USD", "merchant_product_id": "BP-MONITOR-PRO", "upc_code_or_gtin": "14567890123456", "images": [ "https://cdn.example.com/bp-monitor-1.jpg", "https://cdn.example.com/bp-monitor-2.jpg" ] } ``` ## Related Endpoints * [Create Product](/api-reference/endpoint/create-product-v2) - POST /api/v2/products * [Get Product](/api-reference/endpoint/get-product-v2) - GET /api/v2/products/ * [Update Product](/api-reference/endpoint/update-product-v2) - PUT /api/v2/products/ * [List Products](/api-reference/endpoint/list-products-v2) - GET /api/v2/products * [Delete Product](/api-reference/endpoint/delete-product) - DELETE /api/v2/products/ # Subscription Object Source: https://docs.withgale.com/api-reference/objects/subscription The Subscription object represents a recurring payment schedule for a product or service # Subscription Object Subscriptions enable recurring payments for memberships, services, or product deliveries. They automatically charge customers at specified intervals using their stored HSA/FSA or regular payment method. ## The Subscription Object ```json theme={null} { "id": "sub_abc123xyz", "customer_id": "cus_xyz789", "status": "active", "product_id": 12345, "merchant_product_id": "MEMBERSHIP-PREMIUM", "amount_cents": 9900, "currency": "USD", "interval": "monthly", "interval_count": 1, "trial_period_days": 7, "trial_end": "2025-10-25T14:30:00Z", "current_period_start": "2025-10-18T14:30:00Z", "current_period_end": "2025-11-18T14:30:00Z", "next_billing_date": "2025-11-18T14:30:00Z", "cancel_at_period_end": false, "cancelled_at": null, "ended_at": null, "payment_method": { "type": "hsa_fsa_card", "last4": "1111", "brand": "visa" }, "metadata": { "tier": "premium", "features": "unlimited_access,priority_support" }, "created_at": "2025-10-18T14:30:00Z", "updated_at": "2025-10-18T14:30:00Z" } ``` ## Attributes | Attribute | Type | Description | | - | - | - | | `id` | string | Unique subscription identifier | | `customer_id` | string | Customer ID | | `status` | enum | Subscription status (see below) | | `product_id` | integer | Associated product ID | | `merchant_product_id` | string | Your product reference ID | | `amount_cents` | integer | Recurring charge amount in cents | | `currency` | string | ISO 4217 currency code | | `interval` | enum | Billing interval: `daily`, `weekly`, `monthly`, `yearly` | | `interval_count` | integer | Number of intervals between billings | | `trial_period_days` | integer | Free trial duration in days | | `trial_end` | timestamp | When trial ends (null if no trial) | | `current_period_start` | timestamp | Start of current billing period | | `current_period_end` | timestamp | End of current billing period | | `next_billing_date` | timestamp | Next scheduled charge date | | `cancel_at_period_end` | boolean | Whether subscription cancels at period end | | `cancelled_at` | timestamp | When subscription was cancelled (null if active) | | `ended_at` | timestamp | When subscription ended (null if active) | | `payment_method` | object | Stored payment method details | | `metadata` | object | Custom key-value pairs | | `created_at` | timestamp | When subscription was created | | `updated_at` | timestamp | When subscription was last updated | ## Subscription Status | Status | Description | | - | - | | `trialing` | In free trial period | | `active` | Active and billing normally | | `past_due` | Payment failed, retrying | | `cancelled` | Cancelled, will end at period end | | `ended` | Subscription has ended | | `paused` | Temporarily paused | ## Billing Intervals | Interval | `interval_count` | Billing Frequency | | - | - | - | | `daily` | 1 | Every day | | `daily` | 7 | Every 7 days | | `weekly` | 1 | Every week | | `weekly` | 2 | Every 2 weeks (bi-weekly) | | `monthly` | 1 | Every month | | `monthly` | 3 | Every 3 months (quarterly) | | `yearly` | 1 | Every year | ## Subscription Lifecycle A subscription moves through these states: * **trialing** - Subscription created with trial period * **active** - Subscription is active and billing normally (can come from trialing or be created without trial) * **past_due** - Payment failed, retrying (can come from trialing or active) * **cancelled** - Cancel requested, will end at period end * **ended** - Subscription has ended (can come from cancelled, past_due after max retries, or active for immediate cancellation) ## Trial Periods Subscriptions can include a free trial period: ```json theme={null} { "trial_period_days": 7, "trial_end": "2025-10-25T14:30:00Z", "status": "trialing", "next_billing_date": "2025-10-25T14:30:00Z" } ``` During trial: * Customer is not charged * Payment method is verified * First charge occurs when trial ends ## Payment Method ```json theme={null} { "payment_method": { "type": "hsa_fsa_card", "last4": "1111", "brand": "visa", "exp_month": 12, "exp_year": 2026 } } ``` | Type | Description | | - | - | | `hsa_fsa_card` | HSA/FSA debit card | | `credit_card` | Regular credit card | | `debit_card` | Regular debit card | ## Cancellation Behavior ### Cancel at Period End ```json theme={null} { "status": "cancelled", "cancel_at_period_end": true, "current_period_end": "2025-11-18T14:30:00Z", "cancelled_at": "2025-10-20T10:00:00Z", "ended_at": null } ``` Customer retains access until period end. ### Immediate Cancellation ```json theme={null} { "status": "ended", "cancel_at_period_end": false, "cancelled_at": "2025-10-20T10:00:00Z", "ended_at": "2025-10-20T10:00:00Z" } ``` Access ends immediately. ## Past Due Handling When a payment fails: 1. Status changes to `past_due` 2. Automatic retry attempts (days 3, 7, 14) 3. Customer receives notification 4. After max retries, subscription ends ```json theme={null} { "status": "past_due", "next_billing_date": "2025-10-21T14:30:00Z", "retry_count": 2, "max_retries": 3 } ``` ## Examples ### Monthly Membership ```json theme={null} { "id": "sub_membership_001", "amount_cents": 9900, "interval": "monthly", "interval_count": 1, "status": "active", "trial_period_days": 14 } ``` ### Quarterly Subscription ```json theme={null} { "id": "sub_quarterly_001", "amount_cents": 24900, "interval": "monthly", "interval_count": 3, "status": "active" } ``` ### Annual Plan with Trial ```json theme={null} { "id": "sub_annual_001", "amount_cents": 99900, "interval": "yearly", "interval_count": 1, "status": "trialing", "trial_period_days": 30, "trial_end": "2025-11-18T14:30:00Z" } ``` ## Related Endpoints * [Create Subscription](/api-reference/endpoint/create-subscription) - POST /api/v2/subscriptions * [Get Subscription](/api-reference/endpoint/get-subscription) - GET /api/v2/subscriptions/ * [List Subscriptions](/api-reference/endpoint/list-subscriptions) - GET /api/v2/subscriptions * [Cancel Subscription](/api-reference/endpoint/cancel-subscription) - POST /api/v2/subscriptions//cancel * [Update Subscription](/api-reference/endpoint/update-subscription) - PUT /api/v2/subscriptions/ # Monthly Product Updates Source: https://docs.withgale.com/changelog/updates **September 2025** Updates ## Products now available in your dashboard ![Merchant-Dashboard-product-sync](https://mintcdn.com/galepaymentsinc/0jgxEVgRWyjhE6ru/product-sync.png?fit=max\&auto=format\&n=0jgxEVgRWyjhE6ru\&q=85\&s=3389e9255fe12ac2407438bc0200e86b) You can now view and edit products in the Gale Dashboard. The new Products section allows merchants to: * Import products in bulk via CSV * View eligibility details and update information * Sync products from connected stores ## Shopify HSA/FSA post-purchase reimbursements ![Shopify post-purchase reimbursements](https://mintcdn.com/galepaymentsinc/0jgxEVgRWyjhE6ru/reimbursements.png?fit=max\&auto=format\&n=0jgxEVgRWyjhE6ru\&q=85\&s=25e32ca022fc7740f1323712e876ee1d) We’ve launched a new way for Shopify merchants to boost cart sizes and repeat purchases. Shoppers can now pay with any card and still enjoy automatic HSA/FSA reimbursements — making it easier than ever to save using pre-tax dollars. **August 2025** Updates ## Merchant Dashboard is live ![Merchant-Dashboard-Live](https://mintcdn.com/galepaymentsinc/-tfqSxxNOR5RQPkA/Merchant-dashboard.png?fit=max\&auto=format\&n=-tfqSxxNOR5RQPkA\&q=85\&s=131a6853ad73673646a5a83248258dd3) Merchants no longer have had to take action on their account and orders via their eCommerce platform. Our Merchant dashboard includes, log in, sign up, secure authentication, and account management. ## Generate API Keys ![Self-serve-API-Keys](https://mintcdn.com/galepaymentsinc/-tfqSxxNOR5RQPkA/API-Keys.png?fit=max\&auto=format\&n=-tfqSxxNOR5RQPkA\&q=85\&s=9fa55fbccb03f8d59d6e6b4e4f7ab5e6) Merchants can now generate and manage their own API keys directly from the dashboard, eliminating support tickets for key generation and enabling faster testing workflows. **July 2025** Updates ## Letter of Medical Necessity – Launched ![LMN-Launched](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/hsa-lmn-launch.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=5fe511beefcf1877d7c8383ff60c8395) Our Letter of Medical Necessity (LMN) product is now live and out of Beta. Merchants that sell health and wellness products or services that are not on the eligible product list can now offer HSA | FSA eligibility to shoppers that qualify. ## Integration Enhancements * Multi-currency support added to WooCommerce plugin * Background product catalog synchronization – no more waiting for your products to sync **June 2025** Updates ## Refunds available in Shopify ![Shopify-refunds](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/shopify_refunds.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=8607c69a24173167c411962affda4c4b) The Gale Shopify App now allows you to issue full refunds for Gale orders directly from your Shopify dashboard — making it quicker and easier to action returns. **May 2025** Updates ## Our API Docs are now public ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/updated_docs.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=19e8fbb5ec40e7388c3aea85dafd40ae) Our custom integration guides are now out of beta and available for all merchants. [View API Docs](/api-reference/introduction) **April 2025** Updates ## HSA & FSA payments for optical stores ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/optical_store.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=386d3c31ecab46f6c7d3c9cf111d65d7) Gale’s payment platform now supports brands selling vision and eyewear products to consumers. Our platform includes item-level validation, reducing card rejection and protecting merchants and shoppers against compliance risk. **March 2025** Updates ## Hosted Payment Page redesign ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/payment_page_2.0.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=3b11b455d4f24d99b09ae66387aff6bf) This month we shipped a redesign of our Hosted Payment Page. The new design features a simple, modern, and beautiful UI. After seeing positive conversion rate improvements, we’ve rolled this out to all merchants across all platforms. ## Ecwid integration now available (in beta) ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/ecwid_x_gale.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=f59cb1390b0d64b4a3cf848bd3e823a9) Our Ecwid plugin is now here! Merchants on the Ecwid by Lightspeed eCommerce platform can now add HSA & FSA payments in minutes — no-code required.\ Interested? Reach out to your Account Manager or [Gale Support](https://www.withgale.com/contact/support) for early access. **February 2025** Updates ## SIGIS Certified Integrated Payment provider ![Sigis Gale ](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/sigis_gale.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=47dee2fa3bc0bca42fb3e058a1c2d0fa) Gale is now a Certified SIGIS Integrated Payment Provider. The certification enables us to provide an IIAS system and accept FSA/HSA cards on behalf of eCommerce merchants. ## On-site Messaging 2.0 ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/ES_DCNs-vEFQ6D4Q/images/onsite_messaging2.0.png?fit=max\&auto=format\&n=ES_DCNs-vEFQ6D4Q\&q=85\&s=e8692dbd812b81feeb4c786439d7defb) We launched four beautiful new variants of our on-site messaging (OSM) for merchants across all integrated platforms. Promote HSA/FSA eligibility and improve add-to-cart rates. ## Test Mode for Hosted Payment Page We’ve added a “Test Mode” toggle in all of our plugins and integrations — allowing developers to build and test payments without triggering real transactions. **January 2025** Updates ## WooCommerce Plugin now live ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/-tfqSxxNOR5RQPkA/images/WooCommerce_x_Gale.png?fit=max\&auto=format\&n=-tfqSxxNOR5RQPkA\&q=85\&s=698f4694a6e6eceaf5f4cc4d7e44674f) Our WooCommerce plugin has been approved by the WordPress team and is now available on the WordPress Marketplace.\ [View Plugin](https://wordpress.org/plugins/gale-hsa-fsa-payments/) ## Shopify Payments App now available (in beta) ![Shopify Payments App](https://mintcdn.com/galepaymentsinc/-tfqSxxNOR5RQPkA/images/Shopify_x_Gale.png?fit=max\&auto=format\&n=-tfqSxxNOR5RQPkA\&q=85\&s=4c17325b85214ef5765d67486e203515) Our Shopify Payments App has been tested and approved by the Shopify Partnership Team. It enables Shopify merchants to seamlessly integrate payments while ensuring compliance with HSA/FSA standards.\ [View App](https://apps.shopify.com/gale-hsa-fsa-payments) ## Shopify Product Eligibility App now live ![Shopify Eligibility App ](https://mintcdn.com/galepaymentsinc/-tfqSxxNOR5RQPkA/images/Gale_Shopify_App.png?fit=max\&auto=format\&n=-tfqSxxNOR5RQPkA\&q=85\&s=66f952b12f65ab6ec50a8586fb10e8a0) Merchants can now seamlessly display product eligibility and onsite messaging, helping customers easily identify which products qualify.\ [View App](https://apps.shopify.com/gale-hsa-fsa-eligibility) **December 2024** Updates ## WooCommerce plugin improvements ![Woocommerce Product Sync](https://mintcdn.com/galepaymentsinc/-tfqSxxNOR5RQPkA/images/WooCommerce_Product_Sync.png?fit=max\&auto=format\&n=-tfqSxxNOR5RQPkA\&q=85\&s=8c870b7ccb0c95c625f790475d0d7938) Our WooCommerce Zip File plugin can now automatically sync your product catalog and determine eligibility at the click of a button — no more CSV file uploads. Check out the docs to get started. # Stripe Checkout Source: https://docs.withgale.com/custom-payment-methods/elements-checkout-session Add Pay with HSA/FSA to a checkout built with Stripe Checkout Sessions. > [!NOTE] > > Pay with HSA/FSA on Stripe Checkout Sessions is not generally available. Ask your account manager before building on this page. The [Stripe Payment Element](/custom-payment-methods/elements-payment-intent) path is available today. On this path Stripe calls an adapter URL to collect each payment. Your backend makes no API call for the payment and needs no API key, only your Stripe secret and publishable keys. ## Prerequisites * An existing checkout built with Stripe **Checkout Sessions**. * Access to Stripe's **merchant-instructed orchestration preview**, which Stripe grants per account. Ask Stripe if you do not have it. * Stripe Dashboard access, with permission to create API keys. * Merchant dashboard access. * Your **adapter URL**, issued during onboarding. Ask your account manager if you do not have it. You paste it into Stripe when you create the payment method. ## Step 1: Create your custom payment method A **custom payment method type** makes Pay with HSA/FSA appear in your Payment Element. Create one per Stripe account, in each mode. **1. Open Custom payment methods** In the Stripe Dashboard, go to **Settings → Payments → Custom payment methods** and click **Create**. ![Payments settings tabs with Custom payment methods highlighted](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-3-cpm-tab.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=444075bfdd8cdfdee5d6dd6915383eb1) Settings → Payments → Custom payment methods ![Custom payment methods list with the Create button highlighted](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-4-create.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=19acaf8f24c2801325a58879acd0a7da) Custom payment methods → Create **2. Choose a custom name and icon** Pay with HSA/FSA is not in Stripe's catalog of known methods, so choose **Provide a custom name and icon**. ![Create custom payment method panel with the custom name and icon link highlighted](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-5-custom-name.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=7489e2b35c454d54a798f9654fd03d16) Create custom payment method → Provide a custom name and icon **3. Set the name, logo and adapter URL** | Field | Value | | - | - | | **Display name** | `Pay with HSA/FSA` | | **Logo** | [Download the logo](/images/gale-cpm-logo.png) | | **Endpoint URL**, under *Checkout Sessions* | Your adapter URL. Stripe calls it to collect every payment, including each renewal | Accept both sets of terms, then click **Create**. The *Checkout Sessions* section appears only if Stripe has enabled it for your account. It is not on by default, and this integration cannot be completed without it. Ask Stripe to enable custom payment methods with Checkout Sessions. ![Create custom payment method form showing display name, logo upload, Checkout Sessions endpoint URL and the terms checkbox](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-6-details.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=493ef92cdd6438bb81aa504585c203f4) Display name, logo, and the Checkout Sessions endpoint URL **4. Copy the cpmt\_ id** Stripe shows the **custom.type ID**, beginning `cpmt_`. Copy it. The steps that follow need it, and Stripe displays it only once. ![Confirmation panel showing the custom.type ID to copy](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-7-created.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=9c476fa71f1d02b4b5a78325be6110a8) Custom payment method created. Note the cpmt\_ id ### Copy your signing secret Stripe signs every call it makes to the adapter URL. The signing secret is how a call is verified as coming from Stripe. Without it every call is rejected. **1. Open Webhooks** In the Stripe Dashboard, click **Developers**, then **Webhooks**. **2. Find the destination Stripe created** Registering the custom payment method created this destination, pointing at the adapter URL you entered. Look for a destination named **SOPI (cpmt\_…)**, with the `cpmt_` id you copied. On an account with several destinations, match by that name. **3. Reveal the secret** Open that destination. **Signing secret** is in the details panel on the right. Click the eye to reveal it and copy it. It starts with `whsec_`. ![Destination details panel showing the SOPI name, API version, 0 deliveries, and a masked whsec\_ signing secret with reveal and roll controls. The type id and endpoint URL are redacted; yours will show your own values](https://mintcdn.com/galepaymentsinc/xCMsVFbcovX9wrtB/images/stripe-cpm-key-8-signing-secret.png?fit=max\&auto=format\&n=xCMsVFbcovX9wrtB\&q=85\&s=06154c53673a7eec15f127a4be55b238) Destination details: the signing secret, with reveal and roll The secret can be viewed or rolled from the destination details page at any time. After rolling it, save the new value in the merchant dashboard. The signing secret and the restricted key are different values. An `rk_` key in the signing secret field, or the reverse, is rejected. The destination shows **0 deliveries** and no event subscriptions. That is correct. It signs Stripe's calls to the adapter and sends you no events, so this path still needs your own Stripe webhook for `checkout.session.*`. The restricted API key, the `cpmt_` id and the signing secret are all saved on the **Pay with HSA/FSA on Stripe** page in the merchant dashboard. See [Create the restricted key](/custom-payment-methods/gale-on-stripe#create-the-restricted-key). ## Step 2: Connect Stripe Access to your Stripe account is needed to import your catalog and report payment outcomes. Do this once per Stripe account, per mode, on the **Pay with HSA/FSA on Stripe** page in the merchant dashboard. **1. Create a restricted Stripe API key** In the Stripe Dashboard, open **Developers → API keys** and create a **restricted** key, not your standard secret key. Permissions cannot be edited after the key exists. See [Create the restricted key](/custom-payment-methods/gale-on-stripe#create-the-restricted-key) for the list. Stripe reveals a restricted key once, so copy it before you leave the page. **2. Save your credentials** In the merchant dashboard, open **Integrations → Pay with HSA/FSA on Stripe** and fill in: | Field | Value | | - | - | | **Restricted API key** | The `rk_…` key from the previous step | | **Custom payment method type ID** | The `cpmt_…` id from Step 1 | | **Signing secret** | The `whsec_…` value from Step 1 | The key is checked against Stripe when you save, so a wrong key or a missing permission shows immediately. **3. Import your products** On the same page, run **Preview** to see what would change, then **Import** to apply it. Eligibility is resolved per line item against this catalog. With **Keep products in sync** on, later edits in Stripe are picked up automatically. **4. Confirm the connection** The panel below the form shows your Stripe account ID, each permission as granted or missing, and whether a signing secret is stored. Permissions cannot be added to an existing key, so a missing one means creating a new key. See [After you save](/custom-payment-methods/gale-on-stripe#after-you-save). ## Step 3: Add Pay with HSA/FSA to your checkout Four changes to the Checkout Session your backend creates, and one beta flag on the client. The card path is unchanged. **1. Server side: create the Checkout Session** Stripe's *Create a Checkout Session* step in [Build a custom checkout page](https://docs.stripe.com/payments/quickstart) ([`POST /v1/checkout/sessions`](https://docs.stripe.com/api/checkout/sessions/create)), with four changes. ```js Stripe's quickstart theme={null} const stripe = require('stripe')('sk_test_...'); const session = await stripe.checkout.sessions.create({ ui_mode: 'elements', customer_email: 'customer@example.com', shipping_address_collection: { allowed_countries: ['US', 'CA'] }, return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}', line_items: [{ price_data: { currency: 'usd', unit_amount: 2599, product_data: { name: 'Allergy Relief' }, }, quantity: 1, }], }); ``` ```js With Pay with HSA/FSA {1-3,6,10,19} theme={null} // 1. The orchestration preview API version. const stripe = require('stripe')('sk_test_...', { apiVersion: '2025-03-31.basil;checkout_merchant_instructed_orchestration_preview=v1;', }); const session = await stripe.checkout.sessions.create({ ui_mode: 'custom', // 2. see the table below customer_email: 'customer@example.com', shipping_address_collection: { allowed_countries: ['US', 'CA'] }, return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}', // 3. List the custom payment method alongside your native methods. custom_payment_method_types: ['cpmt_...'], line_items: [{ price_data: { currency: 'usd', unit_amount: 2599, product_data: { name: 'Allergy Relief', // 4. Tag the product with your SKU. metadata: { merchant_product_id: 'SKU-123' }, }, }, quantity: 1, }], }); ``` | Change | Why | | - | - | | `apiVersion: '…checkout_merchant_instructed_orchestration_preview=v1;'` | Gates the preview. Without it Stripe rejects `custom_payment_method_types`. | | `ui_mode: 'custom'` instead of `'elements'` | `elements` requires a 2026 API version, and the preview pins a 2025 one. `custom` is the same Elements-driven mode under its older name. | | `custom_payment_method_types: ['cpmt_…']` | Lists Pay with HSA/FSA in the Payment Element. Other payment methods are unaffected. | | `product_data.metadata.merchant_product_id` | How HSA/FSA eligibility is resolved per line. Optional. Without it the Stripe product id is used, which is what the catalog import keys on. An item that matches nothing is still charged, as a regular purchase. | Sending `ui_mode: 'elements'` with the preview version returns: ``` Invalid ui_mode: elements. In order to use ui_mode: elements, you must upgrade to Stripe API version 2026-03-2... ``` `shipping_address_collection` is required on this path. The cart needs a shipping address, and only what the session exposes can be used. Collect it here, with a `ShippingAddressElement`, or by passing `shippingAddress` to `confirm()`. Without one, checkout creation fails and the payment is declined with no reason shown to the shopper. **2. Client side: Elements with Checkout Sessions** Stripe's *Initialize Checkout* and *Fetch a Checkout Session client secret* steps, with one change: the beta flag on `loadStripe`. The payment method renders in the Payment Element because the session lists it, and `confirm()` is the same call a card payment makes. ```js Stripe's quickstart theme={null} const stripe = loadStripe('pk_test_...'); ``` ```js With Pay with HSA/FSA {2} theme={null} const stripe = loadStripe('pk_test_...', { betas: ['checkout_merchant_instructed_orchestration_preview_v1'], }); ``` Without that flag the session loads, the card methods render, and Pay with HSA/FSA does not appear. The rest is Stripe's code unchanged: ```jsx theme={null} // Note the /checkout subpath. The Checkout Sessions bindings are not exported // from the package root. Requires @stripe/react-stripe-js v6+. import { CheckoutElementsProvider, PaymentElement, useCheckoutElements, } from '@stripe/react-stripe-js/checkout'; import { loadStripe } from '@stripe/stripe-js'; const stripe = loadStripe('pk_test_...', { betas: ['checkout_merchant_instructed_orchestration_preview_v1'], }); function CheckoutForm() { // Returns a {loading | success | error} result. The SDK, and with it // confirm(), is on result.checkout once it resolves. const result = useCheckoutElements(); if (result.type === 'loading') return

Loading…

; if (result.type === 'error') return

{result.error.message}

; const { checkout } = result; return (
{ e.preventDefault(); await checkout.confirm(); }}> {/* Pay with HSA/FSA appears here, after native methods */} ); } export default function Page({ clientSecret }) { // clientSecret may be a string or a promise resolving to one. return ( ); } ``` Older examples show `CheckoutProvider`, `options={{ fetchClientSecret }}` and a `useCheckout()` that returns the SDK directly. That was the v3-era API. On `@stripe/react-stripe-js` v6 those imports do not exist at the package root, and calling `confirm()` on the hook's return value throws `checkout.confirm is not a function`, because the actions are one level down, on `result.checkout`. `useCheckout()` still works but is deprecated since v6.3.0. Use `useCheckoutElements()` inside `CheckoutElementsProvider`. `ui_mode` also supports `embedded` (Stripe's embedded component) and `hosted` (redirect to a Stripe-hosted page, with no Elements code). Pay with HSA/FSA appears in all three. Stripe lists one exception: it does not work when `approval_method` is `manual`. ## Step 4: Set your webhook URL Stripe reports the session and the renewals. Settlement, refunds and disputes are reported by webhook from this API. You need both. Set your endpoint under **Developer Tools → Webhooks** in the merchant dashboard. | From Stripe | From this API | | - | - | | `checkout.session.completed`: the shopper finished | `order.completed`: the payment was captured | | `invoice.paid` / `invoice.payment_failed`: renewals | `refund.succeeded` | | `customer.subscription.*` | `dispute.created` / `dispute.closed` | No Stripe Charge object exists for these payments, so `charge.succeeded`, `charge.refunded` and `charge.dispute.*` never fire. ## One-time and subscription The session's `mode` decides which applies. The payment is charged and settled the same way in both. The difference is what Stripe keeps. * **One-time**: `mode: 'payment'`. Stripe orchestrates a single charge, the shopper's HSA/FSA card is charged, and Stripe records the outcome against the session. No Stripe subscription exists, and no Stripe Invoice is created automatically. * **Subscription**: `mode: 'subscription'` with a recurring Stripe price. Stripe creates a subscription and drives the billing schedule. `setup` mode is not available. A custom payment method cannot save a card without charging it. ## Recurring billing on this path The cadence is set by your recurring Stripe price. Stripe owns the subscription and the schedule. * **Stripe starts every renewal.** On each billing date Stripe calls the adapter off-session, and the shopper's stored HSA/FSA card is charged. Stripe never charges the card itself. * **Stripe cannot update the card.** The Customer Portal cannot replace the card behind this payment method. See [Changing the card](#changing-the-card). * **Stripe's record is for reconciliation.** The outcome Stripe holds against the subscription is a record of a payment processed outside Stripe. ### Renewals arrive on your Stripe webhooks A renewal on this path is an ordinary Stripe Billing event. Existing `invoice.paid` and `invoice.payment_failed` handlers keep working. | Subscribe to | For | | - | - | | `invoice.paid` | A cycle billed successfully | | `invoice.payment_failed` | A cycle failed | | `customer.subscription.updated` / `.deleted` | Plan changes and cancellations | `subscription.renewed` and `subscription.payment_failed` are not sent for a subscription on this path. `charge.*` and `payment_intent.*` handlers receive nothing, on renewals as on the first cycle. ### Changing the card Card updates use `POST /v2/subscriptions/{id}/card-update-link`. See [Subscriptions](/subscriptions/overview#when-a-card-fails). ### Refunding a cycle Refund in Stripe on this path. Stripe calls the adapter with a refund request and the money is returned to the shopper's HSA/FSA card. Do not call `POST /v2/refunds`. On the [Stripe Payment Element](/custom-payment-methods/elements-payment-intent#refunds) path the direction is reversed: you refund by API and the refund is reported to Stripe. ## Test and live Sandbox and live each need their own `cpmt_` id, adapter URL registration, and signing secret. ## Outcomes in Stripe Stripe accepts four outcome codes for a custom payment method. Refusals map onto them: | Code | When | | - | - | | `payment_method_customer_decline` | Shopper cancelled or abandoned checkout | | `payment_method_provider_decline` | Definitive refusal | | `payment_method_provider_authentication_error` | Authentication (3DS) failure | | `payment_method_provider_unknown_outcome` | Timeout, network error, or otherwise indeterminate | An indeterminate result is never reported as a final failure. The outcome is reported once it is confirmed. ## Test your integration **1. Use test credentials** Use your Stripe test keys and the test-mode `cpmt_…` you created. Test and live are separate registrations. **2. Confirm the option renders** Load your checkout: **Pay with HSA/FSA** appears alongside your native methods. If it does not, the cause is on the Stripe side: the session was created without the `cpmt_` in `custom_payment_method_types`, the preview API version or beta flag is missing, the id belongs to the other mode, or Adaptive Pricing is active. **3. Confirm Stripe reaches the adapter** Complete a checkout. Stripe calls the adapter URL and is answered with a redirect to the hosted page. A call rejected on signature means the signing secret saved on **Pay with HSA/FSA on Stripe** does not match that destination, or came from the other mode. **4. Confirm the session completes** `checkout.session.completed` fires on your Stripe webhook. With `mode: 'subscription'` a Stripe Subscription and Invoice exist from this point. With `mode: 'payment'` neither does. **5. Run a mixed cart** Include an item whose SKU metadata matches nothing in the catalog. It should be charged as a regular purchase and not block the order. **6. Check the outcome codes** Cancel a checkout and confirm the session shows `payment_method_customer_decline`. See [Outcomes in Stripe](#outcomes-in-stripe) for the full set. **7. Confirm the outcome server-side before fulfilling** Verify the outcome on the session. Then check that the order appears in the merchant dashboard under **Orders**, which is the authoritative record, and that a payment record appears in Stripe against your custom payment method. > [!WARNING] > > **`checkout.session.completed` means the shopper finished, not that funds > settled.** There is no PaymentIntent and no Charge on this path, so > `payment_intent.succeeded` and `charge.succeeded` never fire. Settlement is > on the payment record, which is reported after capture. Fulfilling on the > session-completed event alone means fulfilling on an authorization that can > still fail. ## Go-live checklist * Live-mode `cpmt_…` on the live code path * Adapter URL entered as the *Checkout Sessions* endpoint on the live custom payment method * Live signing secret saved in the merchant dashboard, and the restricted key verified * SKU metadata present on live products, or their Stripe product ids imported * `approval_method` is not `manual` * Outcome verified server-side before fulfillment * One real live transaction reconciled in both the Stripe Dashboard and the merchant dashboard * Refunds are issued from Stripe on this path ## Related * [Overview](/custom-payment-methods/overview) * [Stripe Payment Element](/custom-payment-methods/elements-payment-intent) * [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe) * [Subscription Webhooks](/webhooks/subscriptions) # Stripe Payment Element Source: https://docs.withgale.com/custom-payment-methods/elements-payment-intent Add Pay with HSA/FSA to a Stripe Payment Element for a one-time charge. The card is entered on a hosted page and the payment is written back with your restricted key. Use this page for a one-time charge. The shopper picks **Pay with HSA/FSA**, your server creates a checkout, and the shopper pays on a hosted page. The payment record is written to your Stripe account with the restricted key from Step 2. This option does not create a Stripe PaymentIntent or Charge. Card payments on the same page can keep theirs. ## Prerequisites * An existing checkout that mounts Stripe's Payment Element. * Stripe Dashboard access, with permission to create a custom payment method. * Merchant dashboard access, and an API key (`glm_test_…` / `glm_live_…`). ## Step 1: Create your custom payment method A **custom payment method type** makes Pay with HSA/FSA appear in your Payment Element. Create one per Stripe account, in each mode. **1. Open Custom payment methods** In the Stripe Dashboard, go to **Settings → Payments → Custom payment methods** and click **Create**. ![Payments settings tabs with Custom payment methods highlighted](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-3-cpm-tab.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=444075bfdd8cdfdee5d6dd6915383eb1) Settings → Payments → Custom payment methods ![Custom payment methods list with the Create button highlighted](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-4-create.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=19acaf8f24c2801325a58879acd0a7da) Custom payment methods → Create **2. Set the name and logo** Pay with HSA/FSA is not in Stripe's catalog of known methods, so choose **Provide a custom name and icon**, then fill in: | Field | Value | | - | - | | **Display name** | `Pay with HSA/FSA` | | **Logo** | [Download the logo](/images/gale-cpm-logo.png) | | **Checkout Sessions endpoint URL** | Leave empty on this path. The [Checkout Session](/custom-payment-methods/elements-checkout-session) path is the one that sets it. | Accept both sets of terms, then click **Create**. ![Create custom payment method panel with the custom name and icon link highlighted](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-5-custom-name.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=7489e2b35c454d54a798f9654fd03d16) Create custom payment method → Provide a custom name and icon ![Create custom payment method form showing display name, logo upload, Checkout Sessions endpoint URL and the terms checkbox](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-6-details.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=493ef92cdd6438bb81aa504585c203f4) Display name, logo, and the terms checkbox **3. Copy the cpmt\_ id** Stripe shows the **custom.type ID**, beginning `cpmt_`. Copy it. Your frontend passes it to Stripe.js. Stripe displays it only once. ![Confirmation panel showing the custom.type ID to copy](https://mintcdn.com/galepaymentsinc/fp_nidsvrE1p2bEe/images/stripe-cpm-7-created.png?fit=max\&auto=format\&n=fp_nidsvrE1p2bEe\&q=85\&s=9c476fa71f1d02b4b5a78325be6110a8) Custom payment method created. Note the cpmt\_ id ## Step 2: Save the restricted key Open **Integrations → Pay with HSA/FSA on Stripe** and paste the `rk_…` key. It is used to write the payment record, and the page will not save unless Payment Records read and write are both granted. Paste the `cpmt_…` id from Step 1. Leave the signing secret blank. The [Checkout Session](/custom-payment-methods/elements-checkout-session) path is the one that uses that secret. The walkthrough is on [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe). ## Step 3: Add Pay with HSA/FSA to your checkout Two changes in your frontend, and one new endpoint on your backend. Your backend calls the API and authenticates with your **API key** (`glm_test_…` / `glm_live_…`). Generate one in the merchant dashboard under **Developer Tools → API Keys**. See [Getting your API key](/developer-manual/authentication#getting-your-api-key). Keep it on your server. It must never reach the browser. The key prefix sets the mode. `glm_test_…` is test mode and moves no money. `glm_live_…` is a real charge. **1. Frontend: register the payment method** Stripe's deferred Elements setup (*Collect payment details before creating an Intent*, [Collect payment details](https://docs.stripe.com/payments/accept-a-payment-deferred?platform=web\&type=payment#collect-payment-details)) gains one option: [`customPaymentMethods`](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-customPaymentMethods), documented for the Payment Element [here](https://docs.stripe.com/payments/payment-element/custom-payment-methods?payment-ui=elements). ```jsx Stripe's deferred Elements theme={null} const options = { mode: 'payment', amount: 1099, currency: 'usd', appearance: {/*...*/}, }; ``` ```jsx With Pay with HSA/FSA {5-8,12} theme={null} const options = { mode: 'payment', amount: 1099, currency: 'usd', appearance: {/*...*/}, customPaymentMethods: [{ id: customPaymentMethodId, // 'cpmt_...' options: { type: 'static', subtitle: 'Pay with your HSA/FSA card' }, }], }; ``` Custom payment methods render **last** in the Element by default. To put Pay with HSA/FSA above the card options, pass `paymentMethodOrder: ['cpmt_...', 'card']` when you create the Payment Element. **2. Frontend: branch on submit** Stripe's handler (*Submit the payment to Stripe* on the same [deferred-Elements page](https://docs.stripe.com/payments/accept-a-payment-deferred?platform=web\&type=payment#submit-payment)) validates, mints the PaymentIntent, then confirms with [`stripe.confirmPayment`](https://docs.stripe.com/js/payment_intents/confirm_payment). Pay with HSA/FSA adds a branch *before* the intent is created, and leaves the card path untouched. ```jsx Stripe's deferred Elements theme={null} const handleSubmit = async (event) => { event.preventDefault(); if (!stripe) return; const { error: submitError } = await elements.submit(); if (submitError) { handleError(submitError); return; } const res = await fetch('/create-intent', { method: 'POST' }); const { client_secret: clientSecret } = await res.json(); const { error } = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete' }, }); if (error) handleError(error); }; ``` ```jsx With Pay with HSA/FSA {5,8-17} theme={null} const handleSubmit = async (event) => { event.preventDefault(); if (!stripe) return; const { error: submitError, selectedPaymentMethod } = await elements.submit(); if (submitError) { handleError(submitError); return; } if (selectedPaymentMethod === customMethodId) { const { redirect_url } = await fetch('/create-hsa-fsa-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ /* cart items, customer, ... */ }), }).then((r) => r.json()); window.location.href = redirect_url; // -> hosted checkout return; // no PaymentIntent is created } const res = await fetch('/create-intent', { method: 'POST' }); const { client_secret: clientSecret } = await res.json(); const { error } = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete' }, }); if (error) handleError(error); }; ``` | Change | Why | | - | - | | Read `selectedPaymentMethod` from `elements.submit()` | Tells you which method the shopper picked. Stripe's version ignores it because there is only one path. | | Branch when it equals your `cpmt_...` | This payment is a redirect, not a Stripe confirmation. | | `return` before `/create-intent` | No PaymentIntent should exist for a Pay with HSA/FSA payment. Creating and confirming one would charge the shopper twice. | **3. Backend: create the checkout** There is no separate create-cart call. This request creates the checkout and returns the hosted URL. ```js theme={null} const cart = { reference_id: `order-${Date.now()}`, customer: { email: 'shopper@example.com', first_name: 'Sam', last_name: 'Shopper', phone: '+15555550123' }, line_items: [ { product_id: 'SKU-123', name: 'Blood Pressure Monitor', price: 2599, quantity: 1, currency: 'USD' }, ], shipping_info: { address_line_1: '1 Test St', city: 'Austin', state: 'TX', postal_code: '73301', country: 'US' }, metadata: { payment_source: 'stripe_elements_cpm', display_name: 'Pay with HSA/FSA', }, success_url: 'https://your-site.com/success', // HTTPS required failure_url: 'https://your-site.com/cancel', // HTTPS required }; const res = await fetch(`${GALE_API_URL}/api/v2/checkout`, { method: 'POST', headers: { Authorization: `Bearer ${GALE_MERCHANT_API_KEY}`, // glm_test_... / glm_live_... (SECRET, server-side only) 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify(cart), }); const data = await res.json(); return { redirect_url: data.data.checkout_url }; // { data: { checkout_url, checkout_id } } ``` `checkout_id` looks like `cs_…`. That is the checkout id from this API, not a Stripe Checkout Session. ## Step 4: Set your webhook URL The outcome is sent to your application by webhook. In the merchant dashboard, open **Developer Tools → Webhooks**, add your endpoint, and subscribe to the events you fulfill on. | Event | Fires when | | - | - | | `order.completed` | The payment is captured. Fulfill on this event, not on the browser redirect. | | `order.failed` | The order is closed and will not complete | | `payment.failed` | One attempt was declined. The shopper may retry the same checkout. | | `refund.created` | You requested a refund | | `refund.succeeded` | The refund was accepted | | `refund.failed` | The refund failed | | `dispute.created` / `dispute.closed` | A chargeback opened or resolved. Stripe has no `charge.*` event for this payment. | | `checkout.expired` | The hosted page timed out unpaid | Verify `X-Gale-Signature` on every delivery. `Authorization: Bearer` with the endpoint secret is still sent. That header will be removed, so use the signature as your check. See [Webhooks](/developer-manual/webhooks). ## Test and live Sandbox and live each need their own `cpmt_` id. The API key carries the mode: `glm_test_…` or `glm_live_…`. ## Scope of this page This checkout charges once. Leave `mode` and `plan_id` off the request. If the subscription is in Stripe Billing, use [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing). Subscriptions without Stripe Billing and Stripe Checkout Sessions are not generally available. See the [overview](/custom-payment-methods/overview). ## Charging the same card again To charge the shopper again later from your own system, for a renewal or a refill, add `"setup_future_usage": "off_session"` to the checkout you create in Step 3. The shopper agrees on the hosted page, a payment method id is returned, and you charge it by API. Send the same `payment_source` in `metadata` on each of those charges and they are written to your Stripe account too. See [Saved Payment Methods](/integration/saved-payment-methods). ## Refunds Refund the order with [`POST /api/v2/refunds`](/api-reference/endpoint/create-refund). `order_id` and `reason` are required. `amount` is optional and is in cents. `refund.created`, `refund.succeeded`, or `refund.failed` follows by webhook. Stripe does not send `charge.refunded` for this payment. Do not refund it from the Stripe Dashboard. ## Failure modes * **Wrong or missing API key, or a key from the other environment** → `401`/`422` from `/api/v2/checkout`. * **Line item missing `product_id`** → `422`. It's required on every line item. A `product_id` that is not HSA/FSA-eligible is accepted. That item is charged as a regular purchase. * **`success_url` / `failure_url` not HTTPS** → checkout creation is rejected. Use a tunnel or a local certificate in development. * **Payments are not configured for this environment** → `CHECKOUT_001`. No checkout is created. ## Test your integration **1. Use test credentials** Use your `glm_test_…` API key and your test-mode `cpmt_…` id. The key prefix sets the mode. Nothing else about the request changes. **2. Confirm the option renders** Load your checkout: **Pay with HSA/FSA** appears after your native methods, with the name and logo you gave the type in Stripe. If it does not, the problem is on the Stripe side: wrong mode, wrong account, or a `cpmt_` id that does not belong to the publishable key mounting the Element. Also check that Adaptive Pricing is not active. No dashboard setting changes this. **3. Confirm the branch skips stripe.confirmPayment** Select Pay with HSA/FSA and submit. Your handler should branch before Stripe's confirm call, so no PaymentIntent is created or confirmed. If one appears in your Stripe logs, the branch is not firing. **4. Create a checkout** Your backend endpoint calls `POST /api/v2/checkout` and answers `{ data: { checkout_url, checkout_id } }`, and the shopper lands on the hosted page. **5. Run a mixed cart** Include an item whose `product_id` is not HSA/FSA-eligible. It should still be charged, as a regular purchase, and not rejected. **6. Confirm the outcome server-side** Verify `order.completed` on your own backend before fulfilling. The order appears in the merchant dashboard under **Orders** with the `reference_id` you sent. A payment record is reported to Stripe with the restricted key from Step 2. There is no Stripe Charge. **7. Test cancel and decline** Abandon the hosted page and confirm the shopper returns to your `failure_url` and can pay another way, with the order left unfulfilled. > [!WARNING] > > **There is no PaymentIntent and no Charge for a Pay with HSA/FSA payment.** A > `payment_intent.succeeded` or `charge.succeeded` handler never fires for > one. Fulfill from `order.completed`. Your server cannot verify a browser > redirect. ## Go-live checklist * Live API key (`glm_live_…`) on the live code path, and the live `cpmt_` id in the Element * Restricted key saved on Pay with HSA/FSA on Stripe, with Payment Records read and write * Endpoint URL on the custom payment method left empty * `product_id` present on every line item * `success_url` and `failure_url` are HTTPS * `order.completed` verified before fulfillment, with `X-Gale-Signature` checked * One real live transaction in the merchant dashboard, and the payment record in Stripe * Refunds go through `POST /api/v2/refunds`, not the Stripe Dashboard ## Related * [Create Checkout Session](/api-reference/endpoint/create-checkout-v2) * [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe) * [Saved Payment Methods](/integration/saved-payment-methods) * [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing) * [Webhooks](/developer-manual/webhooks) * [Create a refund](/api-reference/endpoint/create-refund) # Pay with HSA/FSA on Stripe Source: https://docs.withgale.com/custom-payment-methods/gale-on-stripe Save the restricted key used to write a Pay with HSA/FSA payment back to your Stripe account. **Pay with HSA/FSA on Stripe** is in the merchant dashboard: open **Integrations**, then the **Pay with HSA/FSA on Stripe** card. The one-time Payment Element setup saves its restricted key here. That key authenticates to your Stripe account and is used to write the payment record. Save the key before you take a test payment. The page is per mode. Sandbox and production keep separate credentials, and a test key cannot be saved into production. Create the `cpmt_…` id on the [Payment Element](/custom-payment-methods/elements-payment-intent#step-1-create-your-custom-payment-method) page and paste it here. Leave the endpoint URL blank on that path. The [Checkout Session](/custom-payment-methods/elements-checkout-session) path is the one that sets the endpoint URL and the signing secret. ## Credentials | Field | What to paste | Required | | - | - | - | | **Restricted API key** | The `rk_…` key Stripe showed you. Not your secret key. | Required the first time you save. Leave the field blank to keep the key already stored. | | **Custom payment method type ID** | The `cpmt_…` id from the Payment Element page | Paste it for the Payment Element setup. Leave the field blank to keep the saved id. | | **Signing secret** | Leave blank for the Payment Element | The Checkout Session path needs this secret. Leave the field blank to keep a secret already stored. | The key is checked when you save. Payment Records read and write have to be granted, or the page will not save. Other permissions may be missing. The page shows a warning and still saves. ## Create the restricted key Create one restricted key per Stripe account, per mode. A restricted key cannot move money. **1. Open API keys** In the Stripe Dashboard, open **Developers** and choose **API keys**. ![Stripe Developers menu listing Workbench, Documentation, and API keys](https://mintcdn.com/galepaymentsinc/xCMsVFbcovX9wrtB/images/stripe-cpm-key-1-developers.png?fit=max\&auto=format\&n=xCMsVFbcovX9wrtB\&q=85\&s=7cdd9500b28b8f2e2bde99adcd7935a8) Developers → API keys **2. Create a restricted key** Find the **Restricted keys** card and click **Create restricted key**. Not the standard secret key above it. ![Restricted keys card with the Create restricted key button](https://mintcdn.com/galepaymentsinc/xCMsVFbcovX9wrtB/images/stripe-cpm-key-2-restricted-keys.png?fit=max\&auto=format\&n=xCMsVFbcovX9wrtB\&q=85\&s=e7bda58f365e092086e1bf9538901fb3) Restricted keys → Create restricted key **3. Choose how the key will be used** Pick **Powering an integration you built** and click **Continue**. ![Create a restricted key dialog with three usage options](https://mintcdn.com/galepaymentsinc/xCMsVFbcovX9wrtB/images/stripe-cpm-key-3-usage.png?fit=max\&auto=format\&n=xCMsVFbcovX9wrtB\&q=85\&s=901ca5cd1ebe64c0ebe01ca37dccbd89) Create a restricted key, usage "Providing this key to a third-party application" leads to a different flow. Use the first option. **4. Grant Payment Records** Set **Payment Records** to **Write**. Stripe's Write level includes Read, and the dashboard page requires both. Without them, the save fails. Leave Checkout Sessions, Products, Prices, Payment Methods, Subscriptions, and Webhook Endpoints at **None**. The dashboard page lists each of those as a warning. A warning does not block the save. For [Stripe Billing subscriptions](/custom-payment-methods/stripe-billing), also set **Invoices** to **Write**. It is used to attach each payment to its invoice. ![Create restricted API key page listing resources with None, Read and Write toggles](https://mintcdn.com/galepaymentsinc/xCMsVFbcovX9wrtB/images/stripe-cpm-key-4-resources.png?fit=max\&auto=format\&n=xCMsVFbcovX9wrtB\&q=85\&s=ed06003da75a7174988e5eda64250e3f) The resource list, all permissions at None Set the level on the **child row**, not the section header. Setting the section grants far more than this page checks. **5. Name it and create it** Name the key, for example `Pay with HSA/FSA`. Then click **Create key** and copy what Stripe shows you. > [!WARNING] > > Stripe shows a restricted key once. If you leave the page before copying it, create another. Permissions cannot be edited after the key exists, so a missed Payment Records grant also means a new key. Paste the key into **Restricted API key** and save. On the Payment Element path, leave the signing secret blank. ## After you save The panel lists each permission as granted, missing, or a warning. * **Payment Records read and write** are required. If either is missing, the page will not save. * The other rows are warnings. A warning does not block the save. * **Signing secret** shows whether one is stored. The value is never shown again. For the Payment Element path, leave it unset. * **Re-check permissions** runs the check again. Stripe will not show the restricted key a second time, so saving the form again does not refresh the check. ## Which payments are written to Stripe A payment record is written for a payment whose request carries this in `metadata`: ```json theme={null} { "metadata": { "payment_source": "stripe_elements_cpm" } } ``` Send it on the checkout you create for the [Payment Element](/custom-payment-methods/elements-payment-intent), and on each later charge of a [stored card](/integration/saved-payment-methods). On the Payment Element setup, a payment without it is not written to Stripe. ## Related * [Stripe Payment Element](/custom-payment-methods/elements-payment-intent) * [Saved Payment Methods](/integration/saved-payment-methods) * [Webhooks](/developer-manual/webhooks) * [Create a refund](/api-reference/endpoint/create-refund) # Stripe Custom Payment Methods Source: https://docs.withgale.com/custom-payment-methods/overview Add Pay with HSA/FSA to Stripe. Pick the page that matches how you charge. **Pay with HSA/FSA** appears in your Stripe checkout as a custom payment method. The card is charged on a hosted page. Save a restricted key on [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe) so the payment can be written back to your Stripe account. Fulfill the order from `order.completed`. ## Pick your path | How you charge | Follow | | - | - | | One payment, in a Payment Element you already run | [Stripe Payment Element](/custom-payment-methods/elements-payment-intent) | | The same shopper again, when your own system decides: refills, or renewals you schedule yourself | [Stripe Payment Element](/custom-payment-methods/elements-payment-intent), then [Saved Payment Methods](/integration/saved-payment-methods) | | A subscription that lives in Stripe Billing, where Stripe raises an invoice for each cycle | [Stripe Billing Subscriptions](/custom-payment-methods/stripe-billing) | Two more paths are not generally available. Ask your account manager before building on either. * [Subscriptions](/subscriptions/overview): the plan and the schedule are kept for you, without Stripe Billing. * [Stripe Checkout](/custom-payment-methods/elements-checkout-session): for Stripe Checkout, not the Payment Element. Stripe calls an endpoint URL set on the custom payment method. ## What every path shares 1. You create a custom payment method type in Stripe for Pay with HSA/FSA. 2. You save a restricted key on [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe). 3. Your server creates a checkout with `"metadata": {"payment_source": "stripe_elements_cpm"}` and sends the shopper to the hosted page. 4. The card is charged and the payment is written to your Stripe account as a payment record. 5. You fulfill from the `order.completed` webhook. The paths differ only in what happens after the first payment. ## Related * [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe): where you save the restricted key * [Create Checkout Session](/api-reference/endpoint/create-checkout-v2): the request every path starts with * [Charge a Payment Method](/api-reference/endpoint/charge-payment-method): used for refills and renewals * [Payment Method Object](/api-reference/objects/payment-method) * [Order Object](/api-reference/objects/order) * [Webhooks](/developer-manual/webhooks) * [Create a refund](/api-reference/endpoint/create-refund) # Stripe Billing Subscriptions Source: https://docs.withgale.com/custom-payment-methods/stripe-billing Keep the subscription in Stripe Billing. Each invoice is collected from the shopper's HSA/FSA card. Use this when the subscription lives in your Stripe account: Stripe creates an invoice for each cycle, and tools that follow Stripe Billing act on `invoice.paid`. The shopper's HSA/FSA card is charged for each invoice and the payment is reported to Stripe, so Stripe marks the invoice paid and keeps the subscription active. Your system starts every charge. This API keeps no schedule. > [!NOTE] > > This flow is enabled per merchant account. Ask your account manager to enable it for your test account. ## Responsibilities | | Stripe | This API | You | | - | - | - | - | | Subscription, plan, billing dates | Owns them | | Create and cancel them in Stripe | | Card details | Never sees them | Collects them on the hosted page and stores the card | | | Charging the card | | Charges it, first payment and renewals | Start each charge by API | | Invoice status | Marks it paid when the payment is attached | Attaches the payment | | | Access to your product | Sends `invoice.paid` | Sends `order.completed` | Grant access from either | ## Before you start * Create a custom payment method type in Stripe for Pay with HSA/FSA, as in Step 1 of the [Stripe Payment Element](/custom-payment-methods/elements-payment-intent#step-1-create-your-custom-payment-method) page. You need its `cpmt_...` id. * Save a restricted key on [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe). Set **Payment Records** to Write and **Invoices** to Write. No permission on charges, balance or payouts is needed. * [Saved payment methods](/integration/saved-payment-methods) are enabled for your account. * The product you sell is in your product catalog. Each product is reviewed for HSA/FSA eligibility. A digital product needs no UPC. ## How it works 1. You create the Stripe customer and the subscription, with your custom payment method as its default. 2. For the first invoice, you create a checkout that stores the card and names the Stripe customer and invoice. 3. The shopper pays on the hosted page. A payment record is written to your Stripe account and attached to the invoice. 4. Stripe marks the invoice paid and the subscription active, and sends `invoice.paid`. 5. For each renewal, Stripe sends you `invoice.payment_attempt_required`. You charge the stored card by API and name the new invoice. ## Step 1: Create the subscription in Stripe Create a payment method of your custom type, attach it to the customer, and create the subscription with `payment_behavior: "default_incomplete"`. ```js theme={null} const paymentMethod = await stripe.paymentMethods.create({ type: 'custom', custom: { type: 'cpmt_...' }, // your Pay with HSA/FSA type id }); await stripe.paymentMethods.attach(paymentMethod.id, { customer: customer.id }); const subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{ price: 'price_...' }], payment_behavior: 'default_incomplete', default_payment_method: paymentMethod.id, }); // subscription.latest_invoice is the first invoice, status "open" ``` > [!WARNING] > > Stripe expires an incomplete subscription 23 hours after it is created. Redirect the shopper to the checkout as soon as the subscription is created. ## Step 2: Collect the first invoice Create a checkout for the invoice amount. Three keys in `metadata` tie it to Stripe. ```json theme={null} { "reference_id": "in_1Abc...", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [ { "product_id": "MEMBERSHIP", "name": "Monthly membership", "price": 2500, "quantity": 1, "currency": "USD" } ], "shipping_info": { "address_line_1": "1 Main St", "city": "Austin", "state": "TX", "postal_code": "78701", "country": "US" }, "success_url": "https://yoursite.com/welcome", "failure_url": "https://yoursite.com/pricing", "setup_future_usage": "off_session", "metadata": { "payment_source": "stripe_elements_cpm", "stripe_customer_id": "cus_...", "stripe_invoice_id": "in_1Abc..." } } ``` | Key | Value | | - | - | | `payment_source` | `stripe_elements_cpm`. The payment is written to your Stripe account | | `stripe_customer_id` | The customer on the invoice | | `stripe_invoice_id` | The open invoice this payment settles. Needs `stripe_customer_id` | The checkout total has to equal what is due on the invoice. A payment of a different amount is refused. `customer.email`, `customer.first_name` and `customer.last_name` are required. `customer.phone` is optional. `shipping_info` is required even for a digital product, so send the customer's billing address there. Card details are entered on the hosted page. When the shopper pays, you receive `payment_method.id` on the `order.completed` webhook. Store it against the Stripe customer. ## Step 3: Collect each renewal Listen for `invoice.payment_attempt_required` on your Stripe webhook. Charge the stored card for that invoice. ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/payment-methods/pm_.../charges \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Idempotency-Key: in_1Def...-attempt-1" \ -H "Content-Type: application/json" \ -d '{ "reference_id": "in_1Def...", "line_items": [ { "product_id": "MEMBERSHIP", "name": "Monthly membership", "price": 2500, "quantity": 1, "currency": "USD" } ], "metadata": { "payment_source": "stripe_elements_cpm", "stripe_customer_id": "cus_...", "stripe_invoice_id": "in_1Def..." } }' ``` The card is charged, and the payment record is written and attached to the invoice. Stripe sends `invoice.paid` once the payment is captured. ## Events | Event | Where it arrives | | - | - | | A cycle is due | Stripe: `invoice.payment_attempt_required` | | The payment succeeded | Webhook: `order.completed`. Stripe: `invoice.paid` | | The card was declined | API: `422` on the charge, with a `checkout_url` for the shopper. Webhook: `payment.failed`. Stripe: the invoice stays open and the subscription moves to `past_due` | | A refund | Webhooks: `refund.created`, `refund.succeeded`, `refund.failed` | ## When a payment is refused before charging The invoice is read from Stripe before the card is charged, on the first checkout and on every renewal. A payment that could not settle the invoice is refused and no money is taken. | Answer | Meaning | What to do | | - | - | - | | `422` `CHECKOUT_004` | The payment cannot settle the invoice it names. `error.message` gives the reason | See the reasons below | | `422` `GEN_003` | An id is malformed, `stripe_invoice_id` came without `stripe_customer_id`, or the ids came without `payment_source`. The reason is in `error.validation_errors.metadata` | Fix the request | Reasons behind `CHECKOUT_004`: * The invoice is paid, void, or still a draft. Only an open invoice can be paid, so wait for `invoice.payment_attempt_required` before you charge a renewal. * The invoice belongs to a different customer than `stripe_customer_id`. * The total of the payment does not match what is due on the invoice. * The invoice was not found in the Stripe account and mode of the saved key. * The saved key cannot read invoices. It needs **Invoices** set to Write. * The invoice was already collected with an earlier order. The card is not charged again, and the earlier payment is attached to the invoice. No action is needed. * Another payment for this invoice is in progress. Retry after a few minutes. While that payment is waiting for an answer from the card network, the invoice stays held. A hosted checkout is checked again when the shopper pays, which can be later than when you created it. If the invoice changed in between, the shopper sees a message and is not charged. Create a new checkout for the current invoice. ## Declines A declined renewal returns `422` with `PAYMENT_METHOD_010` and a `checkout_url`. The failed payment is reported to the invoice in Stripe, so the subscription moves to `past_due` and your retry schedule in Stripe runs. Stripe's Smart Retries do not cover these payments, so use a custom retry schedule or an automation. A declined charge is not retried automatically. Each retry from Stripe sends `invoice.payment_attempt_required` again. Call the charge again with a new `Idempotency-Key`. No wait is required between attempts. The retry is recorded on the same payment in Stripe, so the invoice shows one payment with its attempts. To let the shopper pay with another card, send them the `checkout_url`. ## Refunds and disputes Refund the order with [`POST /api/v2/refunds`](/api-reference/endpoint/create-refund), sending `order_id` and a `reason`. The refund is reported to the payment record in Stripe. The invoice stays paid and the subscription stays active. Stripe does not send `charge.refunded`, and no credit note is created. Create one in Stripe if your accounting requires it. Stripe does not hold disputes for payments processed outside Stripe, so a dispute on one of these payments does not appear in your Stripe account. Stripe lists this in its [limitations](https://docs.stripe.com/billing/subscriptions/third-party-payment-processing). ## Cancelling Cancel the subscription in Stripe. Nothing has to be cancelled through this API, because a charge only happens when your system requests one. To remove the customer's card, call [`DELETE /api/v2/payment-methods/{id}`](/api-reference/endpoint/delete-payment-method). ## Webhooks Every webhook is signed with `X-Gale-Signature`, and a failed delivery is retried. Add your endpoint in the merchant dashboard under **Developer Tools** > **Webhooks**. See [Webhooks](/developer-manual/webhooks) for the signature check and every event. ## Testing Use a `glm_test_` key and a restricted key from your Stripe sandbox. Put the Stripe customer on a [test clock](https://docs.stripe.com/billing/testing/test-clocks) and advance it one cycle to make Stripe send `invoice.payment_attempt_required`. Pay with the [test cards](/resources/test-cards). ## Limits * One invoice per charge, and the amounts have to match. * An invoice is paid with one card. A payment split across two cards is refused. * The card is charged the full amount of the invoice or declined. A partial amount is not taken. * A renewal cannot mix eligible and non-eligible items. An item that needs a Letter of Medical Necessity renews only while the shopper holds a valid letter for it. * To change the shopper's card, send them a new checkout with `setup_future_usage` and remove the old payment method. ## Related * [Create Checkout Session](/api-reference/endpoint/create-checkout-v2) * [Checkout Session Object](/api-reference/objects/checkout-session) * [Payment Method Object](/api-reference/objects/payment-method) * [Order Object](/api-reference/objects/order) * [Create a refund](/api-reference/endpoint/create-refund) * [Saved Payment Methods](/integration/saved-payment-methods) * [Charge a Payment Method](/api-reference/endpoint/charge-payment-method) * [Pay with HSA/FSA on Stripe](/custom-payment-methods/gale-on-stripe) * [Webhooks](/developer-manual/webhooks) # Authentication Source: https://docs.withgale.com/developer-manual/authentication How to authenticate API requests and ensure safe retries using idempotency keys. # Authentication All requests to the Gale API must be authenticated using a valid API key. ## Base URL ``` https://api.withgale.com/api/v2 ``` ## API Keys ### Getting Your API Key 1. Log in to [Gale Dashboard](https://dashboard.withgale.com) 2. Navigate to **Developer Tools** → **API Keys** 3. Select **Generate API Key**, give the key a name, and select **Generate Key** 4. Copy the key from the dialog and store it securely > [!WARNING] > > The full key is displayed **only once**, at the moment you generate it. The API Keys table shows a truncated value that cannot be used to authenticate. If you lose a key, revoke it and generate a new one. Keys are scoped to the environment you're in when you generate them, and the table only lists keys for the environment you're currently viewing. Use the **Test Mode** toggle in the top bar to switch. * **Test keys** (prefix: `glm_test_`) - Generated with Test Mode on. For development and testing * **Live keys** (prefix: `glm_live_`) - Generated with Test Mode off. For production Live keys become available once account verification is complete. A key looks like `glm_live_.`. To disable a key, open the **⋮** menu beside it and select **Revoke Key**. Revoking takes effect immediately and breaks every integration using that key. ### Using Your API Key Include your API key in the `Authorization` header of every request: ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` **Example request:** ```bash theme={null} curl https://api.withgale.com/api/v2/products \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ### Authentication Errors Missing or invalid API keys return a `401 Unauthorized` response: ```json theme={null} { "error": { "code": "unauthorized", "message": "Invalid or missing API key" } } ``` ## Idempotency Prevent duplicate operations by using idempotency keys for state-changing requests. ### How It Works Add an `Idempotency-Key` header to prevent duplicate processing: ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/checkout \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000" \ -H "Content-Type: application/json" \ -d '{...}' ``` * **Key format**: Use a unique UUID (v4 recommended) * **Validity**: Keys are stored for 24 hours * **Behavior**: Requests with the same key within 24 hours return the original response without reprocessing ### When to Use Use idempotency keys for: * Creating checkout sessions (`POST /api/v2/checkout`) * Creating refunds (`POST /api/v2/refunds`) * Creating payment links (`POST /api/v2/payment-links`) * Any POST request that creates or modifies data ### Best Practices * Generate a new UUID for each operation * Retry failed requests with the **same** idempotency key * Store the key with your request for retry scenarios * Don't reuse keys across different operations **Example:** ```javascript theme={null} const { v4: uuidv4 } = require('uuid'); const createCheckout = async (data) => { const idempotencyKey = uuidv4(); const response = await fetch('https://api.withgale.com/api/v2/checkout', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Idempotency-Key': idempotencyKey, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); return response.json(); }; ``` ## Security Best Practices * **Never expose API keys** in client-side code or public repositories * **Use environment variables** to store API keys * **Rotate keys regularly** in production * **Use test keys** for development and staging environments * **Monitor API key usage** in your dashboard ## Related * [Rate Limits](/developer-manual/rate-limits) - API request limits * [Errors](/developer-manual/errors) - Error handling # Errors Source: https://docs.withgale.com/developer-manual/errors Learn about standardized error responses and how to interpret them. # Error Handling Gale returns consistent and descriptive error responses across all endpoints to help you debug and recover gracefully. ## Standard Error Format All errors follow this format: ```json theme={null} { "error": { "code": "validation_error", "message": "Validation failed: merchant_product_id is required.", "details": { "field_errors": { "merchant_product_id": ["This field is required"] } } } } ``` ## HTTP Status Codes | Status Code | Error Code | Meaning | When It Happens | | - | - | - | - | | 400 | `bad_request` | Bad Request | Malformed JSON or missing required fields | | 401 | `unauthorized` | Unauthorized | Missing or invalid API key | | 403 | `forbidden` | Forbidden | Valid token but insufficient permissions | | 404 | `not_found` | Not Found | Resource does not exist | | 409 | `conflict` | Conflict | Invalid state change | | 422 | `validation_error` | Validation Failed | Field validation failed | | 429 | `rate_limit_exceeded` | Too Many Requests | Rate limit exceeded | | 500 | `internal_error` | Server Error | Something went wrong on Gale's side | ## Error Examples ### Validation Error (422) ```json theme={null} { "error": { "code": "validation_error", "message": "Validation failed", "details": { "field_errors": { "line_items": ["At least one line item is required"], "customer.email": ["Invalid email format"] } } } } ``` ### Unauthorized (401) ```json theme={null} { "error": { "code": "unauthorized", "message": "Invalid or missing API key" } } ``` ### Not Found (404) ```json theme={null} { "error": { "code": "not_found", "message": "Order not found" } } ``` ### Rate Limited (429) ```json theme={null} { "error": { "code": "rate_limit_exceeded", "message": "Too many requests. Please try again in 30 seconds." } } ``` Response includes `Retry-After` header indicating seconds to wait. ## Best Practices * **Check status code first**: Use HTTP status codes to determine error type * **Parse error details**: Check `error.details.field_errors` for specific validation failures * **Implement retry logic**: For 429 and 500 errors, retry with exponential backoff * **Log errors**: Store error responses for debugging ## Related * [Authentication](/developer-manual/authentication) - API key setup * [Rate Limits](/developer-manual/rate-limits) - Handling rate limits # Getting Started Source: https://docs.withgale.com/developer-manual/getting-started Get up and running with Gale's API in minutes # Getting Started This guide walks you through creating your first checkout session using Gale's API. By the end, you'll understand the full payment flow. ## Base URL ``` https://api.withgale.com/api/v2 ``` Use test API keys (prefix `glm_test_`) during development. All test transactions are processed in sandbox mode with no real charges. ## Authentication Include your API key in the `Authorization` header: ```bash theme={null} Authorization: Bearer glm_test_YOUR_API_KEY ``` Generate an API key in the [Gale Dashboard](https://dashboard.withgale.com) under **Developer Tools** > **API Keys**. The full key is shown only once, when you generate it — copy it straight away. See [Authentication](/developer-manual/authentication) for details. ## Quick Start ### 1. Sync a Product Before creating a checkout, sync your product catalog so Gale can determine HSA/FSA eligibility. ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/products \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Digital Blood Pressure Monitor", "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "price": 4995, "currency": "USD" }' ``` The response includes eligibility status: ```json theme={null} { "success": true, "data": { "id": 12345, "name": "Digital Blood Pressure Monitor", "merchant_product_id": "BP-MONITOR-001", "price": 4995, "eligibility": { "hsa_fsa_eligible": true, "message": "SIGIS verified - Medical device" } } } ``` ### 2. Create a Checkout Session Create a checkout session and get a URL to redirect your customer to: ```bash theme={null} curl -X POST https://api.withgale.com/api/v2/checkout \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "reference_id": "your-order-123", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [ { "product_id": "BP-MONITOR-001", "name": "Digital Blood Pressure Monitor", "price": 4995, "quantity": 1 } ], "shipping_info": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "shipping": 500, "tax": 410, "success_url": "https://yoursite.com/order/success", "failure_url": "https://yoursite.com/order/failed" }' ``` Response: ```json theme={null} { "success": true, "checkout_id": "01HXYZ...", "checkout_url": "https://checkout.withgale.com/checkout/01HXYZ...", "status": "open", "expires_at": "2026-02-26T14:30:00Z" } ``` ### 3. Redirect Customer Send your customer to the `checkout_url`. Gale's hosted checkout page handles: * HSA/FSA card collection * Eligibility verification * Letter of Medical Necessity (LMN) flow for dual-purpose items * Payment processing After payment, the customer is redirected to your `success_url` or `failure_url`. ### 4. Confirm Payment **Option A: Webhooks (recommended)** Register a webhook endpoint in your [Dashboard](https://dashboard.withgale.com) under **Developer Tools** > **Webhooks**. Gale sends an `order.completed` event when payment succeeds: ```json theme={null} { "type": "order.completed", "data": { "id": "ord_abc123", "status": "completed", "checkout_id": "01HXYZ...", "reference_id": "your-order-123", "customer": { "email": "jane@example.com" } } } ``` **Option B: Poll for status** Check the checkout status by querying the order: ```bash theme={null} curl https://api.withgale.com/api/v2/orders/{order_id} \ -H "Authorization: Bearer glm_test_YOUR_API_KEY" ``` ## Three Key IDs | ID | What it is | When you get it | | - | - | - | | `checkout_id` | The checkout session you created | Returned when you create a checkout | | `order_id` | The payment record after successful payment | Returned in webhooks and order queries | | `reference_id` | Your own order/cart ID for correlation | You provide this when creating a checkout | ## Testing Use test API keys (`glm_test_*`) during development. Test card numbers: | Card Number | Result | | - | - | | `4111 1111 1111 1111` | Successful payment | | `4000 0000 0000 0002` | Card declined | See [Test Cards](/resources/test-cards) for the full list. ## Next Steps > [card] [Integration Flow](/developer-manual/integration-flow) > > Full end-to-end integration walkthrough > [card] [Checkout Guide](/integration/checkout) > > Detailed checkout integration guide > [card] [API Reference](/api-reference/introduction) > > Complete API endpoint documentation > [card] [Webhooks](/developer-manual/webhooks) > > Set up real-time event notifications # Integration Flow Source: https://docs.withgale.com/developer-manual/integration-flow Understand the end-to-end flow of integrating with the Gale API platform. This page outlines the complete sequence of steps required to successfully integrate with Gale's API platform. ## 1. Product Sync Before initiating any checkout session, sync your product catalog with Gale. Each product includes its name, UPC/GTIN, and your SKU as `merchant_product_id`. Endpoint: ``` POST /api/v2/products ``` This step ensures Gale has full context of the items you intend to sell through the hosted checkout. See the [Product API Reference](/api-reference/endpoint/create-product-v2) for full details. Send each SKU once with `POST /api/v2/products`, and store the Gale `id` from the response. Use `PUT /api/v2/products/{id}` for changes. The API does not look up or dedupe products by SKU, so sending the same SKU twice creates two products. ## 2. Eligibility Classification When a product has a UPC or GTIN, Gale checks HSA/FSA eligibility against the SIGIS database. Each product response includes an `eligibility` object with: * `hsa_fsa_eligible`: boolean indicating whether the product qualifies for HSA/FSA * `eligibility_type`: the basis for eligibility, such as `auto_substantiation`, or `null` * `reason`: a short, human-readable reason for the result You can: * Check the `eligibility` object on any product response from [Create Product](/api-reference/endpoint/create-product-v2) * Read the current eligibility again with [Get Product](/api-reference/endpoint/get-product-v2) ## 3. Hosted Checkout Session With eligible products in place, initiate a hosted checkout session using the Gale API. Endpoint: ``` POST /api/v2/checkout ``` You must include customer details, line items, shipping, tax, and a `reference_id` (your order or cart ID for correlation). A successful response returns a `checkout_id` and `checkout_url` which you redirect your customer to. Gale automatically determines the checkout type based on product eligibility: * **Eligible** - All items are HSA/FSA eligible, entire amount charged to HSA/FSA card * **Split** - Mix of eligible and non-eligible items, Gale handles splitting payment across HSA/FSA and regular payment methods * **Regular** - No items are eligible, standard payment processing See [Checkout API Reference](/api-reference/endpoint/create-checkout-v2) for full request/response details. ## 4. Payment Processing The customer completes payment on Gale's hosted checkout page. Once paid, an **order** is created. ### Order Lifecycle Orders track both fulfillment and payment separately: **Order Status** (your fulfillment state): * `pending` - Order created, awaiting payment * `processing` - Payment in progress * `completed` - Payment successful, ready to fulfill * `failed` - Payment declined * `cancelled` - Order cancelled **Payment Status** (money movement): * `pending` - Payment not attempted * `authorized` - Funds reserved (not yet captured) * `captured` - Funds captured successfully * `refunded` - Funds returned to customer This separation gives you flexibility. For example, an order can be `completed` while payment is still `authorized` (not yet captured). **Most merchants only need to check:** Order `status === 'completed'` means the order is paid and ready to ship. Check order status anytime: ``` GET /api/v2/orders/{order_id} ``` ### Three Key IDs Keep these distinct: | ID | What it is | When you get it | | - | - | - | | `checkout_id` | The checkout session you created | Returned when you create a checkout | | `order_id` | The payment record after successful payment | Returned in webhooks and order queries | | `reference_id` | Your own order/cart ID for correlation | You provide this when creating a checkout | ## 5. Webhook Notifications Gale sends webhooks when important events occur. All payment flows (checkout sessions, payment links) create orders, so you'll receive order webhooks. ### Common Webhooks **For Checkout Sessions and Payment Links:** * `order.completed` - Payment captured. Fulfil the order * `order.failed` - The order is closed and will not complete * `payment.failed` - A payment attempt was declined. The shopper can retry * `refund.succeeded` - A refund was processed * `checkout.expired` - A checkout session expired without payment See the [Webhooks reference](/developer-manual/webhooks) for every event and its payload. ### Setup 1. Register your webhook URL in **Settings** > **Webhooks** in the Gale Dashboard 2. Validate signatures using `X-Gale-Signature` header 3. Respond with HTTP 200 within 5 seconds 4. Gale retries failed deliveries with exponential backoff See [Webhooks Reference](/developer-manual/webhooks) for all event types and examples. ## 6. Refunds You can issue full refunds via the API: ``` POST /api/v2/refunds ``` For split checkout sessions (where payment was split across HSA/FSA and regular payment methods), partial refunds are managed through the [Gale Dashboard](https://dashboard.withgale.com). See [Refund API Reference](/api-reference/endpoint/create-refund) for details. ## Summary | Step | Description | | - | - | | Product Sync | Send your products to Gale | | Eligibility | Check which items are HSA/FSA eligible | | Create Checkout | Launch a hosted checkout session | | Process Payment | Customer completes payment on Gale's page | | Listen to Webhooks | Receive real-time updates | | Handle Refunds | Process returns via API or Dashboard | Refer to the API Reference section for implementation details of each step. # Rate Limits Source: https://docs.withgale.com/developer-manual/rate-limits Understand how Gale enforces rate limits and how to handle throttled requests. # Rate Limits Gale enforces rate limits to ensure consistent performance and prevent abuse. ## Current Limits | API Key Type | Requests per Minute | | - | - | | Test keys (`glm_test_*`) | 100 | | Live keys (`glm_live_*`) | 1000 | Limits are enforced per API key across all endpoints. All requests count toward your limit regardless of HTTP method (GET, POST, etc.). ## Rate Limit Headers Every API response includes rate limit information: ``` X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 995 X-RateLimit-Reset: 1698345600 ``` * `X-RateLimit-Limit`: Total requests allowed per minute * `X-RateLimit-Remaining`: Requests remaining in current window * `X-RateLimit-Reset`: Unix timestamp when the limit resets ## Handling Rate Limits When you exceed the rate limit, you'll receive a `429` response: ```json theme={null} { "error": { "code": "rate_limit_exceeded", "message": "Too many requests. Please try again in 30 seconds." } } ``` Response includes: ``` HTTP/1.1 429 Too Many Requests Retry-After: 30 ``` The `Retry-After` header indicates seconds to wait before retrying. ## Best Practices ### 1. Implement Exponential Backoff ```javascript theme={null} async function makeRequestWithRetry(url, options, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { const response = await fetch(url, options); if (response.status === 429) { const retryAfter = response.headers.get('Retry-After') || (2 ** i); await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); continue; } return response; } throw new Error('Max retries exceeded'); } ``` ### 2. Use Webhooks Instead of Polling Don't poll for order status - use webhooks: **Bad:** ```javascript theme={null} // Polling every second setInterval(async () => { const order = await getOrder(orderId); }, 1000); ``` **Good:** ```javascript theme={null} // Use webhooks app.post('/webhooks/gale', (req, res) => { if (req.body.type === 'order.completed') { handleOrder(req.body.data); } }); ``` ### 3. Batch Operations Use batch endpoints when available: ```javascript theme={null} // Instead of multiple requests for (const product of products) { await checkEligibility(product); // 100 requests } // Use batch endpoint await batchCheckEligibility(products); // 1 request ``` ### 4. Cache Results Cache eligibility checks and product data: ```javascript theme={null} const cache = new Map(); async function getProductEligibility(productId) { if (cache.has(productId)) { return cache.get(productId); } const result = await checkEligibility(productId); cache.set(productId, result); return result; } ``` ## Request Higher Limits Need higher limits for your production use case? Contact [support@withgale.com](mailto:support@withgale.com) with: * Your use case description * Expected request volume * Current API key ## Related * [Authentication](/developer-manual/authentication) - API key setup * [Errors](/developer-manual/errors) - Error handling # Webhooks Source: https://docs.withgale.com/developer-manual/webhooks Receive real-time notifications about events in your Gale account # Webhooks Webhooks allow your application to receive real-time notifications when events happen in your Gale account, such as completed payments, failed charges, and refunds. ## How Webhooks Work 1. **Customer** completes payment on Gale's checkout page 2. **Gale** processes the payment 3. **Gale sends** a POST request to your webhook endpoint with event data 4. **Your server** processes the event (e.g., fulfills order, sends email) 5. **Your server** returns a `200 OK` response 6. **Event is marked** as delivered successfully If your server doesn't respond with `200`, Gale retries the delivery automatically. ## Setup ### 1. Create an Endpoint on Your Server ```javascript theme={null} app.post('/webhooks/gale', async (req, res) => { // Acknowledge immediately — process async res.status(200).send('OK'); const event = req.body; switch (event.type) { case 'order.completed': await fulfillOrder(event.data); break; case 'order.failed': await notifyOrderFailed(event.data); break; case 'refund.succeeded': await handleRefund(event.data); break; } }); ``` ### 2. Register It in the Dashboard 1. Log in to [Gale Dashboard](https://dashboard.withgale.com) 2. Go to **Developer Tools** → **Webhooks** 3. Click **Add Endpoint** 4. Enter your webhook URL 5. Select the events to subscribe to 6. Copy the secret shown — **it is only displayed once** ## Authentication Verify `X-Gale-Signature` before you trust the body. The endpoint secret is the HMAC key. Gale still sends `Authorization: Bearer ` on the same request. That header will be removed. Use the signature as your check. | Header | Purpose | | - | - | | `X-Gale-Signature` | `t=,v1=` | | `X-Gale-Event` | The event type | | `X-Gale-Delivery` | This delivery's id | `v1` is HMAC-SHA256 over `"."`, keyed with the endpoint secret. Compare in constant time. Reject a `t` older than 5 minutes. During a secret rotation the header can carry more than one `v1`. Accept the delivery if any of them matches. Verify the raw body, before JSON parsing. In Express use `express.raw()` on this route. ```javascript theme={null} app.post('/webhooks/gale', express.raw({ type: 'application/json' }), (req, res) => { const parts = (req.headers['x-gale-signature'] || '').split(','); const t = parts.find((p) => p.startsWith('t='))?.slice(2); const sigs = parts.filter((p) => p.startsWith('v1=')).map((p) => p.slice(3)); if (!t || Math.abs(Date.now() / 1000 - Number(t)) > 300) { return res.status(400).send('Stale'); } const expected = crypto .createHmac('sha256', process.env.GALE_WEBHOOK_SECRET) .update(`${t}.${req.body}`) .digest('hex'); const ok = sigs.some((s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)) ); if (!ok) return res.status(401).send('Unauthorized'); res.status(200).send('OK'); // process JSON.parse(req.body) }); ``` ## Retry Schedule If your endpoint doesn't return `200`, Gale retries with increasing delays: | Attempt | Delay after previous failure | | - | - | | 1st retry | 1 minute | | 2nd retry | 5 minutes | | 3rd retry | 30 minutes | | 4th retry | 2 hours | | 5th retry | 6 hours | After all retries are exhausted the delivery is marked as failed. The dashboard lists your endpoints. It does not list deliveries. If you miss an event, poll `GET /api/v2/checkout/{checkout_id}`. ## Webhook Events | Event | When it fires | | - | - | | `order.completed` | Payment captured successfully | | `order.failed` | The order is terminally closed and will not complete | | `payment.failed` | A single payment attempt was declined; the shopper may retry on the same checkout | | `payment_method.saved` | A shopper's card was stored for later charges. See [Saved Payment Methods](/integration/saved-payment-methods) | | `refund.created` | Refund initiated by merchant | | `refund.succeeded` | Refund processed successfully | | `refund.failed` | Refund attempt failed (including failures after submission) | | `dispute.created` | A chargeback was opened against an order — respond before `evidence_due_by` | | `dispute.closed` | The chargeback was resolved (`outcome`: `won` / `lost`) | | `checkout.expired` | A checkout session expired without payment | ## Event Envelope Every event shares the same top-level structure: ```json theme={null} { "id": "evt_01ABC...", "type": "order.completed", "created_at": "2026-03-31T12:00:00Z", "data": { ... } } ``` Use `id` for deduplication — Gale may deliver the same event more than once during retries. ## Event Payload Examples ### order.completed Fires when payment is captured and the order is complete. Use this to trigger fulfillment. ```json theme={null} { "id": "evt_01ABC...", "type": "order.completed", "created_at": "2026-03-31T12:00:00Z", "data": { "id": "ord_01ABC...", "checkout_id": "cs_abc123", "status": "completed", "is_recurring": false, "payment_status": "captured", "amount": 4995, "currency": "usd", "payment_link_id": "pl_abc123", "client_reference_id": "your-order-123", "reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "line_items": [ { "product_id": "PROD-001", "name": "Digital Thermometer", "quantity": 1, "unit_amount": 4995, "amount": 4995, "currency": "usd", "is_recurring": false } ], "created_at": "2026-03-31T12:00:00Z" } } ``` > [!NOTE] > > `payment_link_id` and `client_reference_id` are present for payment link orders. For checkout session orders, `reference_id` is set instead and `payment_link_id` is null. ### order.failed Fires when the order is terminally closed and will not complete. For a declined attempt the shopper can still retry, use `payment.failed`. ```json theme={null} { "id": "evt_01DEF...", "type": "order.failed", "created_at": "2026-03-31T12:01:00Z", "data": { "id": "ord_01DEF...", "checkout_id": "cs_def456", "status": "failed", "is_recurring": false, "payment_status": "failed", "amount": 4995, "currency": "usd", "payment_link_id": "pl_abc123", "client_reference_id": "your-order-123", "reference_id": null, "failure_reason": "Payment declined", "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "created_at": "2026-03-31T12:01:00Z" } } ``` ### payment.failed Fires when a single payment attempt is declined. The shopper may retry on the same checkout, so this is not terminal. `retryable` is `false` for a hard decline. Subscribe to this event to observe declined attempts; use `order.failed` for the terminal outcome. ```json theme={null} { "id": "evt_01GHI...", "type": "payment.failed", "created_at": "2026-03-31T12:01:00Z", "data": { "id": "ord_01DEF...", "checkout_id": "cs_def456", "status": "failed", "payment_status": "failed", "decline_code": "do_not_honor", "decline_reason": "issuer_declined", "decline_severity": "soft", "retryable": true, "failure_reason": "Your card was declined.", "amount": 4995, "currency": "usd", "payment_link_id": null, "client_reference_id": "your-order-123", "reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "created_at": "2026-03-31T12:01:00Z" } } ``` ### payment_method.saved Fires once when a shopper's card is stored on a checkout created with `setup_future_usage`. Store `data.id` against your customer and use it to [charge the card later](/api-reference/endpoint/charge-payment-method). ```json theme={null} { "id": "evt_01ABC...", "type": "payment_method.saved", "created_at": "2026-11-10T21:04:11Z", "data": { "id": "pm_fc61f9c445dd477287c47052087dc91c", "type": "card", "brand": "visa", "last4": "1111", "exp_month": "03", "exp_year": "2030", "usage": "off_session", "status": "active", "checkout_id": "cs_abc123", "customer_email": "jane@example.com", "last_used_at": null, "created_at": "2026-11-10T21:04:11Z", "reference_id": "order-1001", "customer": { "email": "jane@example.com", "name": "Jane Doe" } } } ``` > [!NOTE] > > `order.completed` includes the same object as `data.payment_method` for the order that stored a card and for every order charged to a stored card. `payment.failed` includes it when a charge to a stored card is declined. Other orders are unchanged. ### refund.created Fires when a refund is initiated. A `refund.succeeded` or `refund.failed` will follow. ```json theme={null} { "id": "evt_01GHI...", "type": "refund.created", "created_at": "2026-03-31T13:00:00Z", "data": { "id": "ref_01GHI...", "order_id": "ord_01ABC...", "checkout_id": "cs_abc123", "amount": 4995, "currency": "usd", "reason": "Customer request", "payment_link_id": "pl_abc123", "client_reference_id": "your-order-123", "reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "initiated_at": "2026-03-31T13:00:00Z" } } ``` ### refund.succeeded Fires when the refund is processed. Check `payment_status` to know if the order is fully or partially refunded. ```json theme={null} { "id": "evt_01JKL...", "type": "refund.succeeded", "created_at": "2026-03-31T13:01:00Z", "data": { "id": "ref_01GHI...", "order_id": "ord_01ABC...", "checkout_id": "cs_abc123", "amount": 4995, "currency": "usd", "order_status": "completed", "payment_status": "refunded", "reason": "Customer request", "payment_link_id": "pl_abc123", "client_reference_id": "your-order-123", "reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "refunded_at": "2026-03-31T13:01:00Z" } } ``` `payment_status` will be `refunded` for a full refund or `partially_refunded` if only part of the order was refunded. ### refund.failed Fires when the refund attempt fails. ```json theme={null} { "id": "evt_01MNO...", "type": "refund.failed", "created_at": "2026-03-31T13:02:00Z", "data": { "id": "ref_01GHI...", "order_id": "ord_01ABC...", "checkout_id": "cs_abc123", "amount": 4995, "currency": "usd", "failure_reason": "Processor declined refund", "payment_link_id": "pl_abc123", "client_reference_id": "your-order-123", "reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "failed_at": "2026-03-31T13:02:00Z" } } ``` ### dispute.created Fires when a customer opens a chargeback (dispute) against an order. **Respond before `evidence_due_by`** — missed deadlines are lost disputes. ```json theme={null} { "id": "evt_01PQR...", "type": "dispute.created", "created_at": "2026-03-31T14:00:00Z", "data": { "id": "dp_01STU...", "order_id": "ord_01ABC...", "checkout_id": "cs_abc123", "amount": 4995, "currency": "usd", "reason": "fraudulent", "status": "needs_response", "evidence_due_by": "2026-04-10T00:00:00Z", "payment_link_id": null, "client_reference_id": null, "reference_id": "your-order-123", "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "opened_at": "2026-03-31T14:00:00Z" } } ``` ### dispute.closed Fires when a chargeback is resolved. `outcome` is `won` (funds returned to you), `lost`, or `warning_closed`. ```json theme={null} { "id": "evt_01VWX...", "type": "dispute.closed", "created_at": "2026-04-12T09:00:00Z", "data": { "id": "dp_01STU...", "order_id": "ord_01ABC...", "checkout_id": "cs_abc123", "amount": 4995, "currency": "usd", "reason": "fraudulent", "outcome": "won", "payment_link_id": null, "client_reference_id": null, "reference_id": "your-order-123", "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "closed_at": "2026-04-12T09:00:00Z" } } ``` ### checkout.expired Fires when a checkout session passes its expiry without a completed payment — use it to release held inventory or trigger follow-up. ```json theme={null} { "id": "evt_01YZA...", "type": "checkout.expired", "created_at": "2026-04-01T10:00:00Z", "data": { "checkout_id": "cs_abc123", "reference_id": "your-order-123", "payment_link_id": null, "client_reference_id": null, "customer": { "email": "jane@example.com", "name": "Jane Doe" }, "amount": 4995, "currency": "usd", "created_at": "2026-03-17T10:00:00Z", "expired_at": "2026-04-01T10:00:00Z" } } ``` ## Status Fields ### `status` — Fulfillment status | Value | Meaning | | - | - | | `completed` | Payment captured, ready to fulfill | | `failed` | Payment failed | | `cancelled` | Order cancelled | ### `payment_status` — Payment state | Value | Meaning | | - | - | | `captured` | Payment successfully captured | | `failed` | Payment failed or declined | | `refunded` | Fully refunded | | `partially_refunded` | Partially refunded | ## Best Practices * **Return 200 immediately**, then process the event asynchronously * **Deduplicate using `id`** — Gale may send the same event more than once during retries * **Don't rely on webhooks alone** — use `GET /api/v2/checkout/{checkout_id}` to poll status if a webhook is missed * **Always validate the Bearer token** before processing ## Missed Webhooks — Status Polling If your server was down or a webhook was missed, you can check order status directly: ```bash theme={null} GET /api/v2/checkout/{checkout_id} ``` [See the endpoint reference →](/api-reference/endpoint/get-checkout) ## Related Resources * [Payment Links](/integration/payment-links) * [Order Object](/api-reference/objects/order) * [Get Checkout Status](/api-reference/endpoint/get-checkout) # Payment Links Source: https://docs.withgale.com/documentation/integration/payment-links Learn how to create one-time and recurring payment links from the Gale Dashboard. ## Overview Payment Links allow you to quickly generate a hosted checkout link from the Gale Dashboard. These links can be shared with customers to accept one-time payments or recurring subscription payments. This guide walks you through: * Creating a **one-time** payment link * Creating a **recurring / subscription** payment link *** ## Prerequisites Before creating a payment link, make sure the following requirements are met: 1. **You must have access to the Gale Dashboard.** 2. **Products Available in Gale** * At least one product must be **synced** from your store\ **OR** * A product must be **manually created** from the Gale Dashboard *** ## Creating a One-Time Payment Link Follow these steps to create a one-time payment link: ### Step 1: Navigate to Payment Links * Log in to the **Gale Dashboard** * Go to **Payment Links** * Click **Create Payment Link** ![Screenshot 2026 01 30 At 8 14 42 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.14.42AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=9d0c07b51bf7b50c91fff2bfeab36bcf) *** ### Step 2: Select a Product * In the **Products** section, choose a product from the dropdown * This product will be charged when the payment link is used ![Screenshot 2026 01 30 At 8 15 42 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.15.42AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=2f458fa2c186fb59c7fb22493d6958b4) *** ### Step 3: Configure Additional Charges (Optional) In the **Additional Charges** section, you can optionally add: * **Shipping (Flat Fee)** * **Discount** * **Tax Percentage** ![Screenshot 2026 01 30 At 8 16 17 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.16.17AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=f1070d2afe8a18fdc3d6ded7ca4bedeb) These fields are optional and can be left empty if not required. *** ### Step 4: Add Multiple Shipping Rates (Optional) If you want to offer multiple shipping options: * Add multiple entries under the **Shipping Rates** section * Each rate can have its own label and amount ![Screenshot 2026 01 30 At 8 16 57 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.16.57AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=d289e7e6eb65c1ab90d1fbe687fb45ae) *** ### Step 5: Configure Redirect URLs In the **Redirect URLs** section: * Enter a **Success URL**\ → Customer is redirected here after a successful payment * Enter a **Failure URL**\ → Customer is redirected here if the payment fails or is canceled ![Screenshot 2026 01 30 At 8 17 15 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.17.15AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=ff282b4d7cd4a879fc1a89882c7b2b19) *** ### Step 6: Collect Shipping Information (Optional) * If you need to collect shipping details from the customer, make sure the **Collect Shipping Information** checkbox is checked ![Screenshot 2026 01 30 At 8 18 38 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.18.38AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=8b29692f1138b7f7d6dcc7798dd97c8c) *** ### Step 7: Create the Payment Link * Review all details ![Screenshot 2026 01 30 At 8 19 11 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.19.11AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=63f27ba2154c125caedda6453ab94a9e) * Click **Create Payment Link** * Copy and share the generated payment link with your customer ### Step 8: Client Reference ID (optional) You can simplify reconciliation by appending a `client_reference_id` query parameter to any payment link URL. This is entirely optional — payment links work the same with or without it. When provided, it allows you to associate a payment with a record in your own system, such as a customer ID, order ID, or cart ID. **How it works** After creating a payment link, you can optionally append `client_reference_id` as a query string parameter to the URL: ```text theme={null} https://checkout.withgale.com/payment/pl_M5CS4Y2?client_reference_id={customer_id} ``` If a `client_reference_id` is included: * It will be passed along in the webhook events you receive for that payment. * You can also retrieve the payment status using the `client_reference_id` directly via the API. If omitted, the payment link functions normally without any impact. | Requirements | **Description** | | - | - | | `client_reference_id` | An optional unique string to associate the payment with your internal systems. Must be composed of alphanumeric characters, dashes, or underscores, up to 200 characters in length. | *** ## Creating a Recurring / Subscription Payment Link The process for creating a **recurring (subscription)** payment link is almost identical to a one-time payment link, with one additional step during product selection. ### Follow Steps 1–4 Above * Navigate to **Payment Links** * Click **Create Payment Link** * Select a product * Configure optional charges (shipping, discount, tax) *** ### Enable Recurring Subscription When selecting a product: 1. Enable **Make this a recurring subscription** 2. Choose a **Subscription Interval** (e.g. weekly, monthly, yearly) ![Screenshot 2026 01 30 At 8 19 57 AM](https://mintcdn.com/galepaymentsinc/lL9AlJakuqc8gygO/images/Screenshot2026-01-30at8.19.57AM.png?fit=max\&auto=format\&n=lL9AlJakuqc8gygO\&q=85\&s=d9dcaa39fa3ea6d63c627957fc635f30) *** ### Complete Remaining Steps * Configure **Redirect URLs** * Enable **Collect Shipping Information** if required * Click **Create Payment Link** The generated link will now charge customers on a recurring basis according to the selected interval. *** ## Notes & Best Practices * Ensure redirect URLs are valid and publicly accessible * Use different payment links for different pricing or subscription intervals * Test payment links in a test environment before sharing with customers *** If you have any questions or need help setting up payment links, reach out to the Gale support team. # How Gale Works Source: https://docs.withgale.com/how-it-works Understand the complete Gale Payments flow — from syncing products to completing checkout and fulfilling orders. Gale integrates into your existing checkout flow to help you accept HSA and FSA cards in a compliant, seamless way. We handle product validation, payment authorization, and documentation (like LMNs), all through a secure hosted experience — so you don’t have to. *** ## End-to-End Workflow > [card] 1. Product Sync > > Gale syncs your product catalog and identifies which items are eligible based on your selected product categories. > [card] 2. Payment Method Appears > > A new payment method — “Gale HSA/FSA Payments” — appears on your checkout page when eligible items are in the cart. > [card] 3. Hosted Checkout Page > > Customers who choose Gale are redirected to a secure, Gale-hosted payment page tailored to HSA/FSA compliance. > [card] 4. Auto-Approve or LMN Flow > > If the cart contains SIGIS-eligible items, payment is instantly approved.\ > For dual-purpose products, the customer completes a short medical survey for LMN review. > [card] 5. Return and Fulfill > > Once the flow completes, the customer is redirected back to your store.\ > The order is marked as **paid** and ready to ship — no manual steps needed. *** ## Summary of the Flow > Product Sync → Payment Method Shown → Payment → Order Completed This flow ensures: * Accurate eligibility validation * Secure handling of healthcare-related payments * A smooth, compliant checkout experience for your customers * Minimal operational burden on your side # Checkout (Hosted Page) Source: https://docs.withgale.com/integration/checkout Redirect customers to Gale's hosted checkout page for seamless HSA/FSA payments # Checkout Integration The most common way to integrate Gale. Create a checkout session via API, redirect your customer to Gale's hosted page, and we handle the rest—including card collection, eligibility detection, and LMN flow for dual-purpose products. ## How It Works 1. **Customer clicks** "Checkout" on your site 2. **Your site** creates a checkout session via `POST /api/v2/checkout` 3. **Gale returns** a `checkout_url` 4. **Your site redirects** customer to the checkout URL 5. **Customer completes** payment on Gale's hosted page 6. **Gale sends** webhook with `order.completed` event 7. **Your system** fulfills the order 8. **Customer is redirected** back to your `success_url` ## When to Use Checkout > [!NOTE] > > **Using Shopify or WooCommerce?** Install our plugin instead: > > * [Shopify Plugin](/onboarding/shopify/installation) > * [WooCommerce Plugin](/onboarding/woocommerce/installation) > > The Checkout API is for custom platforms and sites not supported by our plugins. **Perfect for:** * Custom e-commerce platforms * Membership and subscription platforms * SaaS applications * Next.js, React, or custom-built sites * Adding HSA/FSA payments alongside existing payment methods **Use cases:** * Next.js membership site with monthly subscriptions * Custom healthcare e-commerce store * Wellness platform built on custom stack * Telehealth service with custom checkout ## Quick Start ### 1. Create Checkout Session ```javascript theme={null} const createCheckout = async (cart) => { const response = await fetch('https://api.withgale.com/api/v2/checkout', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.GALE_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ reference_id: cart.id, customer: { email: cart.customerEmail, first_name: cart.firstName, last_name: cart.lastName }, line_items: cart.items.map(item => ({ product_id: item.sku, name: item.name, quantity: item.quantity, price: item.price, currency: 'USD' })), shipping_info: cart.shippingAddress, shipping: cart.shipping, tax: cart.tax, success_url: 'https://yoursite.com/order/success', failure_url: 'https://yoursite.com/cart' }) }); const checkout = await response.json(); return checkout.checkout_url; }; ``` ### 2. Redirect Customer ```javascript theme={null} // Redirect to Gale's hosted checkout const checkoutUrl = await createCheckout(cart); window.location.href = checkoutUrl; ``` ### 3. Handle Webhook ```javascript theme={null} app.post('/webhooks/gale', async (req, res) => { const event = req.body; if (event.type === 'order.completed') { const order = event.data; // Fulfill the order await fulfillOrder(order.id, { items: order.line_items, shipping: order.customer.shipping_address }); // Send confirmation email await sendEmail({ to: order.customer.email, subject: `Order ${order.order_number} Confirmed`, template: 'order_confirmation' }); } res.status(200).send('OK'); }); ``` ## Integration Examples ### Next.js Membership Site ```typescript theme={null} // app/checkout/route.ts import { NextResponse } from 'next/server'; export async function POST(request: Request) { const { tier, customerId } = await request.json(); const membershipPlans = { basic: { productId: 'BASIC-001', price: 2900 }, premium: { productId: 'PREMIUM-001', price: 4900 }, elite: { productId: 'ELITE-001', price: 9900 } }; const plan = membershipPlans[tier]; const response = await fetch('https://api.withgale.com/api/v2/checkout', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.GALE_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ customer: await getCustomer(customerId), line_items: [{ product_id: plan.productId, name: `${tier} Membership`, quantity: 1, price: plan.price, currency: 'USD' }], payment_type: 'subscription', subscription: { interval: 'monthly' }, success_url: `${process.env.BASE_URL}/welcome?tier=${tier}`, failure_url: `${process.env.BASE_URL}/pricing` }) }); const checkout = await response.json(); return NextResponse.json({ url: checkout.checkout_url }); } ``` ### React E-commerce Checkout ```jsx theme={null} function CheckoutButton({ cart }) { const handleCheckout = async () => { const response = await fetch('/api/create-checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cart }) }); const { checkout_url } = await response.json(); window.location.href = checkout_url; }; return ( ); } ``` ### Shopify Integration ```javascript theme={null} // Add Gale as payment option const addGalePaymentMethod = () => { // In checkout page const galeButton = document.createElement('button'); galeButton.textContent = 'Pay with HSA/FSA'; galeButton.onclick = async () => { const cart = await fetch('/cart.js').then(r => r.json()); const checkout = await createGaleCheckout({ customer: { email: cart.customer.email, first_name: cart.customer.first_name, last_name: cart.customer.last_name }, line_items: cart.items.map(item => ({ product_id: item.sku, name: item.title, quantity: item.quantity, price: item.price, currency: 'USD' })), success_url: window.location.origin + '/thank-you', failure_url: window.location.origin + '/cart' }); window.location.href = checkout.checkout_url; }; document.querySelector('.payment-methods').appendChild(galeButton); }; ``` ## What Gale Handles When customers reach the hosted checkout page, Gale automatically: 1. **Collects payment information** - Secure card entry 2. **Detects HSA/FSA eligibility** - Real-time SIGIS verification 3. **Handles dual-purpose items** - LMN flow when required 4. **Processes payment** - Charges appropriate payment method(s) 5. **Creates order** - Sends webhook notification to your system ## Checkout URL Customization Pre-fill customer information to streamline checkout: ```javascript theme={null} { customer: { email: "customer@example.com", first_name: "Jane", last_name: "Doe", phone: "+1-555-123-4567" }, shipping_info: { address_line_1: "123 Main St", city: "New York", state: "NY", postal_code: "10001", country: "US" } } ``` Customer only needs to enter payment details. ## Subscription Support For recurring payments, add subscription parameters: ```javascript theme={null} { payment_type: "subscription", subscription: { interval: "monthly", interval_count: 1, trial_period_days: 14 } } ``` ## Charging the Same Card Later To charge a customer again from your own system, for a refill or a renewal you schedule, add `setup_future_usage: "off_session"` to the checkout. The customer agrees on the hosted page, Gale returns a payment method id, and you charge it by API with the customer absent. See [Saved Payment Methods](/integration/saved-payment-methods). ## Testing Use test API keys and test cards: ```javascript theme={null} // Test card numbers const testCards = { success: '4111111111111111', decline: '4000000000000002', requiresAuth: '4000002500003155' }; ``` See [Test Cards](/resources/test-cards) for full list. ## Related Resources * [Checkout API Reference](/api-reference/endpoint/create-checkout-v2) * [Webhooks](/developer-manual/webhooks) * [Order Object](/api-reference/objects/order) ## Support Questions about checkout integration? * 📧 Email: [support@withgale.com](mailto:support@withgale.com) * 💬 [Contact Support](https://www.withgale.com/contact/support) # Custom API Integration Source: https://docs.withgale.com/integration/custom-api Full control over checkout experience with complete API access - perfect for mobile apps and custom platforms # Custom API Integration Build your own checkout experience with complete control using Gale's APIs. Perfect for mobile apps, custom platforms, and merchants who need full flexibility. ## When to Use Custom API > [!TIP] > > Perfect for you if: * You're building a mobile app (iOS, Android, React Native) * You need complete UI control over checkout * You want to manage subscriptions externally * You require advanced features (custom flows, idempotent retries) * You have development resources for custom implementation ## Architecture Overview The custom API integration follows this flow: 1. **Create Products** - Create your products with Gale's Product API. The response includes HSA/FSA eligibility 2. **Create Checkout** - Create checkout session via Checkout API 3. **Redirect/Open** - Send customer to Gale's hosted checkout page 4. **Process Payment** - Gale processes payment securely 5. **Webhook** - Receive webhook notification when payment completes 6. **Fulfill Order** - Your backend fulfills the order ## Implementation Guide ### Step 1: Product Management Create each product with Gale. The `merchant_product_id` is your SKU. Send each SKU once, and store the Gale product `id` from the response, because the API does not look up a product by SKU: ```bash theme={null} POST /api/v2/products ``` ```json theme={null} { "name": "Digital Blood Pressure Monitor", "description": "FDA-approved automatic BP monitor with Bluetooth connectivity and memory storage for tracking health metrics.", "price_cents": 4995, "currency": "USD", "merchant_product_id": "BP-MONITOR-001", "upc_code_or_gtin": "14567890123456", "images": [ "https://yourcdn.com/bp-monitor-front.jpg", "https://yourcdn.com/bp-monitor-side.jpg" ] } ``` **Response includes eligibility:** ```json theme={null} { "success": true, "message": "Product created successfully", "data": { "id": 12345, "name": "Digital Blood Pressure Monitor", "merchant_product_id": "BP-MONITOR-001", "price_cents": 4995, "eligibility": { "hsa_fsa_eligible": true, "eligibility_type": "auto_substantiation", "reason": "SIGIS auto-substantiation", "checked_at": "2026-11-05T12:00:00+00:00" } } } ``` [Create Product API Reference →](/api-reference/endpoint/create-product-v2) ### Step 2: Read Eligibility (Optional) Create returns eligibility, so you do not need a separate eligibility call. To read the current value later, call [Get Product](/api-reference/endpoint/get-product-v2) with the Gale product `id`: ```bash theme={null} GET /api/v2/products/12345 ``` The `eligibility` object in `data` has the same shape as in the create response. Products without a UPC or GTIN, such as prescription items, stay `hsa_fsa_eligible: false` until Gale sets their eligibility. ### Step 3: Create Checkout Session When customer checks out, create a checkout session: ```bash theme={null} POST /api/v2/checkout ``` ```json theme={null} { "reference_id": "mobile-cart-uuid-123", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe", "phone": "+1-555-123-4567" }, "line_items": [ { "product_id": "BP-MONITOR-001", "name": "Digital Blood Pressure Monitor", "quantity": 1, "price": 4995, "currency": "USD" } ], "shipping_info": { "address_line_1": "123 Main St", "address_line_2": "Apt 4B", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "shipping": 995, "tax": 410, "success_url": "myapp://checkout/success", "failure_url": "myapp://checkout/cancel", "metadata": { "platform": "mobile_app" } } ``` **Response:** ```json theme={null} { "success": true, "message": "Checkout created", "data": { "checkout_id": "cs_a1b2c3...", "checkout_url": "https://checkout.withgale.com/checkout/cs_a1b2c3...?token=...", "status": "open", "expires_at": "2026-02-26T14:30:00Z" }, "metadata": { "request_id": "..." } } ``` [Checkout API Reference →](/api-reference/endpoint/create-checkout-v2) ### Step 4: Handle Checkout **Option A: Use Gale's Hosted Checkout (Recommended)** Redirect to `checkout_url` for payment. Customer completes payment on Gale's secure page. **Option B: Embedded Checkout (Alternative)** For a more seamless experience, embed the checkout in a webview or iframe within your app. See [Embedded Checkout Guide](/integration/embedded-checkout). ### Step 5: Handle Payment Confirmation Use webhooks to receive real-time payment confirmation (recommended) or poll the Order API if needed: ```bash theme={null} GET /api/v2/orders/{order_id} ``` **Response:** ```json theme={null} { "id": "ord_abc123", "status": "completed", "customer": { "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe" }, "line_items": [...], "total": 6400, "created_at": "2025-10-18T15:30:00Z" } ``` ### Step 6: Handle Webhooks Configure webhook endpoint to receive real-time updates: ```javascript theme={null} // Node.js/Express example const crypto = require('crypto'); app.post('/webhooks/gale', express.raw({ type: 'application/json' }), async (req, res) => { const parts = (req.headers['x-gale-signature'] || '').split(','); const t = parts.find((p) => p.startsWith('t='))?.slice(2); const sigs = parts.filter((p) => p.startsWith('v1=')).map((p) => p.slice(3)); if (!t || Math.abs(Date.now() / 1000 - Number(t)) > 300) { return res.status(400).send('Stale'); } const expected = crypto .createHmac('sha256', process.env.GALE_WEBHOOK_SECRET) .update(`${t}.${req.body}`) .digest('hex'); const ok = sigs.some( (s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)) ); if (!ok) return res.status(401).send('Unauthorized'); const event = JSON.parse(req.body); switch (event.type) { case 'order.completed': await handleOrderCompleted(event.data); break; case 'order.failed': await handleOrderFailure(event.data); break; case 'refund.succeeded': await handleRefundSucceeded(event.data); break; } res.status(200).send('OK'); }); ``` For the full signing details, see the [Webhook Documentation](/developer-manual/webhooks). Gale also sends `Authorization: Bearer ` on each delivery. That header is deprecated and will be removed, so do not authenticate on it. ## Subscription Support Gale handles subscriptions for you. When creating a checkout session, pass subscription parameters: ```json theme={null} { "reference_id": "sub-vitamins-123", "customer": {...}, "line_items": [{ "product_id": "MONTHLY_VITAMINS", "name": "Monthly Vitamin Subscription", "quantity": 1, "price": 2999, "currency": "USD" }], "payment_type": "subscription", "subscription": { "interval": "monthly", "interval_count": 1, "trial_period_days": 7 } } ``` > [!NOTE] > > Subscription checkout is currently in Beta. Gale will automatically: * Collect payment method * Charge customer monthly * Send webhooks for each payment * Handle failed payments and retries See [Subscription API Reference](/api-reference/endpoint/create-subscription) for more details. ## Advanced Features ### Idempotency Prevent duplicate operations using idempotency keys: ```bash theme={null} POST /api/v2/checkout Idempotency-Key: unique-checkout-12345 ``` ### Rate Limiting See [Rate Limits](/developer-manual/rate-limits) for handling rate limits. ## Best Practices > [card] Secure API Keys > > Never hardcode API keys in mobile apps. Proxy through your backend. > [card] Handle Errors > > Implement proper error handling for all API calls > [card] Use Webhooks > > Don't rely solely on polling - use webhooks for reliability > [card] Cache Eligibility > > Cache product eligibility to reduce API calls ## Error Handling ```javascript theme={null} try { const response = await fetch('https://api.withgale.com/api/v2/checkout', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}` }, body: JSON.stringify(checkoutData) }); if (!response.ok) { const error = await response.json(); switch (error.error.code) { case 'validation_error': // Handle validation errors console.error('Validation failed:', error.errors); break; case 'checkout_expired': // Checkout expired - create new one break; case 'product_not_eligible': // Product not HSA/FSA eligible break; default: console.error('API Error:', error.error.message); } } return response.json(); } catch (error) { console.error('Network error:', error); } ``` ## Testing ### Test Environment Always use test keys during development: ``` Authorization: Bearer glm_test_YOUR_TEST_KEY ``` ### Test Scenarios 1. **Successful payment**: Use test card `4111111111111111` 2. **Card declined**: Use test card `4000000000000002` 3. **Expired session**: Create checkout and wait 24+ hours 4. **Mixed eligibility**: Create checkout with eligible and non-eligible products [See all test cards →](/resources/test-cards) ## API Reference Complete API documentation: * [Product APIs](/api-reference/endpoint/create-product-v2) * [Checkout API](/api-reference/endpoint/create-checkout-v2) * [Order APIs](/api-reference/endpoint/get-order) * [Subscription APIs](/api-reference/endpoint/create-subscription) ## Next Steps > [card] [Webhook Guide](/developer-manual/webhooks) > > Set up webhook endpoints > [card] [Core Objects](/api-reference/objects/order) > > Understand data structures > [card] [Test Cards](/resources/test-cards) > > Test payment scenarios > [card] [Error Codes](/developer-manual/errors) > > Handle errors properly ## Support Building a custom integration? * 📧 Email: [support@withgale.com](mailto:support@withgale.com) * 📚 [Full API Reference](/api-reference/introduction) * 💬 [Contact Support](https://www.withgale.com/contact/support) # Embedded Checkout Source: https://docs.withgale.com/integration/embedded-checkout Keep customers on your site with iframe-embedded checkout - the perfect balance of simplicity and branding # Embedded Checkout Integration Embed Gale's secure checkout directly on your website using an iframe. Customers stay on your domain while Gale handles payment processing, eligibility verification, and compliance. ## When to Use Embedded Checkout > [!TIP] > > Perfect for you if: * You want customers to stay on your website during checkout * You need a branded checkout experience * You're building a platform or multi-tenant solution * You want Gale to handle checkout UI and compliance * You can integrate via API to create checkout sessions ## How It Works 1. **Customer adds items** to cart on your website 2. **Your site** creates a checkout session via `POST /api/v2/checkout` 3. **Gale API returns** a `checkout_url` 4. **Your site embeds** the checkout URL in an iframe 5. **Customer completes** payment in the iframe (stays on your domain) 6. **Gale processes** the payment securely 7. **Gale sends** webhook notification with `order.completed` event 8. **Your site shows** confirmation to customer ## Implementation Steps **1. Create Checkout Session via API** When customer is ready to checkout, create a checkout session with their items **2. Embed the Checkout Iframe** Use the returned `checkout_url` in an iframe on your checkout page **3. Handle Payment Confirmation** Listen for webhooks or postMessage events to confirm payment **4. Fulfill the Order** Process the order and show confirmation to customer ## Step 1: Create Checkout Session Create a checkout session with customer info and line items. > All monetary amounts are integers in cents (e.g., 2995 = \$29.95). ```bash theme={null} POST /api/v2/checkout ``` ```json theme={null} { "customer": { "email": "customer@example.com", "first_name": "Jane", "last_name": "Doe", "phone": "+1-555-123-4567" }, "reference_id": "your-cart-123", "line_items": [ { "product_id": "PROD-001", "name": "Digital Thermometer", "quantity": 1, "price": 2995, "currency": "USD" } ], "shipping_info": { "address_line_1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "shipping": 995, "tax": 245, "success_url": "https://yoursite.com/checkout/success", "failure_url": "https://yoursite.com/checkout/cancel", "metadata": { "platform": "your_platform" } } ``` **Response:** ```json theme={null} { "checkout_id": "checkout_abc123xyz", "checkout_url": "https://checkout.withgale.com/c/checkout_abc123xyz", "status": "open", "expires_at": "2025-10-19T14:30:00Z", "created_at": "2025-10-18T14:30:00Z" } ``` ## Step 2: Embed Checkout Use the `checkout_url` in an iframe on your page: > [tab] HTML > > ```html theme={null} > > > > Checkout - Your Store > > > >
>

Complete Your Purchase

> >
> > > > > ``` > [tab] React > > ```jsx theme={null} > import { useEffect, useState } from 'react'; > > function GaleCheckout({ cartId }) { > const [checkoutUrl, setCheckoutUrl] = useState(null); > > useEffect(() => { > // Create checkout session > const createCheckout = async () => { > const response = await fetch('https://api.withgale.com/api/v2/checkout', { > method: 'POST', > headers: { > 'Authorization': `Bearer ${process.env.GALE_API_KEY}`, > 'Content-Type': 'application/json' > }, > body: JSON.stringify({ > // checkout data > }) > }); > > const { checkout_url } = await response.json(); > setCheckoutUrl(checkout_url); > }; > > createCheckout(); > }, []); > > useEffect(() => { > // Listen for checkout events > const handleMessage = (event) => { > if (event.origin !== 'https://checkout.withgale.com') return; > > if (event.data.type === 'checkout.completed') { > // Handle success > window.location.href = `/success?order=${event.data.order_id}`; > } > }; > > window.addEventListener('message', handleMessage); > return () => window.removeEventListener('message', handleMessage); > }, []); > > if (!checkoutUrl) return
Loading checkout...
; > > return ( >
>

Complete Your Purchase

>