# OnCharge developer documentation (full text) > All OnCharge developer docs in one file, for AI assistants. Source: https://oncharge.io/docs. API spec: https://oncharge.io/openapi.json. Index: https://oncharge.io/llms.txt. --- # OnCharge developer docs OnCharge gives your store a hosted card checkout, risk screening on every payment, dispute tools, and payouts released when the order is delivered. You integrate it with a few signed API calls from your server and either send the shopper to OnCharge's checkout page or embed it in yours. Card details are entered on OnCharge's page and never pass through your servers. ## How it works 1. **Create a checkout session.** When the shopper is ready to pay, your server calls [`POST /api/v1/checkout/sessions`](https://oncharge.io/docs/api#createcheckoutsession) with the amount, your order reference, a return URL and, for goods you ship, the shipping address. The request is [signed](https://oncharge.io/docs/authentication) with your API secret. 2. **Show the checkout.** Redirect the shopper to the session's checkout URL, or embed it in an iframe on your own checkout page. See [Checkout](https://oncharge.io/docs/checkout). 3. **Confirm the payment.** OnCharge sends a signed [webhook](https://oncharge.io/docs/webhooks) (`payment.captured`). Mark the order paid when it arrives. 4. **Ship and report tracking.** Send the carrier and tracking number to [`POST /api/v1/shipments`](https://oncharge.io/docs/shipments). OnCharge follows the package with the carrier. 5. **Get paid.** The order's payout is released 1 day after the carrier confirms delivery to the checkout address. Orders with nothing to ship (digital goods and services) are paid 7 days after payment. See [Shipments & payouts](https://oncharge.io/docs/shipments). ## Choose your integration | You run | Start here | |---|---| | WooCommerce | [WooCommerce plugin](https://oncharge.io/docs/woocommerce): install, paste your keys, done. Shipping and tracking are reported automatically. | | Magento 2 | [Magento 2 module](https://oncharge.io/docs/magento) (beta) | | Wix | [Wix integration](https://oncharge.io/docs/wix) (beta) | | Next.js | [Next.js guide](https://oncharge.io/docs/nextjs) | | React single-page app | [React guide](https://oncharge.io/docs/react) | | Any site with a server (PHP, Node, Python, …) | [HTML & iframe guide](https://oncharge.io/docs/html) | | Custom or headless commerce | [Custom & headless guide](https://oncharge.io/docs/headless) | | An AI coding assistant | [Build with AI](https://oncharge.io/docs/ai): prompts, a Claude skill, a custom GPT and an MCP server | New to OnCharge? Follow the [Quickstart](https://oncharge.io/docs/quickstart) first. ## Key concepts **Store.** Each store has its own API keys, registered domains and webhook endpoint. Create stores and keys in the merchant portal at [app.oncharge.io](https://app.oncharge.io). **Server-side only.** API requests are signed with your API secret, so they must come from your server. The browser only ever receives a checkout URL. **Amounts** are integers in the currency's minor unit: `4900` is $49.00. Currencies are ISO 4217 codes such as `USD`. **Registered domains.** The `return_url` must be on one of the store's registered domains, and only pages on those domains may embed the checkout. **Session statuses.** | Status | Meaning | |---|---| | `created` | Waiting for the shopper. | | `pending` | The shopper has to complete an extra step. | | `authorized` | Approved but not yet captured. | | `captured` | Paid. | | `refused` | Declined. | | `cancelled` | Cancelled before capture. | | `error` | The payment could not be completed. | | `expired` | Not paid within 30 minutes. | ## Resources - [API reference](https://oncharge.io/docs/api) and the [OpenAPI 3.1 spec](https://oncharge.io/openapi.json) - [SDKs](https://oncharge.io/docs/sdks): `@oncharge/node` for your server, `@oncharge/js` for the browser - [`llms.txt`](https://oncharge.io/llms.txt) and [`llms-full.txt`](https://oncharge.io/llms-full.txt) for AI assistants - [Testing & going live](https://oncharge.io/docs/testing) - Questions: [contact OnCharge](https://oncharge.io/contact) --- # Quickstart This walks through one complete payment: create a checkout session on your server, show the checkout, confirm the payment with a webhook, and report the shipment so the order is paid out. It uses Node.js; every step links to the equivalent in other languages. ## Before you start You need: - An approved OnCharge merchant account and an **active** store in the [merchant portal](https://app.oncharge.io). A newly approved store is `pending` until OnCharge has opened its processing account; its API keys are refused (`403 store_inactive`) until then. - The store's **API key** and **API secret**, generated on the store in the portal's **Stores** page (the secret is shown once). - Your store's domain registered under **Security → Domains** (for example `shop.example.com`). - A webhook endpoint URL registered for the store, and its **webhook signing secret**. Put the secrets in your server environment, never in browser code: ```bash title=".env" ONCHARGE_API_KEY=oc_key_... ONCHARGE_API_SECRET=oc_sec_... ONCHARGE_WEBHOOK_SECRET=oc_cbsec_... ``` ## 1. Install the SDK ```bash npm install @oncharge/node ``` > **Coming soon.** `@oncharge/node` is not yet published to npm. Until it is, copy the `onchargeRequest()` helper from [Authentication & signing](https://oncharge.io/docs/authentication#nodejs) (about 30 lines, no dependencies); the request bodies below are the same. ```ts title="lib/oncharge.ts" import { OnCharge } from '@oncharge/node'; export const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_API_KEY!, apiSecret: process.env.ONCHARGE_API_SECRET!, }); ``` ## 2. Create a checkout session Create the session on your server when the shopper clicks **Pay**. Use your order ID as the idempotency key so a retry never creates a second session. ```ts title="server: create the session" const session = await oncharge.checkout.sessions.create( { amount: 4900, // $49.00, in cents currency: 'USD', reference: 'order-1001', order_id: '1001', return_url: 'https://shop.example.com/checkout/complete?order=1001', customer_email: 'shopper@example.com', shipping: { name: 'Alex Rivera', line1: '500 Market St', city: 'San Francisco', state: 'CA', postal_code: '94105', country: 'US', }, }, { idempotencyKey: 'order-1001' }, ); // session.checkout_url is the full URL of the hosted checkout page. ``` Without the SDK: `onchargeRequest('POST', '/api/v1/checkout/sessions', body, { idempotencyKey })` returns `iframe_url`, a path; the checkout URL is `https://app.oncharge.io` + `iframe_url`. Send `shipping` for anything you ship: OnCharge releases the payout once the carrier confirms delivery to this address, and it cannot be changed later. ## 3. Show the checkout Either redirect the shopper: ```ts title="server: redirect" return Response.redirect(session.checkout_url, 303); ``` or embed it on your checkout page with the script tag: ```html title="checkout page"
``` See [Checkout](https://oncharge.io/docs/checkout) for React, Next.js and plain-iframe options. ## 4. Confirm the payment with a webhook ```ts title="app/api/webhooks/oncharge/route.ts (Next.js)" import { createWebhookHandler } from '@oncharge/node/next'; export const { POST } = createWebhookHandler({ secret: process.env.ONCHARGE_WEBHOOK_SECRET!, async onEvent(event) { switch (event.type) { case 'payment.captured': await markOrderPaid(event.data.order_id, event.data.session_id); break; case 'payment.refused': case 'payment.cancelled': await markOrderFailed(event.data.order_id); break; } }, }); ``` Other frameworks and languages: [Webhooks](https://oncharge.io/docs/webhooks). The handler verifies `OnCharge-Signature`, answers `400` to bad signatures, skips repeated event IDs, and answers `500` if `onEvent` throws so OnCharge retries later. On your `return_url` page, show "thank you" but treat the order as paid only after the webhook arrives, or check the session yourself ([`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession)): ```ts const current = await oncharge.checkout.sessions.retrieve(sessionId); if (current.status === 'captured') { // paid } ``` ## 5. Report the shipment When the order ships, send the carrier and tracking number: ```ts await oncharge.shipments.report({ session_id: session.session_id, shipments: [{ carrier: 'UPS', tracking_number: '1Z999AA10123456784' }], }); ``` OnCharge follows the package with the carrier. One day after it is confirmed delivered to the order's shipping address, the payout for the order is released. Check progress any time with `oncharge.shipments.get(sessionId)`. See [Shipments & payouts](https://oncharge.io/docs/shipments). ## 6. Refund (when needed) ```ts await oncharge.refunds.create({ session_id: session.session_id, amount: 1500, currency: 'USD', reference: 'refund-1001-1' }); ``` ## Next steps - [Testing & going live](https://oncharge.io/docs/testing): the launch checklist. - [API reference](https://oncharge.io/docs/api): every endpoint and error code. - [Build with AI](https://oncharge.io/docs/ai): have Claude, ChatGPT or Cursor write the integration for your stack. --- # Authentication & signing Every OnCharge API request is signed on your server with your store's API secret. OnCharge never accepts a bare API key, and the secret never travels over the network. > **Server-side only.** Never put your API secret in browser code, a mobile app, a public repository or a client-side environment variable (anything prefixed `NEXT_PUBLIC_`, `VITE_`, `REACT_APP_` and so on). The browser only ever receives the checkout URL. ## Your credentials | Credential | Looks like | Where it is used | |---|---|---| | API key | `oc_key_…` | Sent in the `X-Oncharge-Key` header. Identifies your store. | | API secret | `oc_sec_…` | Never sent. Used to compute the request signature. | | Webhook signing secret | `oc_cbsec_…` | Verifies webhooks OnCharge sends you. See [Webhooks](https://oncharge.io/docs/webhooks). | | Store ID | a UUID | Only the WooCommerce plugin asks for it. | Generate API credentials for a store on the **Stores** page of the merchant portal at [app.oncharge.io](https://app.oncharge.io). The secret is shown **once**; store it in your secret manager or server environment, for example: ```bash title=".env (server only)" ONCHARGE_API_KEY=oc_key_... ONCHARGE_API_SECRET=oc_sec_... ONCHARGE_BASE_URL=https://app.oncharge.io ``` **New stores.** A store's keys are issued when it is approved, but the store stays `pending` until OnCharge has opened its processing account. Until it is active, every request with its keys fails with `403 store_inactive`; keep the keys and retry later, nothing needs to be regenerated. **Rotating keys.** Rotating a store's keys in the portal issues a new key and secret and keeps the old pair working for a 14-day grace window, so you can deploy the new pair without downtime. Regenerating keys instead revokes every old key immediately; use that if a secret leaked. ## Base URL ```text https://app.oncharge.io ``` All endpoints live under `/api/v1/`. See the [API reference](https://oncharge.io/docs/api) or download the [OpenAPI 3.1 spec](https://oncharge.io/openapi.json). ## How to sign a request Each request carries three headers: | Header | Value | |---|---| | `X-Oncharge-Key` | Your API key. | | `X-Oncharge-Timestamp` | The current Unix time in seconds, e.g. `1767225600`. | | `X-Oncharge-Signature` | The signature computed below, lower-case hex. | Compute the signature in four steps: 1. **Body hash.** `body_hash = hex(sha256(raw_body))`, where `raw_body` is the exact bytes you send. For `GET` requests and for `POST` requests without a body, hash the empty string (`e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`). 2. **Signing string.** `signing_string = "{timestamp}.{METHOD}.{path}.{body_hash}"`. `{timestamp}` is the exact string you put in `X-Oncharge-Timestamp`; `{METHOD}` is upper case; `{path}` is the URL path **without the query string**, for example `/api/v1/shipments` for `GET /api/v1/shipments?session_id=…`. 3. **Signing key.** `signing_key = hex(sha256(api_secret))`: the 64-character lower-case hex digest of your API secret, used as an ASCII string. Do not decode it back to bytes. 4. **Signature.** `X-Oncharge-Signature = hex(hmac_sha256(signing_key, signing_string))`. OnCharge rejects a request when the timestamp is more than **300 seconds** away from its clock, so keep your server's clock synced (NTP). > **Serialize once.** Hash and send the same string. If you sign `JSON.stringify(body)` and then let your HTTP client serialize the object again, whitespace or key order can differ and the signature will not match. ### Test vector Use this to check your implementation without calling the API: | Input | Value | |---|---| | API secret | `oc_sec_example_secret_do_not_use` | | Timestamp | `1767225600` | | Method and path | `POST /api/v1/checkout/sessions` | | Body | `{"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"}` | | Body hash | `5e52ceb9b1f344953c18661d556985d8cc6da177161aae0192a494cad909077b` | | Signing key | `da99cc22bdd7ff7663935ccc2966a363e9b0fe1c4fc4b9803c7469ef2de84d54` | | Signing string | `1767225600.POST./api/v1/checkout/sessions.5e52ceb9b1f344953c18661d556985d8cc6da177161aae0192a494cad909077b` | | Signature | `7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7` | A `GET /api/v1/shipments?session_id=…` with the same secret and timestamp signs `1767225600.GET./api/v1/shipments.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` and gives `e03651b9e5bf9da64bacc56efcc7e0c11471e2942fede23c61141434528c4a6f`. ## Examples Each example reads `ONCHARGE_API_KEY`, `ONCHARGE_API_SECRET` and (optionally) `ONCHARGE_BASE_URL` from the environment, creates a checkout session and then reads the order's delivery status with a query-string request. They use only each language's standard library, and each one has been run against a reimplementation of OnCharge's server-side signature check. ### curl ```bash title="oncharge.sh" test="sign-curl" #!/usr/bin/env bash # Usage: oncharge METHOD PATH [JSON_BODY] set -euo pipefail oncharge() { local method="$1" path="$2" body="${3:-}" local base="${ONCHARGE_BASE_URL:-https://app.oncharge.io}" local ts body_hash signing_key signature ts="$(date +%s)" body_hash="$(printf '%s' "$body" | openssl dgst -sha256 -hex | awk '{print $NF}')" signing_key="$(printf '%s' "$ONCHARGE_API_SECRET" | openssl dgst -sha256 -hex | awk '{print $NF}')" # Sign the path without the query string. signature="$(printf '%s' "$ts.$method.${path%%\?*}.$body_hash" \ | openssl dgst -sha256 -hmac "$signing_key" -hex | awk '{print $NF}')" local args=(-sS -X "$method" "$base$path" -H "Content-Type: application/json" -H "X-Oncharge-Key: $ONCHARGE_API_KEY" -H "X-Oncharge-Timestamp: $ts" -H "X-Oncharge-Signature: $signature") if [ -n "$body" ]; then args+=(--data-raw "$body"); fi curl "${args[@]}" } oncharge POST /api/v1/checkout/sessions \ '{"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"}' echo oncharge GET "/api/v1/shipments?session_id=8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11" echo ``` ### Node.js Node 18 or later (uses the built-in `fetch`). With the [Node SDK](https://oncharge.io/docs/sdks) you do not need this code. ```js title="oncharge.mjs" test="sign-node" import { createHash, createHmac } from 'node:crypto'; const BASE_URL = process.env.ONCHARGE_BASE_URL ?? 'https://app.oncharge.io'; const sha256Hex = (value) => createHash('sha256').update(value, 'utf8').digest('hex'); export async function onchargeRequest(method, path, body, { idempotencyKey } = {}) { const rawBody = body === undefined ? '' : JSON.stringify(body); const timestamp = Math.floor(Date.now() / 1000).toString(); const url = new URL(path, BASE_URL); // Sign the path without the query string. const signingString = `${timestamp}.${method.toUpperCase()}.${url.pathname}.${sha256Hex(rawBody)}`; const signature = createHmac('sha256', sha256Hex(process.env.ONCHARGE_API_SECRET)) .update(signingString, 'utf8') .digest('hex'); const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json', 'X-Oncharge-Key': process.env.ONCHARGE_API_KEY, 'X-Oncharge-Timestamp': timestamp, 'X-Oncharge-Signature': signature, ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}), }, body: rawBody === '' ? undefined : rawBody, // send exactly the bytes you hashed }); const data = await res.json(); if (!res.ok) { throw Object.assign(new Error(data.message ?? `HTTP ${res.status}`), { status: res.status, code: data.error }); } return data; } const session = await onchargeRequest( 'POST', '/api/v1/checkout/sessions', { amount: 4900, currency: 'USD', reference: 'order-1001', return_url: 'https://shop.example.com/thanks' }, { idempotencyKey: 'order-1001' }, ); console.log(session.session_id, new URL(session.iframe_url, BASE_URL).href); const delivery = await onchargeRequest('GET', `/api/v1/shipments?session_id=${session.session_id}`); console.log(delivery.delivery.state); ``` ### PHP PHP 7.4 or later with the `curl` extension. ```php title="oncharge.php" test="sign-php" strtoupper($method), CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); if ($rawBody !== '') { curl_setopt($ch, CURLOPT_POSTFIELDS, $rawBody); // send exactly the bytes you hashed } $response = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($response === false) { throw new RuntimeException('OnCharge request failed: ' . curl_error($ch)); } $data = json_decode($response, true) ?? []; if ($status >= 400) { throw new RuntimeException(($data['error'] ?? 'http_error') . ': ' . ($data['message'] ?? "HTTP $status")); } return $data; } $session = oncharge_request('POST', '/api/v1/checkout/sessions', [ 'amount' => 4900, 'currency' => 'USD', 'reference' => 'order-1001', 'return_url' => 'https://shop.example.com/thanks', ], 'order-1001'); echo $session['session_id'], ' ', $session['iframe_url'], PHP_EOL; $delivery = oncharge_request('GET', '/api/v1/shipments?session_id=' . urlencode($session['session_id'])); echo $delivery['delivery']['state'], PHP_EOL; ``` ### Python Python 3.8 or later, standard library only. ```python title="oncharge.py" test="sign-python" import hashlib import hmac import json import os import time import urllib.error import urllib.request from urllib.parse import urlsplit BASE_URL = os.environ.get("ONCHARGE_BASE_URL", "https://app.oncharge.io") def oncharge_request(method, path, body=None, idempotency_key=None): raw_body = "" if body is None else json.dumps(body, separators=(",", ":")) timestamp = str(int(time.time())) # Sign the path without the query string. body_hash = hashlib.sha256(raw_body.encode("utf-8")).hexdigest() signing_string = f"{timestamp}.{method.upper()}.{urlsplit(path).path}.{body_hash}" signing_key = hashlib.sha256(os.environ["ONCHARGE_API_SECRET"].encode("utf-8")).hexdigest() signature = hmac.new(signing_key.encode("ascii"), signing_string.encode("utf-8"), hashlib.sha256).hexdigest() headers = { "Content-Type": "application/json", "User-Agent": "my-store/1.0", "X-Oncharge-Key": os.environ["ONCHARGE_API_KEY"], "X-Oncharge-Timestamp": timestamp, "X-Oncharge-Signature": signature, } if idempotency_key: headers["Idempotency-Key"] = idempotency_key request = urllib.request.Request( BASE_URL + path, data=raw_body.encode("utf-8") if raw_body else None, # send exactly the bytes you hashed headers=headers, method=method.upper(), ) try: with urllib.request.urlopen(request, timeout=30) as response: return json.loads(response.read()) except urllib.error.HTTPError as err: payload = json.loads(err.read() or b"{}") raise RuntimeError(f"{payload.get('error')}: {payload.get('message')}") from None session = oncharge_request( "POST", "/api/v1/checkout/sessions", {"amount": 4900, "currency": "USD", "reference": "order-1001", "return_url": "https://shop.example.com/thanks"}, idempotency_key="order-1001", ) print(session["session_id"], session["iframe_url"]) delivery = oncharge_request("GET", f"/api/v1/shipments?session_id={session['session_id']}") print(delivery["delivery"]["state"]) ``` ## Idempotency Send an `Idempotency-Key` header on requests that create something, so a retry after a timeout cannot create it twice: - **`POST /api/v1/checkout/sessions`**: while a session created with the same key is still open (`created` or `pending`) and less than 50 minutes old, OnCharge returns that session (HTTP 200) instead of creating a new one. Use your order or cart ID. - **`POST /api/v1/refunds`**: a repeat with the same key returns the first refund with `"idempotent": true`. Use your refund ID. - **`POST /api/v1/checkout/sessions/{id}/cancel`**: the key is passed along so a retried cancellation is not applied twice. The key is part of the headers, not the signature. ## Store domains Register every domain your store runs on (for example `shop.example.com` and `www.shop.example.com`) for the store under **Security → Domains** in the merchant portal. OnCharge uses the list three ways: - `return_url` must be on a registered domain, or session creation fails with `invalid_return_url`. - The checkout may only be framed by pages on a registered domain (over HTTPS; a registered `localhost` works from any port). - If an API request carries an `Origin`, `Referer` or `X-Store-Domain` header, at least one must match a registered domain, or it fails with `domain_mismatch`. Server-to-server calls normally send none of these; you may send `X-Store-Domain: shop.example.com` to make the origin explicit. ## Rate limits Requests are rate-limited per store. A limited request gets `429 rate_limited` with `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (Unix seconds) headers. Wait until the reset time, then retry with the same `Idempotency-Key`. ## Errors Errors are JSON with a stable `error` code and a human-readable `message`: ```json { "error": "invalid_signature", "message": "HMAC signature verification failed" } ``` | Status | `error` | What to check | |---|---|---| | 401 | `missing_auth` | All three `X-Oncharge-*` headers are present. | | 401 | `invalid_timestamp` | The timestamp is an integer number of seconds (not milliseconds). | | 401 | `timestamp_expired` | Your server clock is within 300 seconds of real time. | | 401 | `invalid_key` | The API key is correct and has not been revoked or rotated out. | | 401 | `invalid_signature` | Signing key is `sha256(secret)` as hex text; path has no query string; body hash is of the exact bytes sent; method is upper case; timestamp string matches the header. | | 403 | `store_inactive` | The store is active in the portal. A newly approved store is `pending` until OnCharge has opened its processing account, and its keys are refused until then; a suspended store is refused too. | | 403 | `store_checkout_closed` | Only on session creation: OnCharge has closed the store to new payments (for example while the account is being offboarded). Shipments, refunds and other calls still work. | | 403 | `domain_mismatch` | `Origin`/`Referer`/`X-Store-Domain` is a registered store domain. | | 429 | `rate_limited` | Back off until `X-RateLimit-Reset`. | | 503 | `service_unavailable`, `config_error` | Temporary. Retry with backoff. | Each endpoint's own errors are listed in the [API reference](https://oncharge.io/docs/api). --- # Testing & going live OnCharge does not currently offer a self-serve sandbox account. Test the parts you build against the published test vectors and local fixtures, then confirm the whole flow with a small live payment that you refund. If you need a separate test configuration for your store, ask your OnCharge contact before launch. ## 1. Request signing Check your signing code against the [test vector](https://oncharge.io/docs/authentication#test-vector) before calling the API: with secret `oc_sec_example_secret_do_not_use` and timestamp `1767225600`, a `POST /api/v1/checkout/sessions` with the sample body must produce `7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7`. Then make one real request with your keys. A wrong signature fails with `401 invalid_signature` before anything is created, so this is safe. Common causes are listed under [Errors](https://oncharge.io/docs/authentication#errors). ## 2. Webhooks - Unit-test your verifier with the [webhook test vector](https://oncharge.io/docs/webhooks#verify-the-signature) (allow a large tolerance, because its timestamp is in the past). - Sign your own fixtures to test your handler end to end. With Node: ```js title="send-test-webhook.mjs" import { createHmac } from 'node:crypto'; const secret = process.env.ONCHARGE_WEBHOOK_SECRET; const body = JSON.stringify({ id: `evt_test_${Date.now()}`, type: 'payment.captured', created: Math.floor(Date.now() / 1000), livemode: false, data: { session_id: '8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11', order_id: '1001', reference: 'order-1001', amount: 4900, currency: 'USD', status: 'captured' }, }); const t = Math.floor(Date.now() / 1000); const v1 = createHmac('sha256', secret).update(`${t}.${body}`).digest('hex'); const res = await fetch('http://localhost:3000/api/webhooks/oncharge', { method: 'POST', headers: { 'Content-Type': 'application/json', 'OnCharge-Event-Id': JSON.parse(body).id, 'OnCharge-Signature': `t=${t},v1=${v1}` }, body, }); console.log(res.status); ``` With the Node SDK, `OnCharge.webhooks.generateTestHeader({ payload: body, secret })` builds the same header. - Send the same event twice and check that the second is ignored. - Send a tampered body and check that you respond `400`. ## 3. Checkout display - The page that shows the checkout must be on a registered store domain and served over HTTPS. Staging domains must be registered too. - If you use a Content Security Policy, allow `frame-src https://app.oncharge.io` (and `script-src` for the hosted script). - For local development, register `localhost` as a domain: a registered `localhost` may frame the checkout from any port. Remove it before launch if you do not need it. - Test on a phone: the iframe should resize to its content, and nothing on your page should cover it. - Create a session, wait 30 minutes and reload: you should create a fresh session instead of showing an expired one. ## 4. Shipments - Report a tracking number for an unpaid session: expect `409 order_not_paid`. - Report an invalid number: expect `"status": "rejected"` with `tracking_number_invalid`. - After your live test payment, report a real tracking number and check `GET /api/v1/shipments?session_id=…` shows `in_transit`. ## 5. A live end-to-end payment 1. Create a low-value order on your production store and pay with a real card. 2. Confirm the `payment.captured` webhook marked the order paid, and that the shopper landed on your `return_url`. 3. Refund it with `POST /api/v1/refunds` (with an `Idempotency-Key`) and confirm the `refund.succeeded` webhook. ## Go-live checklist - [ ] API secret and webhook secret are stored server-side only (not in the browser bundle, not in the repository). - [ ] Every production domain (with and without `www`) is registered for the store. - [ ] Sessions are created on the server with an `Idempotency-Key` per order or cart. - [ ] `shipping` is sent for every order that ships. - [ ] Orders are marked paid from the webhook or a server-side status check, never from the browser. - [ ] The webhook endpoint verifies `OnCharge-Signature`, deduplicates on the event ID and answers within 10 seconds. - [ ] Tracking numbers are reported for every shipped order (USPS, UPS, FedEx or DHL Express). - [ ] Refunds send an `Idempotency-Key`. - [ ] Server clock is synced (requests are rejected more than 300 seconds off). - [ ] RUO stores only: the compliance feed is connected and verified in the portal, and a reviewer login is set up. --- # Checkout The shopper pays on OnCharge's checkout page. Your server creates a **checkout session**, and you show the session's checkout page in one of five ways: | Option | Best for | |---|---| | [Hosted redirect](#hosted-redirect) | The fastest integration. Works everywhere, including in-app browsers. | | [Embedded iframe](#embedded-iframe) | Keeping the shopper on your checkout page, with no JavaScript library. | | [Script tag](#script-tag) | Embedding on any site with automatic resizing and events. | | [React component](#react) | React apps. | | [Next.js](#nextjs) | Next.js App Router stores. | Whichever you choose, the payment is confirmed on your server by a [webhook](https://oncharge.io/docs/webhooks), never by the browser. ## Create a checkout session Call [`POST /api/v1/checkout/sessions`](https://oncharge.io/docs/api#createcheckoutsession) from your server (see [Authentication](https://oncharge.io/docs/authentication) for signing). | Field | Required | Notes | |---|---|---| | `amount` | Yes | Integer in minor units (`4900` = $49.00). | | `currency` | Yes | ISO 4217 code, e.g. `USD`. | | `reference` | Yes | Your order number or cart ID, up to 255 characters. Returned in webhooks. | | `return_url` | Yes | Where the shopper goes after checkout. Must be on a registered store domain. | | `order_id` | No | Your order ID if the order already exists. Otherwise [attach it later](#create-the-session-before-the-order-exists). | | `customer_email`, `customer_phone` | No | Used for fraud screening and receipts. Phone in E.164 (`+15551234567`). | | `shipping` | For physical goods | `name`, `line1`, `line2`, `city`, `state`, `postal_code`, `country`. The payout is released after the carrier confirms delivery to this address. It cannot be changed later. | | `line_items` | No | `[{ description, quantity, amount_including_tax }]`. | | `metadata` | No | Your own key-value data. | Send an `Idempotency-Key` header (your order or cart ID) so retries return the same open session. If OnCharge has closed your store to new payments (for example while the account is being offboarded), session creation fails with `403 store_checkout_closed` and sessions that are already open can no longer be paid; the checkout shows the shopper an error. The rest of the API keeps working, so you can still report shipments and refund paid orders. ```json title="201 Created" { "session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11", "status": "created", "iframe_url": "/checkout/8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11?token=pt_eyJ…", "pay_token": "pt_eyJ…", "created_at": "2026-01-01T00:00:00.000Z", "expires_at": "2026-01-01T00:30:00.000Z" } ``` `iframe_url` is a path. The **checkout URL** is `https://app.oncharge.io` followed by `iframe_url`; the Node SDK returns it ready-made as `checkout_url`, and `@oncharge/js` accepts either. It already contains the short-lived `pay_token`, so pass it to the browser as-is and create a new session if the shopper comes back after 30 minutes. ## Hosted redirect Send the shopper to the checkout URL with a `303` redirect (or a link). They pay on OnCharge's page and are returned to your `return_url`. ```ts title="server" const session = await oncharge.checkout.sessions.create(params, { idempotencyKey: order.id }); return Response.redirect(session.checkout_url, 303); ``` ```php title="PHP" $session = oncharge_request('POST', '/api/v1/checkout/sessions', $params, $orderId); header('Location: https://app.oncharge.io' . $session['iframe_url'], true, 303); exit; ``` On the `return_url` page, look the order up on your server. Do not mark it paid because the shopper arrived there; wait for the `payment.captured` webhook or check [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession). ## Embedded iframe Put the checkout in an iframe on a page served from one of your store's registered domains (merchant portal → **Security → Domains**). The checkout's `Content-Security-Policy: frame-ancestors` lists exactly those domains over HTTPS; any other page, and any request whose token or session cannot be resolved, is refused (`frame-ancestors 'none'`). A registered `localhost` may frame the checkout from any port for local development. Full-page use is never affected. Add three query parameters to the checkout URL when you embed it: | Parameter | Value | |---|---| | `embed` | `1`. The checkout shows its own pay button, and links that would leave the frame become `redirect` messages. | | `parent_origin` | Your page's origin, e.g. `https://shop.example.com`. Messages are only addressed to it if it is one of your store's origins. | | `embed_nonce` | A fresh random value per page load, 16–128 characters of `A-Z a-z 0-9 _ -`. Every message echoes it. | ```html title="checkout.html" ``` ### Messages from the checkout The checkout posts messages to the parent window, only at your store's own origins (never `*`): ```json { "source": "oncharge-checkout", "version": 1, "type": "complete", "sessionId": "8b0f6f2e-…", "nonce": "`, that takes a payment without a website or a cart. Share it by email, chat or social media, or print its QR code. Customers see your store's name, what they are paying for, and pay by card or crypto, whichever your store has turned on.
Every payment through a link is an ordinary OnCharge checkout session. It shows under **Payments → Transactions**, can be refunded and disputed like any other payment, fires the usual [webhooks](https://oncharge.io/docs/webhooks), and is paid out on the usual terms: goods you ship are paid out once the carrier confirms delivery ([Shipments & payouts](https://oncharge.io/docs/shipments)).
## Make a link
In the dashboard, open **Payments → Payment links** and choose **New link**. Or call [`POST /api/v1/payment-links`](https://oncharge.io/docs/api#createpaymentlink), signed like every merchant API request ([Authentication](https://oncharge.io/docs/authentication)):
```json title="Request"
{
"title": "Consultation deposit",
"amount": 5000,
"currency": "USD",
"collect_phone": true,
"success_url": "https://shop.example.com/thank-you"
}
```
```json title="Response (shortened)"
{
"id": "5f0c9d4e-2a1b-4c3d-9e8f-7a6b5c4d3e2f",
"object": "payment_link",
"code": "k7Hq2mNpR4sT",
"url": "https://app.oncharge.io/l/k7Hq2mNpR4sT",
"title": "Consultation deposit",
"amount_type": "fixed",
"amount": 5000,
"currency": "USD",
"status": "active",
"stats": { "views": 0, "checkouts": 0, "payments": 0, "revenue": 0, "refunded": 0 },
"qr_code": "data:image/svg+xml;base64,…"
}
```
| Field | What it does |
|---|---|
| `title`, `description` | What the customer sees. |
| `amount_type` | `fixed` (default): the customer pays `amount` per item. `customer_chosen`: they enter an amount between `min_amount` and `max_amount` (useful for donations, tips and deposits); `preset_amount` pre-fills it. |
| `currency` | Default `USD`. Card payments are USD only on stores paid out per delivered order. |
| `adjustable_quantity`, `max_quantity` | Let the customer choose how many (up to `max_quantity`, at most 99). |
| `collect_shipping` | Ask for a shipping address. **Required if your store ships what it sells**: the order is paid out once the carrier confirms delivery to that address. |
| `collect_phone` | Ask for a phone number. The customer's email is always asked for. |
| `success_url` | Where a paid customer goes next. It must be `https` on one of your store's registered domains (**Integrations → Domains**). Without it, they see an OnCharge thank-you page. |
| `rails` | `["card"]`, `["crypto"]` or both (default). Your store must have the way to pay turned on. |
| `expires_at` | When the link stops taking payments (at most two years ahead). |
Amounts are in minor units (cents). A link takes payments from 50 cents up to $10,000 each: `amount` × `max_quantity`, or `max_amount`, must stay within $10,000.
With the Node SDK:
```ts
import { OnCharge } from '@oncharge/node';
const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_API_KEY!, apiSecret: process.env.ONCHARGE_API_SECRET! });
const link = await oncharge.paymentLinks.create({ title: 'Tip jar', amount_type: 'customer_chosen', min_amount: 100, max_amount: 50000 });
console.log(link.url);
```
## Track and manage links
- [`GET /api/v1/payment-links`](https://oncharge.io/docs/api#listpaymentlinks) lists your links, newest first (`active`, `limit` and `before` to page), each with `stats`: views, checkouts started, payments, revenue (before refunds) and what was refunded.
- [`GET /api/v1/payment-links/{id}`](https://oncharge.io/docs/api#getpaymentlink) returns one link with its QR code.
- [`POST /api/v1/payment-links/{id}`](https://oncharge.io/docs/api#updatepaymentlink) changes any field, or turns the link off (`"active": false`) and back on (`"active": true`).
- [`POST /api/v1/payment-links/{id}/deactivate`](https://oncharge.io/docs/api#deactivatepaymentlink) turns it off. Its payments stay; a visit says the link is no longer active, and checkouts already started from it can't be completed (a crypto payment whose address was already given out can still finish). The same applies when a link expires or your store is not active.
In the SDK: `paymentLinks.list()`, `retrieve()`, `update()` and `deactivate()`.
## Payments and webhooks
When a customer pays, OnCharge creates a checkout session for the amount × quantity and sends them to OnCharge's hosted checkout. Its webhooks are the ones you already handle (`payment.authorized`, `payment.captured`, `payment.refused`, `refund.*` and `chargeback.*`), with `data.payment_link_id` set to the link's `id` (and `data.reference` to `link_`) so you can tell which link a payment came from. To ship the order, report its tracking number with the event's `session_id` ([Shipments & payouts](https://oncharge.io/docs/shipments)).
## Protection against card testing
Links are public, so OnCharge screens every checkout they start:
- Rate limits per visitor and per link.
- A visitor whose cards are declined several times on a link can't start more checkouts there for a while; a link that sees a run of declines from several visitors pauses itself for a few minutes. One visitor alone can't pause your link for everyone.
- Your [risk policy](https://oncharge.io/docs/risk-engine) runs before the checkout is created (in `enforce` mode a deny refuses it) and again on the checkout page.
- The global ban list applies as on every checkout.
---
# Payment methods
Besides cards, OnCharge checkout can offer shoppers more ways to pay. Each one is off until you turn it on, and each is checked for your business before it appears at checkout.
| Method | How the shopper pays | When it counts as paid | Refunds |
|---|---|---|---|
| **Bank debit (ACH)** | From a US bank account, entered on the checkout page and confirmed with a small test deposit | When the debit clears, up to 4 business days after the shopper confirms their account | Up to 180 days |
| **Cash App Pay** | Scan a QR code, or continue in Cash App on their phone | At once | Up to 90 days |
| **Klarna** | Pay over time, on Klarna's page | At once | Up to 180 days |
| **Affirm** | Pay over time, on Affirm's page (orders of $35 or more) | At once | Up to 120 days |
| **Afterpay** | Pay in 4, on Afterpay's page (orders up to $2,000) | At once | Up to 120 days |
All of them are in US dollars, for US shoppers. Every payment is an ordinary OnCharge checkout session: it shows under **Payments → Transactions**, fires the usual [webhooks](https://oncharge.io/docs/webhooks) and is paid out once the carrier confirms delivery ([Shipments & payouts](https://oncharge.io/docs/shipments)). You are always paid the full order amount; the shopper's instalments are between them and the provider.
## Turn a method on
In the dashboard, open **Settings → Payment setup**. Under **Ways to pay**, each method shows its status in plain words:
- **Off**: choose **Turn on**.
- **Being set up** or **Being reviewed**: the method is checked for your business. It appears at checkout once approved.
- **Needs information**: what is still needed is listed; add it and the review continues.
- **Active**: shoppers see it at checkout.
- **Not available for your business**: pay-later methods are offered to Low Risk stores only, and not for supplements, nutraceuticals, CBD, pharmacy, research chemicals, alcohol or tobacco. Cash App Pay is not offered to pharmacies.
Owners and admins can turn methods on and off. Turning one off removes it from checkout at once.
Read the same list with [`GET /api/v1/payment-methods`](https://oncharge.io/docs/api#listpaymentmethods) or `oncharge.paymentMethods.list()` in the [Node SDK](https://oncharge.io/docs/sdks).
## What it costs
| Method | OnCharge fee |
|---|---|
| Bank debit, Cash App Pay | Your card rate |
| Klarna, Affirm, Afterpay | Your card rate + 3.1 percentage points |
The fee is taken from each payment, as for cards.
## Bank debit (ACH)
1. At checkout the shopper chooses **Bank account**, enters the account holder, routing and account numbers, and authorizes the debit. The account numbers go straight to the payment network; they never reach your site or OnCharge's servers.
2. Within 1–2 business days a $0.01 deposit with a 6-character code starting with **SM** (or two small deposits) appears on their bank statement. OnCharge emails the shopper a link to enter it, and reminds them. They have 10 days; if they do not confirm, nothing is taken.
3. Once confirmed, the debit is sent and takes up to 4 business days to clear.
While it is waiting or being collected, the session's `status` stays `pending` and your webhook receives `payment.pending` with `data.payment_method: "bank_debit"`. **Do not ship until `payment.captured`**: a debit can still fail (for example for insufficient funds), in which case you receive `payment.refused`. [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession) shows where it stands in `settlement`: `verify_deposits`, `processing` or `settled`.
You can cancel a bank debit that has not cleared from the payment's page. It cannot be refunded until it has cleared.
**Payouts.** A shopper can ask their bank to return a debit from a personal account for up to 60 days, and such returns cannot be disputed. So a bank debit is paid out only after it has cleared **and** its return window has passed, on top of confirmed delivery: 14 days for Low Risk stores, 60 days for High Risk stores. If a debit is returned after it was paid out, the amount is taken from your next payout, like a lost chargeback.
## Pay later (Klarna, Affirm, Afterpay)
The shopper chooses the provider's tab in the card form and finishes on the provider's own page, then comes back to your store. The payment is confirmed at once, like a card. Refunds work as for cards, in full or in part, within each provider's window above. A shopper's dispute goes through the provider and can be answered with evidence, as for cards.
## Cash App Pay
On a computer the checkout shows a QR code to scan with the phone's camera; on a phone it opens Cash App. The payment is confirmed as soon as the shopper approves it.
## In webhooks and the API
Every payment event carries `data.payment_method`: `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm` or `afterpay` (`null` for crypto). The checkout session API returns the same `payment_method`, and the **Transactions** list, the activity ledger and reports show the method by name.
---
# Webhooks
OnCharge sends a signed `POST` to your webhook endpoints whenever something happens in your store: a payment succeeds or fails on any rail (card, crypto or Card to Crypto), a refund goes through, a shopper disputes a charge or its evidence is due, the cardholder's bank reports fraud, every package of an order is confirmed delivered, a payout reaches your bank or comes back, or your account needs something. Webhooks are how your store learns that an order is paid. Do not rely on the shopper's browser returning to your site.
## Set up endpoints
1. Create an HTTPS route on your server, for example `https://shop.example.com/webhooks/oncharge`, that accepts `POST` with a JSON body.
2. Add it on the **Webhooks** page of the merchant portal. A store can have up to 16 endpoints (your order system, your accounting, a monitoring tool…). For each one, choose the events it receives (every event, whole groups such as `payout.*`, or single events) and give it a description. An endpoint you added before endpoints had event choices keeps the payment, refund, chargeback and delivery events it received then; add the others on the same page. OnCharge shows each endpoint's **signing secret** (`oc_cbsec_…`) once. Store it as a server-side secret, e.g. `ONCHARGE_WEBHOOK_SECRET`.
3. Verify the signature of every request before you trust it (below), then respond with any `2xx` status within 8 seconds.
Each endpoint has its own secret, which you can rotate, and can be disabled and enabled again: a disabled endpoint is sent nothing. The page also shows every event of the last 30 days, where it went, and lets you send any of them to an endpoint again.
The platform integrations include their own endpoint, so you do not write one: add the URL they give you and paste its signing secret into their settings.
| Platform | Webhook URL to add | Where the secret goes |
|---|---|---|
| WooCommerce (plugin 1.4.0+) | `https:///?wc-api=oncharge_callback` | **Webhook Signing Secret** in the plugin settings |
| Magento 2 (beta) | `https:///oncharge/webhook` | **Callback Signing Secret** in the payment method settings |
| Wix (beta) | `https:///_functions/onchargeWebhook` | `oncharge_webhook_secret` in the Secrets Manager |
## The request
```http
POST /webhooks/oncharge HTTP/1.1
Content-Type: application/json
OnCharge-Event-Id: evt_5f0c2a8e-1b7d-4c39-9e64-2d8f1a7b3c90
OnCharge-Signature: t=1767225600,v1=e6be572e7034db173b697bf2ca8964d5a340767572bf5ddb7b5c7dad8afd1bdb
```
```json title="payment.captured"
{
"id": "evt_5f0c2a8e-1b7d-4c39-9e64-2d8f1a7b3c90",
"type": "payment.captured",
"created": 1767225600,
"livemode": true,
"data": {
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"order_id": "1001",
"reference": "order-1001",
"amount": 4900,
"currency": "USD",
"status": "captured",
"rail": "card",
"payment_reference": "ocpay_8b0f6f2e4d1a4c4e9a526f3e1d2c7b11",
"payment_link_id": null,
"payment_method": "card"
},
"event": "payment.captured",
"status": "captured",
"psp_reference": "ocpay_8b0f6f2e4d1a4c4e9a526f3e1d2c7b11"
}
```
Every event has `id`, `type`, `created`, `livemode` and `data`, and every `data` has `rail`. Payment events from a checkout carry these fields:
| Field | Meaning |
|---|---|
| `id` | Unique event ID, also in the `OnCharge-Event-Id` header. The same on every retry and replay. |
| `type` | One of the event types below. |
| `created` | Unix time the event was created. |
| `livemode` | `false` for events from test payments. |
| `data.session_id` | The checkout session the event is about. |
| `data.order_id` | Your order ID if OnCharge has it (sent at session creation or attached later), else `null`. |
| `data.reference` | The `reference` you sent when creating the session. |
| `data.amount`, `data.currency` | Minor units (cents) and ISO code. For `refund.succeeded`, the total refunded so far. Can be `null` if unknown. |
| `data.status` | The order's payment status after the event (for example `captured`, `refunded`), or `null`. |
| `data.rail` | `card`, `crypto` (a crypto checkout, or a coin paid to your wallet) or `card_to_crypto`. |
| `data.payment_reference` | OnCharge's reference for the payment (`ocpay_…`). |
| `data.payment_link_id` | The [payment link](https://oncharge.io/docs/payment-links) the checkout was made from, or `null`. |
| `data.payment_method` | How the shopper paid: `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm` or `afterpay` ([Payment methods](https://oncharge.io/docs/payment-methods)); `null` for crypto. A `payment.pending` with `bank_debit` is still being collected: ship after `payment.captured`. |
| `data.invoice_id` | Only on a payment for an [invoice](https://oncharge.io/docs/invoices): the invoice's id. The session's `order_id` and `reference` are the invoice number. |
| `event`, `status`, `psp_reference` | Repeats of older fields kept for existing plugins, which store `psp_reference` as the order's transaction ID. A payment made before 2026-12-01 keeps its original value there; from 2026-12-01 on it is the `ocpay_` reference. New code should read `type` and `data`. |
## Payments on every rail
Card checkout, crypto checkout and payments paid straight to your own wallet use the same `payment.*` events. `data.rail` says which:
| `data.rail` | Where the payment came from |
|---|---|
| `card` | Card checkout (any card, Apple Pay, Google Pay). |
| `crypto` | A crypto checkout, or a coin paid straight to your wallet through the [crypto plugin](https://oncharge.io/docs/crypto-plugin) or the [Gateway API](https://oncharge.io/docs/gateway-api). |
| `card_to_crypto` | Card, Cash App or Venmo through the plugin or the Gateway API, paid out to your wallet in USDC. |
A payment paid to your wallet has no checkout session, so its `data` has `session_id: null` and these fields instead:
```json title="payment.captured (Card to Crypto, plugin)"
{
"id": "evt_0a6c3e1b-9d2f-4b7a-8c5e-1f3a5c7e9b2d",
"type": "payment.captured",
"created": 1767225600,
"livemode": true,
"data": {
"payment_id": "3b1d6c2e-7f40-4a8e-9d51-6a2f0c9e1b74",
"payment_reference": "ocpay_3b1d6c2e7f404a8e9d516a2f0c9e1b74",
"session_id": null,
"order_id": "1043",
"reference": null,
"amount": 2500,
"currency": "USD",
"status": "captured",
"rail": "card_to_crypto",
"source": "plugin",
"method": "cashapp",
"coin": "USDC (Polygon)",
"coin_amount": "23.00",
"wallet": "0x2f1c…9a4e",
"payment_tx": null,
"payout_tx": "0x8b3e5d0c4f1a2b6e9d7c3a1f5e8b2d4c6a0e9f1b3d5c7a9e2f4b6d8c0a1e3f41c7"
}
}
```
`source` is `plugin` or `gateway`, `method` is `card`, `cashapp`, `venmo` or `crypto`, `wallet` is your wallet masked, and the transaction hashes are on public chains. Gateway payments also carry `net_coin_amount` (what reached your wallet). The money is already in your wallet: OnCharge holds none of it, and it is never part of a payout.
## Event types
| `type` | When | What to do |
|---|---|---|
| `payment.pending` | The shopper has to complete an extra step; on a gateway wallet, a payment seen on the chain and not confirmed yet. | Nothing yet; wait for the next event. |
| `payment.authorized` | The payment was approved but is not captured yet. | Wait for `payment.captured` before fulfilling. |
| `payment.captured` | The payment succeeded. | Mark the order paid and fulfil it. |
| `payment.under_review` | A payment to your wallet arrived but does not match the order (for example a different amount). | Check it before you ship. `data.reason` says why. |
| `payment.capture_failed` | Capturing an approved payment failed. | Treat the order as unpaid. |
| `payment.refused` | The payment was declined. | Mark the order failed or let the shopper retry. |
| `payment.cancelled` | The payment was cancelled, or the checkout expired. | Release reserved stock. |
| `payment.expired` | The checkout or payment window expired before it was paid. | Release reserved stock. |
| `refund.succeeded` | A refund went through. | Record the refund. `data.amount` is the total refunded. |
| `refund.failed` | A refund could not be completed. | Alert your staff; the money was not returned. |
| `chargeback.opened` | The shopper disputed the payment with their bank. | Flag the order. Its payout is held. Upload evidence through [disputes](https://oncharge.io/docs/api#disputes); depending on your account, you or the OnCharge team submit the response (the dispute's `responded_by`). |
| `dispute.evidence_due` | A dispute needs its evidence by `data.evidence_due_by`. Sent once per dispute and deadline. | Upload what is missing before the date. |
| `chargeback.won` | The dispute was decided in your favour. | Optional: note it on the order. |
| `chargeback.lost` | The dispute was decided in the shopper's favour. | Note it on the order. |
| `fraud_warning.received` | The cardholder's bank reported the payment as fraud. | Do not ship. The payout is on hold, and OnCharge may refund it to stop a dispute. |
| `delivery.confirmed` | Every package of the order was confirmed delivered to the order's address. | Optional: mark the order delivered. The payout is now scheduled. |
| `payout.paid` | A payout reached your bank, or (`data.method` `instant`) your debit card, with `data.fee` taken out. `data.payout_id` is the ID [`GET /api/v1/payouts`](https://oncharge.io/docs/api#listpayouts) lists. | Reconcile it. |
| `payout.failed` | A payout could not be delivered. `data.problem` says why and what happens next. A debit card payout (`data.method` `instant`) that fails goes to your bank with your next payout. | Fix your bank details if asked to. |
| `payout.returned` | Your bank sent a payout back. | Fix your bank details; it is sent again. |
| `account.updated` | What your account can do changed (`data.account`: `status`, `payments_enabled`, `payouts_enabled`, `requirements_due`, `deadline`; `data.changed` lists what changed). | Optional: show it in your tools. |
| `account.requirements_due` | Your account needs more information by `data.deadline`. | Provide it under Settings in the portal. |
| `account.restricted` | Your account stopped taking payments or receiving payouts. `data.reason` says why. | Act on the reason. |
| `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired` | A crypto conversion through the plugin or the Gateway API started or ended (`data.swap_id` is its `ocswp_` reference). | Optional: record it. |
| `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled` | A [subscription](https://oncharge.io/docs/subscriptions) started, changed (`data.change` says what), nears the end of its trial, has a failed payment being retried, paused, resumed or ended. `data` is the subscription. | Keep your records in step: grant or end access, update the customer's account. |
| `subscription.period.paid`, `subscription.period.payment_failed` | A subscription period (or a plan change) was paid, or its charge failed (`data.failure`, `data.next_attempt_at`). Each period's payment also fires the usual `payment.*` events. | On `paid`, ship the period if it ships and report its tracking with `data.session_id`: its payout waits for delivery. |
The first seven in the [webhook contract](https://oncharge.io/docs/api#webhooks) (`payment.pending`, `payment.captured`, `payment.refused`, `payment.cancelled`, `refund.succeeded`, `chargeback.opened`, `delivery.confirmed`) are the ones most stores need. Each event is sent once per change. Acknowledge (`2xx`) any type you do not handle; new types may be added. The [API reference](https://oncharge.io/docs/api#webhooks) has a sample of every event.
## Verify the signature
`OnCharge-Signature` has the form `t=,v1=`:
1. Split the header on `,` and read `t` and every `v1` value.
2. Compute `expected = hex(hmac_sha256(signing_secret, t + "." + raw_body))`, where `raw_body` is the request body **exactly as received** (before any JSON parsing) and the key is your `oc_cbsec_…` secret as-is.
3. Accept the event only if `expected` equals one of the `v1` values (constant-time comparison) and `|now - t| <= 300` seconds.
Test vector: secret `oc_cbsec_example_secret_do_not_use`, `t=1767225600` and the `payment.captured` body above, serialized without whitespace, give `v1=e6be572e7034db173b697bf2ca8964d5a340767572bf5ddb7b5c7dad8afd1bdb`.
> Parse JSON only after verifying. Frameworks that parse the body for you (Express `json()`, Next.js `request.json()`) change the bytes; read the raw body instead.
### Node.js
```js title="verify-webhook.mjs" test="webhook-node"
import { createHmac, timingSafeEqual } from 'node:crypto';
export function verifyOnChargeWebhook(rawBody, signatureHeader, secret, toleranceSeconds = 300) {
let timestamp = null;
const signatures = [];
for (const part of String(signatureHeader ?? '').split(',')) {
const [key, value] = part.trim().split('=', 2);
if (key === 't') timestamp = value;
else if (key === 'v1' && value) signatures.push(value);
}
if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) {
throw new Error('Malformed OnCharge-Signature header');
}
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) {
throw new Error('Webhook timestamp is outside the tolerance');
}
const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`, 'utf8').digest();
const valid = signatures.some((sig) => {
const given = Buffer.from(sig, 'hex');
return given.length === expected.length && timingSafeEqual(given, expected);
});
if (!valid) throw new Error('Invalid webhook signature');
return JSON.parse(rawBody);
}
```
With Express, read the raw body:
```js title="server.mjs"
import express from 'express';
import { verifyOnChargeWebhook } from './verify-webhook.mjs';
const app = express();
app.post('/webhooks/oncharge', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = verifyOnChargeWebhook(req.body.toString('utf8'), req.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET);
} catch {
return res.status(400).send('Invalid signature');
}
if (await alreadyProcessed(event.id)) return res.sendStatus(200);
switch (event.type) {
case 'payment.captured':
await markOrderPaid(event.data.order_id ?? event.data.reference, event.data.session_id);
break;
case 'payment.refused':
case 'payment.cancelled':
await markOrderFailed(event.data.order_id ?? event.data.reference);
break;
case 'refund.succeeded':
await recordRefund(event.data.session_id, event.data.amount);
break;
case 'chargeback.opened':
await flagOrder(event.data.session_id);
break;
}
await rememberProcessed(event.id);
res.sendStatus(200);
});
```
In a Next.js route handler, use `const rawBody = await request.text()` and `request.headers.get('OnCharge-Signature')`. See [Next.js](https://oncharge.io/docs/nextjs) for a complete route, or use the SDK (below).
### PHP
```php title="verify-webhook.php" test="webhook-php"
$tolerance) {
throw new RuntimeException('Webhook timestamp is outside the tolerance');
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) {
return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
}
}
throw new RuntimeException('Invalid webhook signature');
}
```
```php title="webhook.php"
dict:
timestamp, signatures = None, []
for part in (signature_header or "").split(","):
key, _, value = part.strip().partition("=")
if key == "t":
timestamp = value
elif key == "v1" and value:
signatures.append(value)
if not timestamp or not timestamp.isdigit() or not signatures:
raise ValueError("Malformed OnCharge-Signature header")
if abs(time.time() - int(timestamp)) > tolerance:
raise ValueError("Webhook timestamp is outside the tolerance")
expected = hmac.new(secret.encode("utf-8"), timestamp.encode("ascii") + b"." + raw_body, hashlib.sha256).hexdigest()
if not any(hmac.compare_digest(expected, signature) for signature in signatures):
raise ValueError("Invalid webhook signature")
return json.loads(raw_body)
```
With Flask:
```python title="app.py"
import os
from flask import Flask, abort, request
from verify_webhook import verify_oncharge_webhook
app = Flask(__name__)
@app.post("/webhooks/oncharge")
def oncharge_webhook():
try:
event = verify_oncharge_webhook(
request.get_data(), request.headers.get("OnCharge-Signature", ""), os.environ["ONCHARGE_WEBHOOK_SECRET"]
)
except ValueError:
abort(400)
if event["type"] == "payment.captured":
pass # mark the order paid
return "", 200
```
### With the Node SDK
The [Node SDK](https://oncharge.io/docs/sdks) does the verification for you. In a Next.js route handler:
```ts title="app/api/webhooks/oncharge/route.ts"
import { createWebhookHandler } from '@oncharge/node/next';
export const { POST } = createWebhookHandler({
secret: process.env.ONCHARGE_WEBHOOK_SECRET,
async onEvent(event, { request }) {
if (event.type === 'payment.captured') {
// mark the order paid
}
// throw to have OnCharge retry later
},
});
```
The handler answers `400` (with the reason, e.g. `{"error":"signature_mismatch"}`) to a bad signature, `500` if `onEvent` throws (so OnCharge retries), and `200` without calling `onEvent` again for an event ID it has already handled. It remembers event IDs in memory; pass `eventIdStore: { has(id), add(id) }` backed by your database or Redis when you run several instances, or `eventIdStore: false` to handle every delivery. `toleranceSeconds` defaults to 300.
In any other framework:
```ts
import { OnCharge, OnChargeSignatureError } from '@oncharge/node';
try {
const event = OnCharge.webhooks.constructEvent(rawBody, request.headers.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET!);
// handle event
} catch (err) {
if (err instanceof OnChargeSignatureError) {
// err.code: missing_signature | invalid_signature_header | timestamp_outside_tolerance | signature_mismatch | invalid_payload
}
}
```
`OnCharge.webhooks.generateTestHeader({ payload, secret })` returns a valid `OnCharge-Signature` for a payload, for testing your endpoint without OnCharge.
## Delivery and retries
- Respond with any `2xx` within **8 seconds**. Do slow work (emails, ERP sync) after responding or in a queue.
- Any other response, or a timeout, is retried with backoff for up to **24 hours**.
- The same event can arrive more than once. Store processed `OnCharge-Event-Id` values and skip repeats.
- Events can arrive out of order. If you need the current state, read it with [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession).
- Each endpoint gets its own copy of an event, signed with its own secret, and retried on its own. When an endpoint fails, OnCharge waits a few minutes before sending it more, so its events are delayed, not lost.
## Catch up and replay
Every event is kept for **30 days**, exactly as your endpoints received it:
- [`GET /api/v1/events`](https://oncharge.io/docs/api#listevents) lists them newest first (filter by `type`, such as `payment.captured` or `payout.*`, and by day; paged with `next_cursor`).
- [`GET /api/v1/events/{event_id}`](https://oncharge.io/docs/api#getevent) returns one.
- [`POST /api/v1/events/{event_id}/replay`](https://oncharge.io/docs/api#replayevent) with `{ "endpoint_id": "…" }` sends it to one of your endpoints again, with the same `id`, so your duplicate check still works.
They are signed like every other API request ([authentication](https://oncharge.io/docs/authentication)). With the Node SDK: `oncharge.events.list()`, `.retrieve(id)` and `.replay(id, { endpointId })`.
## Legacy signature header
Requests also carry `X-Oncharge-Signature`, a body-only HMAC with the same secret, kept for older WooCommerce plugins. New integrations should verify `OnCharge-Signature`, which also protects against replays. The WooCommerce plugin (1.4.0+), Magento module and Wix integration check `OnCharge-Signature` first and fall back to the legacy header only when the new one is absent.
---
# Shipments & payouts
OnCharge pays you for an order once the shopper has received it. For goods you ship, that means the carrier has confirmed delivery to the address the shopper gave at checkout. Your part is to send that address when the session is created and to report the tracking number when the order ships.
## When orders are paid out
| What the order contains | Payout released |
|---|---|
| Physical goods (shipped) | 1 day after the carrier confirms delivery of every package to the order's shipping address. |
| Digital goods or services (nothing shipped) | 7 days after payment. |
Your account is set up as shipping physical goods, digital goods and services, or both, during onboarding. On an account that sells both, an order with a shipping address is treated as physical and one without as digital. Research-use-only (RUO) stores always ship physical goods.
Refunds reduce the amount paid out for the order. A dispute (chargeback) or a fraud warning from the shopper's bank holds the order's payout until it is resolved. Every account has a reserve: 2.5% of each order's amount, less refunds, is held back and released automatically 180 days after the payout clock starts (confirmed delivery, or payment for orders with nothing to ship).
OnCharge's card fee is set by your monthly card volume: 6.9% under $10,000, 5.9% from $10,000, 4.9% from $100,000 and 3.9% from $250,000 a month, each plus $0.30 per transaction (on US dollar charges; a charge in another currency pays the percentage only). The percentage is on the amount before sales tax. Your rate starts from the monthly volume in your application and is reviewed on the 1st of each month from the live US dollar payments you processed the month before (counted in the month they were captured), less refunds; the new rate applies to payments started from then on, and you are emailed when it changes. Refunds return the fee in proportion.
## 1. Send the shipping address
Include `shipping` when you [create the checkout session](https://oncharge.io/docs/checkout#create-a-checkout-session):
```json
"shipping": {
"name": "Alex Rivera",
"line1": "500 Market St",
"line2": "Suite 200",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
"country": "US"
}
```
OnCharge compares the carrier's delivery location with this address: for US addresses the first five digits of the ZIP code, otherwise the city and state. Send at least `postal_code` or `city`. If the order is saved after the session is created, send the address with [`POST /api/v1/checkout/sessions/{id}/order`](https://oncharge.io/docs/checkout#create-the-session-before-the-order-exists) instead. The address is fixed once recorded.
## 2. Report the tracking number
When the order ships, call [`POST /api/v1/shipments`](https://oncharge.io/docs/api#reportshipments). Identify the order by `session_id`, or by your `order_id` (the most recent paid session with that order ID).
```json title="Request"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"shipments": [
{ "carrier": "UPS", "tracking_number": "1Z999AA10123456784" },
{ "carrier": "USPS", "tracking_number": "9400 1000 0000 0000 0000 00" }
]
}
```
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"shipments": [
{ "tracking_number": "1Z999AA10123456784", "carrier": "ups", "status": "accepted" },
{ "tracking_number": "9400100000000000000000", "carrier": "usps", "status": "accepted" }
],
"delivery": { "state": "in_transit", "hold_reason": null }
}
```
- **Carriers:** USPS, UPS, FedEx and DHL Express. Common spellings are accepted (`USPS`, `United States Postal Service`, `FedEx Ground`, `DHL`, …). `carrier` may be left out when the number's format identifies the carrier (UPS numbers starting `1Z`, USPS IMpb and `…US` numbers).
- **Tracking numbers:** spaces and dashes are ignored; 8 to 40 letters and digits.
- **Several packages:** send every tracking number, in one call or several (up to 10 per order). The order is delivered when all of them are.
- **Repeats are safe:** a number already on the order is accepted again without change.
- The order must be paid (`captured`) first, otherwise the call fails with `409 order_not_paid`.
Each number is accepted or rejected on its own:
| `error` | Meaning |
|---|---|
| `carrier_not_supported` | The carrier is not USPS, UPS, FedEx or DHL Express, or could not be worked out. |
| `tracking_number_invalid` | Not a valid tracking number. |
| `carrier_mismatch` | The number belongs to a different carrier than the one given. |
| `tracking_number_in_use` | The number is already used for another order. |
| `too_many_shipments` | The order already has 10 tracking numbers. |
With the Node SDK:
```ts
const result = await oncharge.shipments.report({
order_id: '1001',
shipments: [{ carrier: 'FedEx', tracking_number: '7489 1234 5678' }],
});
```
The [WooCommerce plugin](https://oncharge.io/docs/woocommerce#shipping-and-tracking) reports tracking automatically from popular shipment-tracking plugins.
## 3. Follow the delivery
[`GET /api/v1/shipments?session_id=…`](https://oncharge.io/docs/api#getdeliverystatus) (or `oncharge.shipments.get(sessionId)`) returns the order's state and each package's result:
```json
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"delivery": {
"state": "delivered",
"hold_reason": null,
"delivered_at": "2026-01-04T17:12:00.000Z",
"shipments": [
{
"id": "3f2a…",
"carrier": "ups",
"carrier_label": "UPS",
"tracking_number": "1Z999AA10123456784",
"status": "delivered",
"result": "confirmed",
"problems": [],
"delivered_at": "2026-01-04T17:12:00.000Z",
"delivered_to": "San Francisco, CA, 94105",
"note": null,
"removable": false,
"created_at": "2026-01-02T09:30:00.000Z"
}
]
}
}
```
| `delivery.state` | Meaning |
|---|---|
| `not_tracked` | No delivery tracking applies (nothing to ship, or not paid yet). |
| `awaiting_shipment` | Paid; no tracking number reported yet. |
| `in_transit` | At least one package is still on its way. |
| `delivered` | Every package was confirmed delivered to the order address. The payout is scheduled. |
| `on_hold` | Payout held; `hold_reason` says why. |
| `refunded` | The order was refunded in full. |
When every package is confirmed, OnCharge also sends a [`delivery.confirmed` webhook](https://oncharge.io/docs/webhooks#event-types).
### When a delivery does not count
A carrier "delivered" event releases the payout only if the package moved after the order was paid, was delivered after payment, was not a return, and was delivered to the order's address. Otherwise the shipment's `result` is `problem`, with plain-language reasons in `problems`, for example:
- The delivery location does not match the order's shipping address.
- This package was already in transit before the order was paid.
- The carrier returned this package to the sender.
- This order has no shipping address on file to compare the delivery against.
The order is then held for review. If a number was entered by mistake and the carrier has not given a final answer, you can remove it in the merchant portal (`removable: true`) and report the right one.
| `hold_reason` (examples) | Cause |
|---|---|
| The shopper disputed this payment with their bank. | A chargeback is open. |
| The shopper's bank flagged this payment as possibly fraudulent. | A fraud warning was received. |
| A delivery for this order could not be matched to the order. | See the shipment's `problems`. |
| This order is under review. | OnCharge is reviewing the order. |
## Debit card payouts in minutes
Money a delivered order has released can reach a debit card within minutes instead of going to your bank with the next payout, for a fee. Nothing is paid earlier than it would be anyway: a debit card payout takes only what the next standard payout would pay right now (delivered, released orders and due reserves, less any refunds or chargebacks owed), and only money that has settled.
- **Add a debit card** in the merchant portal under **Settings → Payout account**: a non-prepaid Visa, Mastercard or Discover debit card from a US bank. It needs a security code emailed to you, every owner is emailed, and no debit card payout can reach a new card for 48 hours. Your bank account stays where standard payouts go.
- **Take it** from the **Payouts** page, or with [`GET` and `POST /api/v1/payouts/instant`](https://oncharge.io/docs/api#getinstantpayout). The quote shows what reaches the card, the fee (1.5% of the amount, at least $0.50, taken out of it) and when it should arrive (usually within 30 minutes). Send an `Idempotency-Key`: the same key never pays twice.
- **Limits:** $1 to $9,999 per payout, and up to $10,000 or 5 debit card payouts per store per day (the day resets at midnight US Central time).
- **Timing:** with a debit card on file, money you do not take to the card goes to your bank in one standard payout each day, in the evening (from 22:00 UTC), instead of every few minutes.
- Debit card payouts wait while payouts are paused, including the cooling-off after a bank account change.
- **If it does not arrive**, the money is back in your balance and goes to your bank with your next payout, and the fee is refunded. The card is turned off: add it again or use another one. You get a [`payout.failed` webhook](https://oncharge.io/docs/webhooks#event-types) with `method: "instant"`.
## Checklist
- Send `shipping` for every order you ship, at session creation or with `/order`.
- Report tracking numbers as soon as the label is created.
- Use USPS, UPS, FedEx or DHL Express for orders you want paid on delivery.
- Watch `on_hold` orders in the merchant portal.
---
# Customers & saved cards
OnCharge keeps your store's customers: who paid, what they spent, their refunds and disputes, and the cards they chose to save with you. A customer belongs to one store. The same shopper at two of your stores is two customers, and a card saved for one store can never be charged by another.
Customers are added three ways:
- **By paying.** A paid checkout with an email makes the shopper a customer of the store.
- **Through the API.** `POST /api/v1/customers` with an email, a name or your own reference.
- **By saving a card.** At checkout or on a save-card page (below).
See them in the portal under **Payments > Customers**: lifetime value, payments, refunds, disputes and saved cards, with search and a CSV export.
## Add a customer
```bash
POST /api/v1/customers
{ "email": "ann@example.com", "name": "Ann Smith", "reference": "crm-1042", "metadata": { "tier": "gold" } }
```
One email, and one reference, is one customer of a store. A second is refused with `409 customer_exists` and the existing customer's ID in `customer_id`. `GET /api/v1/customers?q=ann` searches by an OnCharge customer ID, or part of an email, name, phone or your reference; `GET /api/v1/customers/{customer_id}` returns one customer with their totals and saved cards.
## Save a card
A card is saved only when the shopper ticks a box that says what they agree to: that your store keeps the card and may charge it later, including when they are not at the checkout, for purchases and payments they agree to with you. The words and their version are recorded with each consent. Use a saved card only for what the shopper agreed to.
**At checkout.** Create the session with the customer and `save_card: true`:
```json
{ "amount": 2900, "currency": "USD", "reference": "order-1042", "return_url": "https://shop.example.com/thanks",
"customer_id": "0b6e4a52-6c3f-4b7e-9d1a-2f3e4a5b6c7d", "save_card": true }
```
The checkout shows the box under the card form. It is never ticked for the shopper; when they leave it unticked, nothing is saved. (Instead of `customer_id` you can send `customer_email`: the shopper becomes your customer with that email.)
**Without a payment.** Create a save-card page and send the customer to its `url`:
```bash
POST /api/v1/customers/{customer_id}/payment-methods
{ "return_url": "https://shop.example.com/account" }
```
The page is hosted by OnCharge. It shows the consent first and the card form only after the customer agrees, then sends them to `return_url`. It is open for 24 hours (`expires_in_hours`, up to 72).
Saved cards show only the brand, the last four digits and the expiry. When a card network renews or replaces a saved card, OnCharge updates its expiry and last four digits for you.
## Charge a saved card
```bash
POST /api/v1/customers/{customer_id}/charges
Idempotency-Key: subscription-2026-12-ann
{ "amount": 2900, "currency": "USD", "reference": "subscription-2026-12" }
```
Always send an `Idempotency-Key`: a retry returns the same charge and never charges twice. Without `payment_method_id` the customer's default card is used.
A charge is a payment like any checkout payment: the same fee, the same delivery-gated payout (an order that ships by carrier is paid out after delivery, so send `shipping` with `order_id`), the same `payment.*` webhooks, and it appears under Payments. Its `session_id` works with refunds and shipments.
| `status` | What happened |
|---|---|
| `succeeded` | Paid (201). |
| `processing` | The bank has not answered yet. A payment webhook follows (201). |
| `requires_authentication` | The customer's bank wants them to confirm the payment. OnCharge emailed them a link to an OnCharge page where they confirm it (`authentication.emailed`). The link goes to the customer only, so the cardholder confirms it, not whoever holds your API key (201). |
| `declined` | `decline.reason` and `decline.message` say why in plain words, for example `insufficient_funds` or `expired_card` (402). |
If the answer is `502 try_again`, the outcome is not known yet: retry with the same `Idempotency-Key` within 20 hours. A retry always charges the card the charge was started with. After 20 hours the charge answers `409 charge_not_completed`; check Payments, then start a new charge with a new key.
`POST /api/v1/recurring/charge` keeps working: on a store with its own card account it charges the saved card of your customer with that `shopper_email`. New integrations should use the customers API.
## Remove a saved card
```bash
DELETE /api/v1/customers/{customer_id}/payment-methods/{payment_method_id}
```
The card is removed for good and can never be charged again. Owners and admins can also remove a card from the customer's page in the portal.
## SDK
```ts
const customer = await oncharge.customers.create({ email: 'ann@example.com' });
const page = await oncharge.customers.paymentMethods.createSetupSession(customer.id, { return_url: 'https://shop.example.com/account' });
const charge = await oncharge.customers.charges.create(customer.id, { amount: 2900, currency: 'USD' }, { idempotencyKey: 'subscription-2026-12-ann' });
```
---
# Invoices
Bill a customer for work or goods and get paid online. An invoice is drafted, finalized (it gets your store's next number, such as `INV-0001`, and a payment link), and sent by email with a PDF. Your customer opens OnCharge's hosted invoice page and pays through OnCharge checkout, by card or crypto where your store has that rail on. Overdue invoices are reminded automatically.
You can do everything from the dashboard (**Payments → Invoices**) or with the API below. Every request is signed like the rest of the API: see [Authentication & signing](https://oncharge.io/docs/authentication).
## How an invoice moves
| Status | What it means | What you can do |
|---|---|---|
| `draft` | Being written. No number, no payment link. | Edit, delete, finalize. |
| `open` | Finalized: numbered, payable, emailed if you chose. Nothing on it can change. | Send again, void (if nothing was paid), mark paid, credit note. |
| `paid` | Paid in full: through OnCharge, outside OnCharge (marked paid), or by credit notes. | Credit note (and refund it to the payment). |
| `void` | Cancelled before anything was paid. Its number stays used. | Nothing. |
An open invoice past its due date shows as `overdue` (`display_status`). A finalized invoice is never edited: void it and create another, or issue a credit note.
## Create and send an invoice
```bash
POST /api/v1/invoices
Idempotency-Key: invoice-2026-11-ada
```
```json
{
"currency": "USD",
"customer": {
"name": "Ada Lovelace",
"email": "ada@example.com",
"address": { "line1": "1 Main St", "city": "Austin", "state": "TX", "postal_code": "78701", "country": "US" }
},
"lines": [
{ "description": "Consulting, November", "quantity": 10, "unit_amount": 15000, "tax_rate": 8.875 },
{ "description": "Returning-client discount", "quantity": 1, "unit_amount": -5000 }
],
"days_until_due": 14,
"memo": "Thank you for your business.",
"reply_to": "billing@yourstore.com",
"send": true
}
```
- Amounts are integers in the currency's minor units (cents; JPY has none). A negative `unit_amount` is a discount line.
- `tax_rate` is a percent with up to three decimals. Each line's tax is rounded half away from zero; the totals are worked out by OnCharge.
- Without `finalize` or `send` the invoice stays a draft. `finalize: true` numbers it and opens it for payment; `send: true` also emails it.
- A repeat with the same `Idempotency-Key` returns the first invoice with `idempotent: true`.
The answer is the invoice: its `number`, `hosted_url` (the page your customer pays on), `total`, `amount_remaining`, `due_at` and the rest.
## Getting paid
The customer pays on the hosted invoice page. Each payment is an ordinary OnCharge checkout for what is left to pay, so:
- the usual `payment.*` [webhooks](https://oncharge.io/docs/webhooks) arrive for it, with `data.invoice_id` set to the invoice's id (the session's `order_id` and `reference` are the invoice number);
- the risk checks, fees and payouts are the same as any payment. Items with `requires_shipping` are paid out after the carrier confirms delivery to the invoice's `shipping_address`, as for any order; invoices for services are paid out 7 days after payment.
When the payment is captured, the invoice is marked `paid` once, and its `payment_reference` is the payment's OnCharge reference (`ocpay_…`).
Only one payment for an invoice is open at a time. Pressing Pay again reuses the checkout already opened, or closes it (cancelling its payment) before starting another; while a card payment is approved and being collected, the page says it is being confirmed instead of offering Pay. Voiding, marking paid and credit notes first close any open checkout the same way, and wait while a card payment is being collected (`409 payment_in_progress`).
If a payment still arrives for more than the invoice needs (it was already settled, voided or credited), the invoice takes only what was left: the rest shows in its history as an extra payment (`payment_unapplied`), you get a notice, and `POST /api/v1/invoices/{id}/refund-extra` with the payment's `payment_reference` refunds it, once.
A store that is not active (for example, suspended) takes no invoice payments: its hosted invoice pages say so, no reminders go out, and new invoices are not created, finalized or sent.
Card payments on stores paid out per delivered order are in USD only. `payment_options` on an invoice says how the customer can pay it and, when a rail is off, why.
## Reminders and receipts
While an invoice is open and `send_reminders` is on, OnCharge emails the customer 1, 7 and 14 days after the due date. When it is paid through OnCharge, the customer gets a receipt and you get a notice in the dashboard.
## Other actions
| Request | What it does |
|---|---|
| `GET /api/v1/invoices?status=overdue` | List invoices (`draft`, `open`, `overdue`, `paid`, `void`, `all`), newest first. Page with `cursor`. |
| `GET /api/v1/invoices/{id}` | The invoice with its lines, history, payments and credit notes. |
| `POST /api/v1/invoices/{id}` | Edit a draft (`lines` replaces every line). |
| `DELETE /api/v1/invoices/{id}` | Delete a draft. |
| `POST /api/v1/invoices/{id}/finalize` | Number it and open it for payment (`{ "send": true }` also emails it). |
| `POST /api/v1/invoices/{id}/send` | Email it (again) with the PDF attached. |
| `POST /api/v1/invoices/{id}/void` | Cancel an open invoice nothing was paid on. |
| `POST /api/v1/invoices/{id}/mark-paid` | Record it as paid outside OnCharge (bank transfer, cash). |
| `POST /api/v1/invoices/{id}/credit-notes` | Issue a credit note (below). |
| `POST /api/v1/invoices/{id}/refund-extra` | Refund an extra payment (`{ "payment_reference": "ocpay_…" }`), once. |
| `GET /api/v1/invoices/{id}/pdf` | The invoice or credit note as a PDF. |
## Credit notes
```json
POST /api/v1/invoices/{id}/credit-notes
{ "amount": 5000, "reason": "order_change", "memo": "Two hours fewer than quoted.", "refund": false }
```
A credit note is numbered on its own (`CN-0001`) and emailed to the customer. On an open invoice it lowers what is left to pay; a credit for all of it settles the invoice. On a paid invoice it records a credit, and `"refund": true` also refunds it to the customer's payment (only for an invoice paid through OnCharge). Send `lines` instead of `amount` to itemize it. `reason` is one of `duplicate`, `fraudulent`, `order_change`, `product_unsatisfactory` or `other`.
## Errors
| Status | `error` | Meaning |
|---|---|---|
| 409 | `invoice_locked` | The invoice is finalized and cannot be edited or deleted. |
| 409 | `invoice_not_draft`, `invalid_transition` | Not possible in its status (for example voiding a paid invoice). |
| 409 | `invoice_partly_paid` | Part of it is paid: issue a credit note instead of voiding. |
| 409 | `payment_in_progress` | A payment for the invoice is under way. Try again in a few minutes. |
| 409 | `store_inactive` | The store is not taking payments. |
| 422 | `invoice_too_large` | The lines would total more than 100000000000 minor units. |
| 422 | `invoice_incomplete` | Finalizing needs a line, a total above zero and the customer's name; sending needs their email. |
| 422 | `credit_too_large` | A credit note is at most what is left to pay (or, once paid, the invoice's total). |
| 404 | `not_found` | No such invoice in your store. |
## SDK
```ts
import { OnCharge } from '@oncharge/node';
const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_API_KEY!, apiSecret: process.env.ONCHARGE_API_SECRET! });
const invoice = await oncharge.invoices.create(
{ customer: { name: 'Ada Lovelace', email: 'ada@example.com' }, lines: [{ description: 'Consulting', quantity: 10, unit_amount: 15000 }], send: true },
{ idempotencyKey: 'invoice-2026-11-ada' },
);
console.log(invoice.number, invoice.hosted_url);
```
See [SDKs](https://oncharge.io/docs/sdks) for every method.
---
# Subscriptions
Bill customers again and again on a schedule: a monthly box, a yearly membership, a weekly delivery. You make a plan (a price every month, every 3 months, every year, …); customers sign up to it; OnCharge bills each period for you. Each period is an OnCharge invoice (`INV-0042`) charged to the card the customer saved at your store, through an ordinary OnCharge checkout session, so its payment, fees, payout and webhooks are those of any other payment.
Customers sign up, agree to the recurring charges and manage their subscription on OnCharge's own pages: the sign-up page and their subscription page. Your customers never see another company's page.
You can do everything from the dashboard (**Payments → Subscriptions**: subscriptions, **Plans and add-ons**, **Settings**) or with the API below. Every request is signed like the rest of the API: see [Authentication & signing](https://oncharge.io/docs/authentication).
> **Not available yet.** Subscriptions are being checked end to end before they are turned on. Until then every subscription endpoint, page and sign-up link answers `404 not_found` ("Subscriptions are not available yet."), and nothing is billed.
## Turning it on
Once subscriptions are available there is nothing to switch on: create a plan. Your store needs:
- to be active (`409 store_inactive` otherwise);
- card payments set up for saved cards, as for [charging a saved card](https://oncharge.io/docs/customers#charge-a-saved-card) (`409 subscriptions_unavailable` otherwise);
- for a subscription you start for an existing customer, the customer's email address: OnCharge emails them the link to confirm it.
Under **Payments → Subscriptions → Settings** choose, per store, what happens when a customer's payments keep failing (cancel the subscription, the default, or pause it) and whether customers may pause their own subscriptions (on by default, for up to 3 periods; up to 12).
## Plans and add-ons
A **plan** is a price per period. An **add-on** is an extra billed with a plan, in the same periods (a second bag, a gift wrap): it has no interval, trial or intro price of its own.
```bash
POST /api/v1/plans
Idempotency-Key: plan-monthly-box
```
```json title="Request"
{
"name": "Monthly box",
"description": "A box of our best sellers, every month.",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"trial_days": 14,
"intro": { "amount": 1500, "periods": 2 },
"requires_shipping": true
}
```
```json title="Response (201)"
{
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"object": "plan",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"interval_text": "month",
"trial_days": 14,
"intro": { "amount": 1500, "periods": 2 },
"requires_shipping": true,
"active": true,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z"
}
```
| Field | What it does |
|---|---|
| `kind` | `plan` (default) or `addon`. |
| `name`, `description` | What the customer sees on the sign-up page, their emails and invoices. |
| `amount`, `currency` | The price per period, per unit, in minor units (cents). Default currency `USD`. Add-ons must be in their plan's currency. |
| `interval`, `interval_count` | `day`, `week`, `month` or `year`, times `interval_count` (default 1). A period is at most a year: up to 365 days, 52 weeks, 12 months or 1 year. Plans only, and required for them. |
| `trial_days` | A free trial: 0 (none) or 7 to 365 days. The customer signs up and saves a card; the first charge is when the trial ends, and they are reminded 7 days before. A shorter trial is refused (`400 invalid_request`), so the reminder the card networks require always fits. |
| `intro` | A lower price for the first periods: `{ "amount": 1500, "periods": 2 }` charges 15.00 for the first two periods, then `amount`. Lower than `amount`, for 1 to 24 periods. |
| `requires_shipping` | Each period is a shipped order: the subscription needs a shipping address, and each period is paid out after carrier-confirmed delivery. On a store set up as shipping physical goods, every period ships whatever this says. |
| `metadata` | Up to 20 of your own keys. |
A subscription has a `quantity` (1 to 1000, default 1): the plan's price is multiplied by it. Add-ons have their own quantities.
**A plan's price and terms never change once it is created.** Customers agreed to them. To charge a different price, create another plan and move subscriptions to it with [`change`](#change-the-plan-quantity-or-add-ons): a higher price applies only after the customer is given notice ([below](#price-increases)). You can rename a plan, change its description or metadata, or archive it:
```bash
PATCH /api/v1/plans/{id}
{ "active": false }
```
An archived plan takes no new subscriptions; those already on it go on. `GET /api/v1/plans` lists active plans and add-ons (`?include_archived=true` for all), newest first; `GET /api/v1/plans/{id}` returns one.
## Start a subscription
Nothing is charged until the customer agrees to the recurring charges on OnCharge's sign-up page ([below](#recurring-consent)). You never put a card on a subscription yourself. There are three ways to bring a customer to that page.
### 1. For an existing customer: OnCharge emails them
```bash
POST /api/v1/subscriptions
Idempotency-Key: sub-ada-box
```
```json title="Request"
{
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"quantity": 1,
"addons": [{ "plan_id": "d2e3f4a5-b6c7-4d8e-9f0a-1b2c3d4e5f6a", "quantity": 1 }],
"shipping": { "name": "Ada Lovelace", "line1": "1 Main St", "city": "Austin", "state": "TX", "postal_code": "78701", "country": "US" }
}
```
The subscription is created as `incomplete` and OnCharge emails the customer a link to its sign-up page. The page may offer the cards they already saved at your store. **The link is never returned to you**: only the cardholder can choose a card for the subscription. It works for 7 days (`sign_up_expires_at`); after that the subscription is `incomplete_expired`. The customer needs an email address (`409 customer_email_required`).
### 2. A hosted sign-up page you send the customer to
```bash
POST /api/v1/subscriptions/checkout
Idempotency-Key: signup-ada
```
```json title="Request"
{
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"customer_email": "ada@example.com",
"customer_name": "Ada Lovelace",
"shipping": { "name": "Ada Lovelace", "line1": "1 Main St", "city": "Austin", "state": "TX", "postal_code": "78701", "country": "US" },
"success_url": "https://shop.example.com/welcome"
}
```
```json title="Response (201, shortened)"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"status": "incomplete",
"status_text": "Waiting for customer",
"plan": { "id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f", "name": "Monthly box", "amount": 3000, "currency": "USD", "interval": "month", "interval_count": 1 },
"payment_method": null,
"source": "checkout",
"sign_up_expires_at": "2026-12-02T00:00:00.000Z",
"url": "https://app.oncharge.io/s/subscribe/7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b?token=ocs_…"
}
```
Send the customer to `url` (it works for 24 hours). They enter a new card there; this page never offers saved cards, because you hold the link. Give `customer_id` for an existing customer, or `customer_email` (the customer is found by email, or added to your store). `success_url` (https) is where they go after signing up; it is kept in the subscription's `metadata`.
### 3. A payment link for a plan
```bash
POST /api/v1/plans/{id}/payment-link
{ "title": "Join the Monthly box" }
```
```json title="Response (201)"
{ "id": "5f0c9d4e-2a1b-4c3d-9e8f-7a6b5c4d3e2f", "code": "k7Hq2mNpR4sT", "url": "https://app.oncharge.io/l/k7Hq2mNpR4sT", "plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f" }
```
Share the link anywhere. A shopper who opens it enters their email (and shipping address if the plan ships) and continues to the sign-up page with a new card. It is one of your [payment links](https://oncharge.io/docs/payment-links): it appears with them, and you turn it off the same way.
Each way: a repeat with the same `Idempotency-Key` returns the first subscription (`200`); the same key for another customer or plan is refused (`409 idempotency_conflict`). A subscription that ships needs `shipping` (`422 shipping_address_required`).
## Recurring consent
On the sign-up page the customer reads the terms before anything else: the price and how often, any intro price and for how many payments, the trial and the date of the first charge, shipping, and how to cancel. They choose a saved card or enter a new one (a new card records the [save-card consent](https://oncharge.io/docs/customers#save-a-card) and is saved before anything is charged). With the card known, the page shows the recurring-charge disclosure naming it (for example "Card to be charged: Visa ending 4242."), and they tick a box to agree to the recurring charges on that card.
Each consent is recorded with the version of the words and the SHA-256 of exactly what was shown (your store's name, the terms and the card's brand and last four digits included), with the time, IP address and browser. If the terms changed while the page was open, or the customer picks another card, they are asked to agree again. A customer whose first card is declined agrees again on the next one. No charge is made for a subscription without its consent.
Then the subscription starts: a trial starts at once; otherwise the first period is charged and the subscription starts when it is paid. If the customer's bank asks them to confirm the payment, the page sends them to OnCharge's confirmation page. The customer gets a confirmation email naming the card charged, with a link to their subscription page.
When the customer cancels, their consent is withdrawn: nothing is charged for that subscription again.
## Statuses
| `status` | What it means |
|---|---|
| `incomplete` | Waiting for the customer to sign up (`sign_up_expires_at`). |
| `incomplete_expired` | They did not sign up in time. Nothing was charged. |
| `trialing` | In its free trial (`trial_end`). Nothing charged yet. |
| `active` | Paid up. Charged again at `next_billing_at`. |
| `past_due` | A payment failed and is being retried ([failed payments](#failed-payments)). |
| `paused` | Nothing is charged or shipped until it resumes (`pause.resume_at`, or when you or the customer resume it). |
| `canceled` | Ended (`ended_at`, `cancel_reason`: `merchant`, `customer`, `api`, `dunning`, `store_closed` or `reminder_undeliverable`). Nothing more is charged. |
A subscription also says what is waiting for the end of the period: `cancel_at_period_end`, `pause.at_period_end` and `pending_change`.
## Billing and proration
**Periods.** Periods are counted from the day the subscription started, never from the previous period's end: a subscription started on January 31 is billed on February 28, March 31, April 30, and so on. A trial's end starts the first period; resuming after a pause, or moving to a plan with another interval, starts the count again.
**Each period's bill.** At the start of each period OnCharge opens a bill (a `SubscriptionBilling`): its lines (the plan at its intro or regular price, times `quantity`, then each add-on), minus any credit from earlier downgrades. The bill has its own OnCharge invoice, listed with your [invoices](https://oncharge.io/docs/invoices), and is charged to the subscription's card through a checkout session whose `order_id` and `reference` are the invoice number. That payment fires the usual `payment.*` [webhooks](https://oncharge.io/docs/webhooks) with `data.invoice_id`, then `subscription.period.paid`.
**Reminders.** Each reminder counts as sent only once the email service accepted it, as of that moment; one that did not go is tried again on the next run (with the same idempotency key, so a retry never sends it twice). The customer is emailed:
- 7 days before the first charge after a trial (a 7-day trial: as it starts), whatever plan the subscription is on by then, with the date and amount of that charge. The first charge never comes before this reminder went at least 7 days ahead, nor before the date it named:
- sent late, it names a date 7 days and an hour away, and the first charge moves to that date;
- not sent yet when the trial ends, the charge is held (nothing is charged or moved) and the reminder is tried again after a growing wait (10 minutes up to 6 hours); if it still could not be emailed 72 hours after it first failed, the subscription ends without being charged (`cancel_reason: "reminder_undeliverable"`) and you are told;
- a trial paused at its end is reminded 7 days before it resumes; resumed early (by you, the API or the customer), it is not charged at once: the reminder goes then, and the first charge comes 7 days (and an hour) later;
- 14 days before an introductory price ends, when the intro offer lasts more than 31 days, with the regular price from then and the card;
- 30 days before each renewal of a plan billed every year (`interval: "year"`);
- before a price increase you make ([below](#price-increases)).
### Change the plan, quantity or add-ons
```bash
POST /api/v1/subscriptions/{id}/change
{ "plan_id": "…", "quantity": 2 }
```
- A change that **raises the price** waits for the customer's notice: see [price increases](#price-increases). It is never applied at once (`"proration": "now"` is refused with `409 price_increase_needs_notice`), and a change applied now never charges more for the current period.
- Any other change applies at once by default (`"proration": "now"`). The rest of the current period is prorated: the difference between the old and the new price per period, for the time left (to the second), rounded half up to the minor unit, is a credit (`credit_balance`) taken off the next bills; the answer's `proration` says how much.
- `"proration": "next_period"` applies it at the renewal; until then it shows as `pending_change`.
- A **shipped subscription** changes at the next period only (each charge is one shipped period's order), and so does a move to a plan with **another interval**: ask for `now` and you get `409 change_at_next_period`. A **paused** subscription always changes at the next period. A trialing one changes at once with nothing to prorate.
- A new plan ends any intro price left. `addons` replaces every add-on (`[]` removes them). The new plan must be in the same currency.
The customer is emailed the new price and when it applies.
### Price increases
A change that makes the customer pay more is scheduled, never applied at once. It pays more when either a charge gets bigger or the price per day rises: another plan, more units, more add-ons, a plan without the intro price they still had, or another interval ($30 a month to $10 a week costs more per day; $30 a month to $300 a year is a bigger charge; both need the notice):
1. It waits in `pending_change`, with `increase`: the price before and after (each with its period, `from_every` and `to_every`), and the period it applies from (`effective_at`): the first period that starts at least 7 days from now on the subscription's real schedule. For a paused subscription that is the day it resumes; with no resume date it has no date yet (`null`).
2. The customer is emailed a notice 7 to 30 days before `effective_at`: at once when it is 30 days away or nearer, otherwise 30 days before. It names the new price, the date and the card, and how to cancel online before then. `increase.notice_sent_at` is set only once the email service accepted it; one that did not go is tried again. A notice belongs to one change and one date (`pending_change.change_id`, `increase.version`): a newer change, or a new date, is always told again.
3. The new price is charged only for the period starting `effective_at`, when the notice went 7 to 30 days before. If the notice could not go out in time, or the schedule moved (a pause, an earlier resumption), the increase moves on to the next period far enough ahead and the customer is told the new date.
`subscription.updated` arrives with `change: "change_scheduled"` when you make it, and `change: "price_increase_notice"` when the customer is told. A change that lowers the price needs no notice.
## Failed payments
When a period's charge fails, the subscription becomes `past_due` and OnCharge works to collect it:
- **Retries** 1, 3, 7 and 14 days after the first failure.
- **Failures a retry cannot fix wait for the customer.** If the bank wants the customer to confirm the payment, OnCharge emails them a link to confirm it. If the card can no longer be used (expired, wrong details, not supported, refused as suspected fraud), they are asked to add another card. Neither is retried blindly. `failure.waits_for_customer` says so, and `next_attempt_at` is null.
- **The customer is emailed after each failure**, with a link to their subscription page (to change the card) and to the period's invoice page (to pay it another way). A card they save there is charged at once.
- **You are told** in the dashboard at the first failure and when collecting ends, and by `subscription.period.payment_failed` (each failed attempt) and `subscription.past_due` webhooks.
- **When it ends.** 14 days after the first failure, with nothing left to try, the bill is given up (`status: "uncollectible"`, its invoice voided) and the subscription is cancelled (`cancel_reason: "dunning"`), or paused if your Settings say so.
Paid in the meantime (a retry, the customer's new card, the invoice page), the subscription is `active` again and `subscription.updated` arrives with `change: "payment_recovered"`. You can also charge it now with `POST /api/v1/subscriptions/{id}/retry`, or ask the customer to switch to another of their saved cards with `PATCH /api/v1/subscriptions/{id}` and `payment_method_id` ([below](#change-the-card)). A sign-up's first charge is not retried: the customer is on the page and can use another card.
## Change the card
Only the customer changes the card a subscription is charged to: it is the card they agreed to. With `PATCH /api/v1/subscriptions/{id}` and `payment_method_id` (another of their saved cards at your store) OnCharge emails the customer a link to switch to that card on their subscription page, naming it (for example "Visa ending 5555"), and answers `202` with `card_change: { "status": "customer_asked" }`. You can ask once an hour per subscription (`429 too_many_requests` otherwise). If the email cannot be sent, nothing in the request is saved (`502 customer_not_emailed`).
The subscription keeps its card, and nothing is charged to the other one, until the customer switches. On their page they agree to the charges on the new card (the disclosure names it), which is recorded as a new consent; a past-due subscription is then charged to it at once.
## Pause, resume and cancel
| Request | What it does |
|---|---|
| `POST /api/v1/subscriptions/{id}/pause` `{ "periods": 2 }` | Pauses from the **end of the current period** (nothing already paid is lost): for `periods` periods (1 to 12), until `resume_at`, or, with neither, until resumed. While paused nothing is charged or shipped. Only an active or trialing subscription; a past-due one must be paid first (`409 payment_required`). |
| `POST /api/v1/subscriptions/{id}/resume` | A **paused** subscription starts again now: a new period begins and is charged at once. On a subscription with a pause or a cancellation **waiting** for the period's end, calls it off. A cancellation the customer asked for is theirs: only they can subscribe again (`409 canceled_by_customer`). |
| `POST /api/v1/subscriptions/{id}/cancel` | By default (`at_period_end: true`) an active or trialing subscription ends when its current period or trial ends: no more charges, and it is `canceled` then. `{ "at_period_end": false }`, or any other status, ends it now; anything unpaid is voided. |
The customer is emailed when their subscription is paused, cancelled or ends.
## The customer's subscription page
Customers manage their subscriptions at your store on an OnCharge page, reached only by a link emailed to them: every subscription email carries one, and it works for 24 hours. To get a fresh link, a customer enters their email at `https://app.oncharge.io/s/manage?store=`; if they have a subscription at your store, OnCharge emails them one. On the page they can:
- **change the card**: one of their cards saved at your store, or a new one (a past-due subscription is charged at once);
- **cancel** at the end of the current period;
- **pause and resume**, if your Settings allow it, for up to the number of periods you chose.
## Delivery-gated payouts
Subscriptions keep OnCharge's payout rule: a shipped order is paid out only after the carrier confirms delivery. **Each shipped period is its own order**: its checkout session carries the subscription's shipping address and the period's lines, and its payout waits for delivery like any other order ([Shipments & payouts](https://oncharge.io/docs/shipments)). A period that does not ship is paid out like any digital order.
So when a period ships, report its tracking number with that period's session: `data.session_id` of its `subscription.period.paid` (or `payment.captured`) webhook, or the period's invoice number as `order_id`:
```json title="POST /api/v1/shipments"
{ "session_id": "8f14e45f-ceea-467a-9575-2c3b8e1f0b6d", "shipments": [{ "carrier": "usps", "tracking_number": "9400111899223344556677" }] }
```
The shipping address belongs to the subscription: change it with `PATCH /api/v1/subscriptions/{id}` and `shipping`, and the next periods ship there.
## Webhooks
Subscription events arrive at your [webhook endpoints](https://oncharge.io/docs/webhooks) like every other event, signed the same way, alongside the `payment.*` events of each period's payment. Choose them (or the whole `subscription.*` group) for an endpoint on the **Webhooks** page of the portal.
| `type` | When |
|---|---|
| `subscription.created` | A customer agreed and the subscription started: its trial began, or its first period was paid. |
| `subscription.updated` | The plan, quantity, card, or a waiting cancellation or pause changed. `data.change`: `plan_changed` (with `prorated_charge`, `prorated_credit`), `change_scheduled` (with `pending_change`), `price_increase_notice` (the customer was emailed the notice of a price increase, with `price_increase`), `change_applied`, `payment_method`, `cancel_scheduled`, `pause_scheduled`, `kept` (a waiting cancellation or pause was called off), `trial_ended` or `payment_recovered`. |
| `subscription.trial_will_end` | A trial ends soon; the customer was reminded. Once per trial. |
| `subscription.past_due` | A period's payment failed; OnCharge is retrying it. |
| `subscription.paused` | It paused: nothing is charged or shipped until it resumes. |
| `subscription.resumed` | A paused subscription started again; a new period began and was charged. |
| `subscription.canceled` | It ended: cancelled by you or the customer, or after its payment failed on every retry. |
| `subscription.period.paid` | A period (or a plan change) was paid. If it ships, ship it and report the tracking with `data.session_id`. |
| `subscription.period.payment_failed` | A charge for a period failed. `data.failure` says why and `data.next_attempt_at` when it is tried again (null: it waits for the customer). |
`subscription.*` events carry the subscription:
```json title="subscription.canceled"
{
"id": "evt_5f0c2a8e-1b7d-4c39-9e64-2d8f1a7b3c90",
"type": "subscription.canceled",
"created": 1767225600,
"livemode": true,
"data": {
"subscription_id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"status": "canceled",
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"plan_name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"quantity": 1,
"trial_end": null,
"current_period_start": "2026-12-01T00:00:00.000Z",
"current_period_end": "2027-01-01T00:00:00.000Z",
"cancel_at_period_end": false,
"canceled_at": "2026-12-20T00:00:00.000Z",
"cancel_reason": "customer",
"paused_at": null,
"resume_at": null,
"rail": "card"
}
}
```
`subscription.period.*` events carry one bill and its payment:
```json title="subscription.period.paid"
{
"id": "evt_5f0c2a8e-1b7d-4c39-9e64-2d8f1a7b3c90",
"type": "subscription.period.paid",
"created": 1767225600,
"livemode": true,
"data": {
"subscription_id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"billing_id": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"reason": "period",
"period_index": 1,
"period_start": "2027-01-01T00:00:00.000Z",
"period_end": "2027-02-01T00:00:00.000Z",
"amount": 3000,
"currency": "USD",
"invoice_id": "4d5e6f7a-8b9c-4d0e-8f1a-2b3c4d5e6f7a",
"invoice_number": "INV-0042",
"session_id": "8f14e45f-ceea-467a-9575-2c3b8e1f0b6d",
"payment_reference": "ocpay_8f14e45fceea467a95752c3b8e1f0b6d",
"attempt": 1,
"ships": true,
"failure": null,
"next_attempt_at": null,
"status": "paid",
"rail": "card"
}
}
```
On `subscription.period.payment_failed`, `status` is `failed`, `session_id` and `payment_reference` may be null, and `failure` is `{ "reason", "message" }` with `reason` one of `declined`, `authentication_required`, `unusable_card`, `error` or `store_unavailable`. Each event is sent once per change; acknowledge (`2xx`) any type you do not handle.
## Endpoints
| Request | What it does |
|---|---|
| `GET /api/v1/plans` | Plans and add-ons, newest first (`include_archived=true` for archived ones too): `{ data }`. |
| `POST /api/v1/plans` | Create a plan or add-on. `Idempotency-Key` honoured. |
| `GET /api/v1/plans/{id}` | One plan. |
| `PATCH /api/v1/plans/{id}` | Rename, describe, archive (`active: false`) or change its metadata. |
| `POST /api/v1/plans/{id}/payment-link` | A payment link that signs shoppers up to the plan. |
| `GET /api/v1/subscriptions` | Subscriptions, newest first: `{ data, has_more }`. Filter with `status` and `customer_id`; page with `limit` (up to 100, default 25) and `starting_after` (the last `id` of the previous page). |
| `POST /api/v1/subscriptions` | Start one for an existing customer (OnCharge emails them). `Idempotency-Key` honoured. |
| `POST /api/v1/subscriptions/checkout` | Start one with a hosted sign-up page (`url`). `Idempotency-Key` honoured. |
| `GET /api/v1/subscriptions/{id}` | The subscription with every bill (`billings`: lines, invoice, attempts, failure, `payment_reference`) and its `history`. |
| `PATCH /api/v1/subscriptions/{id}` | Change the shipping address or the metadata (replaced), or ask the customer to switch to another of their saved cards (`payment_method_id`). |
| `POST /api/v1/subscriptions/{id}/change` | Change the plan, quantity or add-ons. |
| `POST /api/v1/subscriptions/{id}/pause` | Pause from the end of the period. |
| `POST /api/v1/subscriptions/{id}/resume` | Resume, or call off a waiting pause or cancellation. |
| `POST /api/v1/subscriptions/{id}/cancel` | Cancel at the end of the period (default) or now. |
| `POST /api/v1/subscriptions/{id}/retry` | Charge a past-due subscription now. |
`PATCH` requests are signed like any other, with `PATCH` as the method and the JSON body. Every field and answer is in the [API reference](https://oncharge.io/docs/api#subscriptions).
### With curl
With the `oncharge` helper from [Authentication & signing](https://oncharge.io/docs/authentication#curl):
```bash
oncharge POST /api/v1/plans '{"name":"Monthly box","amount":3000,"currency":"USD","interval":"month","trial_days":14}'
oncharge POST /api/v1/subscriptions/checkout '{"plan_id":"c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f","customer_email":"ada@example.com"}'
oncharge GET "/api/v1/subscriptions?status=past_due&limit=50"
oncharge PATCH /api/v1/subscriptions/7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b '{"payment_method_id":"5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e"}'
oncharge POST /api/v1/subscriptions/7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b/cancel '{"at_period_end":true}'
```
To send an `Idempotency-Key`, add `-H "Idempotency-Key: …"` to the helper's curl arguments.
### With the SDK
```ts
import { OnCharge } from '@oncharge/node';
const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_API_KEY!, apiSecret: process.env.ONCHARGE_API_SECRET! });
const plan = await oncharge.plans.create(
{ name: 'Monthly box', amount: 3000, currency: 'USD', interval: 'month', trial_days: 14, requires_shipping: true },
{ idempotencyKey: 'plan-monthly-box' },
);
const signup = await oncharge.subscriptions.checkout(
{ plan_id: plan.id, customer_email: 'ada@example.com', shipping: { name: 'Ada Lovelace', line1: '1 Main St', city: 'Austin', state: 'TX', postal_code: '78701', country: 'US' } },
{ idempotencyKey: 'signup-ada' },
);
// signup.status → 'incomplete'; send the customer to signup.url
const sub = await oncharge.subscriptions.retrieve(signup.id); // with billings and history
await oncharge.subscriptions.change(sub.id, { quantity: 2, proration: 'next_period' });
await oncharge.subscriptions.pause(sub.id, { periods: 1 });
await oncharge.subscriptions.resume(sub.id);
await oncharge.subscriptions.cancel(sub.id); // at the end of the period
const link = await oncharge.plans.createPaymentLink(plan.id); // link.url signs shoppers up
```
`OnCharge.webhooks.constructEvent` types every subscription event: switch on `event.type` and `event.data` has its shape. See [SDKs](https://oncharge.io/docs/sdks).
## Errors
Errors are `{ "error": "", "message": "" }`. Besides the [errors every endpoint can return](https://oncharge.io/docs/authentication#errors):
| Status | `error` | Meaning |
|---|---|---|
| 400 | `invalid_request`, `invalid_json` | The body is not valid; the message names the first invalid field (a trial of 1 to 6 days, an intro price not lower than the price, an add-on listed twice or in another currency, both `periods` and `resume_at`, …). |
| 400 | `invalid_idempotency_key` | The `Idempotency-Key` is longer than 255 characters or has control characters. |
| 400 | `currency_mismatch` | A plan change to a plan in another currency. |
| 404 | `not_found` | No such subscription in your store, or subscriptions are not available yet. |
| 404 | `plan_not_found`, `addon_not_found`, `customer_not_found`, `payment_method_not_found` | No such plan, add-on, customer or active saved card of the customer in your store. |
| 409 | `plan_inactive` | The plan or an add-on is archived. |
| 409 | `store_inactive`, `subscriptions_unavailable` | The store is not taking payments, or has no card payments set up for saved cards. |
| 409 | `customer_email_required` | The customer has no email address to send the sign-up link to, or to ask them to switch cards. |
| 409 | `idempotency_conflict` | The `Idempotency-Key` was used for another customer or plan. |
| 409 | `subscription_ended`, `not_started` | It has ended; or it has not started, so the customer chooses the card. |
| 409 | `not_pausable`, `payment_required`, `cancel_scheduled` | Only an active or trialing subscription pauses; a past-due one must be paid first; one ending at the period's end cannot pause. |
| 409 | `not_paused`, `canceled_by_customer` | Nothing to resume; the customer cancelled it themselves. |
| 409 | `not_changeable`, `change_at_next_period` | It cannot change now (past due, ended or not started); or the change must wait for the next period (`proration: "next_period"`). |
| 409 | `price_increase_needs_notice` | The change raises the price, so it cannot apply now: leave `proration` out (or send `"next_period"`) to schedule it with the customer's notice. |
| 429 | `too_many_requests` | You asked this customer to switch cards less than an hour ago. |
| 502 | `customer_not_emailed` | The email asking the customer to switch cards could not be sent; nothing in the request was saved: try again. |
| 409 | `trial_too_short` | The plan's trial is shorter than 7 days (a plan made before the minimum): it takes no new subscriptions and cannot be taken out of the archive. |
| 409 | `not_past_due` | Only a past-due subscription is retried. |
| 409 | `payment_in_progress`, `conflict` | A payment for it is being collected, or it changed meanwhile: try again in a minute. |
| 422 | `shipping_address_required` | The subscription ships each period: send `shipping`. |
---
# Sales tax
OnCharge can calculate US sales tax on your orders for the states you are registered in, add it at checkout (or take it out of prices that include it), record what you collected, give back its share when you refund, and give you a report to file from.
You decide where you must register, and you file returns and pay the tax yourself: OnCharge does not file or pay sales tax and does not give tax advice. OnCharge charges $0.50 per order taxed in a state you have added, taken with its fee on that order. It is not returned when the order is refunded (the rest of OnCharge's fee is returned in proportion, as for any refund).
Sales tax needs card payments set up for your store. Turn it on in the dashboard: **Settings → Sales tax**.
## Set it up
1. **Where you ship from.** Your store's origin address.
2. **States you are registered in.** Tax is calculated only for these. An order to any other state is not taxed. A registration can start on a later date and be ended; ended registrations stay listed.
3. **How your prices are listed.**
- *Add tax at checkout* (the default): your prices are before tax. The shopper sees subtotal, sales tax and total, and pays the total.
- *Prices include tax*: the total does not change; OnCharge works out how much of it is tax.
4. **Product categories.** A default category for your store (General goods unless you change it), and a category per product id for products taxed differently (clothing, groceries, digital goods, services, not taxable…).
## Where tax is calculated
| Where | When |
|---|---|
| Checkout sessions (API) | Only when the request asks: `tax.enabled: true`. Store plugins (WooCommerce, Magento, Wix…) usually add their own tax to the order total, so OnCharge does not add it again unless you ask. |
| Payment links | Every link of a store with sales tax on. Links that don't ask for a shipping address ask for the shopper's ZIP code and state. |
| Invoices | When you finalize an invoice whose lines have no tax rate of their own. Tax is added on top of the line prices and shown on the invoice, its page, PDF and emails. Needs the customer's address (or a shipping address). |
| Saved-card charges (API) | When the request asks: `tax.enabled: true`. |
Tax is calculated for where the order ships. When nothing ships, it uses the billing address you send (`tax.billing_address`) or, on a payment link, the shopper's ZIP code. It is calculated again whenever the address or the order changes, until the payment is made; then the amount is final.
## Create a taxed checkout session
```json
{
"amount": 5500,
"currency": "USD",
"reference": "cart-8812",
"return_url": "https://shop.example/thanks",
"shipping": { "line1": "1 Congress Ave", "city": "Austin", "state": "TX", "postal_code": "78701", "country": "US" },
"line_items": [
{ "description": "Mug", "quantity": 2, "amount_including_tax": 3000, "product_id": "MUG-1" },
{ "description": "Tea", "quantity": 1, "amount_including_tax": 2000, "tax_category": "groceries" }
],
"tax": { "enabled": true, "shipping_amount": 500 }
}
```
With `tax.enabled`, `amount` is the order as you list it, and the line items (each line's total in `amount_including_tax`) plus `tax.shipping_amount` must add up to it. The answer carries `amount`, what the shopper will pay, and a `tax` object:
```json
{
"session_id": "…",
"amount": 5954,
"tax": {
"status": "calculated",
"inclusive": false,
"currency": "USD",
"subtotal": 5500,
"amount": 454,
"total": 5954,
"shipping": 500,
"jurisdictions": [{ "state": "TX", "rate": "8.25", "amount": 454 }],
"refunded": 0,
"error": null
}
}
```
A cart session created before the order exists gets its tax when you attach the shipping address with `POST /api/v1/checkout/sessions/{id}/order`; that answer carries the new `amount` and `tax`.
## When tax can't be calculated
| Case | What happens |
|---|---|
| No address yet | The payment waits: checkout answers `tax_address_required` until the address is attached. |
| The address can't be placed (wrong ZIP code or state) | `tax_address_invalid`: creating the session answers 422, and checkout refuses the payment. Create a new session with a corrected address. |
| The calculation is briefly unavailable, tax added at checkout | `tax_unavailable`: the shopper is asked to try again. OnCharge never charges a total without its tax. |
| The calculation is briefly unavailable, prices include tax | The listed total is charged (it is right whatever the tax is) and the tax is worked out shortly after (`status: "pending"`). |
## Refunds and disputes
A refund gives back its share of the tax: a refund of a third of an order gives back a third of its tax (rounded half away from zero to the cent), and the last refund gives back whatever is left, so nothing is left over. A dispute you lose does the same. A dispute you win changes nothing.
## Where you see it
- **Webhooks:** payment, refund and chargeback events of a taxed payment carry `data.tax` (the object above).
- **API:** `GET /api/v1/checkout/sessions/{id}` and saved-card charges return `tax`; each entry of `GET /api/v1/payments` has `tax`, the tax inside its `amount` (negative for a refund's share).
- **Dashboard:** with sales tax on, the activity list and export have a Sales tax column after Net, and so does the itemized activity report. The accounting export moves the tax from Sales to a *Sales Tax Payable* account, and back with refunds and lost disputes.
- **Sales tax report** (Settings → Sales tax, with a CSV): per month and state, the taxable sales, tax collected, tax refunded and the net tax to file.
OnCharge's fee is on the amount before tax. Tax collected is paid out with the rest of the order, on the same terms (after carrier-confirmed delivery where that applies).
## Categories
`general_goods`, `nontaxable`, `services`, `electronic_services`, `clothing`, `software_download`, `saas`, `books`, `ebooks`, `music_download`, `dietary_supplements`, `otc_drugs`, `cosmetics`, `candy`, `groceries`, `prepared_food`, `pet_food`, `gift_cards`. Use them in `line_items[].tax_category`, or set them per product id in Settings → Sales tax.
---
# RUO compliance feed
Stores in OnCharge's research-use-only (RUO) programme are reviewed against the programme rules before payments are enabled, and again every day afterwards. A compliant RUO store keeps its catalogue behind a research-access gate, so OnCharge cannot read it as an anonymous visitor. The **compliance feed** is a small, read-only, signed API that your store serves so OnCharge can read the catalogue as a verified buyer would see it.
This page is only for RUO merchants. Other stores can skip it.
| Platform | How to serve the feed |
|---|---|
| WooCommerce | Install the **OnCharge Compliance Scanner** plugin. See [WooCommerce](https://oncharge.io/docs/woocommerce#ruo-compliance-scanner). |
| Next.js | `createComplianceFeedRoute` from `@oncharge/node/next`. See [below](#nextjs). |
| Magento 2 (beta) | Built into the [Magento module](https://oncharge.io/docs/magento): base path `/oncharge/compliance`. |
| Wix (beta) | Built into the [Wix integration](https://oncharge.io/docs/wix): base path `/_functions/onchargeCompliance`. |
| Anything else | Implement the three endpoints below, or use `createComplianceFeed` from `@oncharge/node`. |
## How it works
1. In the merchant portal, start a store connection for your store's host (for example `shop.example.com`), choose its platform and, for anything but WordPress, the feed's base path. The default is `/.well-known/oncharge-compliance`.
2. OnCharge shows a one-time **connection code** `occs_.`. Save it as a server secret (for example `ONCHARGE_COMPLIANCE_CODE`); it is not shown again.
3. Your store serves three `GET` endpoints on that host:
- ` /proof`: proves your server holds the code (ownership check).
- ` /content`: one page of published products and pages (signed requests only).
- ` /reviewer-access`: whether a reviewer login is ready (signed requests only).
4. In the portal, select **Verify connection**, then run a scan.
The endpoints must be served from the connected host itself (`https:// /…`), not a separate API domain, because answering from that host is what proves you control it. If your research gate or firewall blocks unknown visitors, allow these paths.
A base path is only a path on that host: one or more `/segment` parts made of `A-Z a-z 0-9 . _ ~ -`, with no `.` or `..` segment, no query, fragment, `%`, `\`, `@`, `:` or whitespace, no trailing slash, and at most 200 characters. WordPress stores use the plugin's REST routes instead (`https:///?rest_route=/oncharge-compliance-scanner/v1/`).
## Keys
From the code `occs_.`:
- `connection_id` is the UUID.
- `signing_key` is the lower-case hex SHA-256 of the UTF-8 `` (64 characters). Every HMAC below is HMAC-SHA256 **keyed with this 64-character string as ASCII bytes**, output in lower-case hex.
The strings that are signed always use the canonical routes `/oncharge-compliance-scanner/v1/content` and `/oncharge-compliance-scanner/v1/reviewer-access`, whatever URL you serve them at.
## `GET /proof?challenge=&ts=`
Not authenticated. Respond `200` with JSON and `Cache-Control: no-store`:
```json
{ "connection_id": "", "host": "shop.example.com", "proof": "", "plugin_version": "1.0.0" }
```
`proof = HMAC(signing_key, "oncharge-compliance-scanner.proof.v1|" + host + "|" + challenge + "|" + ts)`, where `host` is the host as configured in the portal. Respond `409` if no connection code is configured.
## `GET /content?cursor=&limit=`
Signed by OnCharge with these headers:
| Header | Value |
|---|---|
| `X-OnCharge-Scanner-Connection` | The connection UUID. |
| `X-OnCharge-Scanner-Timestamp` | Unix seconds. |
| `X-OnCharge-Scanner-Nonce` | 32 hex characters, single use. |
| `X-OnCharge-Scanner-Signature` | Hex HMAC below. |
Accept the request only if the connection ID matches, `|now - ts| <= 300`, the nonce was not seen in the last 10 minutes, and the signature equals (constant-time compare):
```text
HMAC(signing_key, "oncharge-compliance-scanner.content.v1|GET|/oncharge-compliance-scanner/v1/content|cursor=&limit=||")
```
Otherwise respond `401` (bad signature, clock skew, replay) or `409` (not connected). `cursor` starts at `0`; `limit` is at most `50`.
```json title="200 OK"
{
"plugin_version": "1.0.0",
"site": {
"name": "Example Research Supply",
"tagline": "Reference materials for laboratory research",
"home_url": "https://shop.example.com/",
"wc_active": false,
"terms_page_url": "https://shop.example.com/terms",
"privacy_policy_url": "https://shop.example.com/privacy",
"refund_page_url": "https://shop.example.com/refunds",
"shipping_page_url": "https://shop.example.com/shipping",
"contact_page_url": "https://shop.example.com/contact"
},
"items": [
{
"type": "product",
"id": 123,
"url": "https://shop.example.com/products/example-compound",
"title": "Example compound, 10 mg",
"content_html": "For laboratory research use only. Not for human or veterinary use.
",
"short_description_html": "",
"price_html": "$49.00",
"sku": "EX-10",
"meta_description": "",
"image_alts": ["Example compound vial"],
"categories": [{ "name": "Reference materials", "url": "https://shop.example.com/c/reference" }],
"tags": [],
"attributes": [{ "name": "Purity", "value": "≥99%" }],
"attachments": [{ "url": "https://shop.example.com/coa/ex-10-lot-123.pdf", "title": "COA lot 123", "mime": "application/pdf" }]
}
],
"next_cursor": 50,
"truncated": false
}
```
- `type` is `product`, `page` or `post`; `id` is a non-negative integer, unique per type.
- Serve every published product, **including products behind an age or research gate**, plus the pages with your terms, privacy policy, refunds, shipping, contact details and research-use statements. Never include drafts, private content, orders or customers.
- `next_cursor` is `null` on the last page. Serve at most 5,000 items in total and set `truncated: true` if there are more.
- Limits: titles 2,000 characters; HTML fields 250,000; at most 200 image alts; 100 categories, tags or attributes; 40 attachments per item.
## `GET /reviewer-access`
Signed like `content`, with the message:
```text
"oncharge-compliance-scanner.reviewer-access.v1|GET|/oncharge-compliance-scanner/v1/reviewer-access|||"
```
Card-network and payment reviewers must be able to see a gated catalogue. Create a dedicated, non-administrator reviewer account on your store with the same research access a verified buyer has, sign in as it once to confirm it sees products and prices, and give the login to OnCharge yourself (never through this endpoint). The endpoint only reports the status:
```json
{
"host": "shop.example.com",
"ready": true,
"account_exists": true,
"can_view_catalog": true,
"owner_confirmed": true,
"checked_at": 1700000000,
"nonce": "",
"signature": ""
}
```
`signature = HMAC(signing_key, "oncharge-compliance-scanner.reviewer-status.v1|" + host + "|" + b(ready) + "|" + b(account_exists) + "|" + b(can_view_catalog) + "|" + b(owner_confirmed) + "|" + checked_at + "|" + nonce)`, where `b(x)` is `1` or `0`. `ready` is true only when the other three are.
## Test vectors
`secret = "test-secret"`, so `signing_key = 9caf06bb4436cdbfa20af9121a626bc1093c4f54b31c0fa937957856135345b6`. With host `shop.example.com`, timestamp `1700000000` and nonce `0123456789abcdef0123456789abcdef`:
| Message | Expected HMAC |
|---|---|
| proof, challenge = 64 zeros | `ce6be291c7332d8c03841e376170ce56e1b8b3948b25e82fcfd74ab9ac60be80` |
| content, `cursor=0&limit=50` | `2d8b01d1ec2bb18d290360e8273dbaa3f668feb173f4febf1f37147e11ceaff3` |
| reviewer-access request | `e1c441bfc451e4d96111660dbacae2d6e2edae506cafa41d2e0c58bbc723f85c` |
| reviewer status, all `1`, `checked_at=1700000000` | `6f18051e96fbb2085ad6f859bfce11ca039ffee5c2ba0bc661e63bcea55bec9f` |
Add these to your unit tests.
## Reference implementation (any JavaScript runtime)
A dependency-free handler using the standard `Request`/`Response` API (Node 18+, Next.js, Remix, Hono, Cloudflare Workers, Bun, Deno). Route every request under your base path to it.
```js title="compliance-feed.mjs" test="ruo-node"
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
const CONTENT_ROUTE = '/oncharge-compliance-scanner/v1/content';
const REVIEWER_ROUTE = '/oncharge-compliance-scanner/v1/reviewer-access';
const VERSION = '1.0.0';
const hmac = (key, message) => createHmac('sha256', key).update(message, 'utf8').digest('hex');
const sameHex = (a, b) => typeof b === 'string' && /^[0-9a-f]{64}$/.test(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b));
const json = (status, body) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });
export function parseConnectionCode(code) {
const m = /^occs_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.([A-Za-z0-9_-]{43})$/.exec(String(code ?? '').trim());
if (!m) return null;
return { connectionId: m[1], signingKey: createHash('sha256').update(m[2], 'utf8').digest('hex') };
}
export const proofSignature = (key, host, challenge, ts) => hmac(key, `oncharge-compliance-scanner.proof.v1|${host}|${challenge}|${ts}`);
export const reviewerStatusSignature = (key, s) =>
hmac(key, ['oncharge-compliance-scanner.reviewer-status.v1', s.host, +s.ready, +s.account_exists, +s.can_view_catalog, +s.owner_confirmed, s.checked_at, s.nonce].join('|'));
/**
* options.connectionCode the occs_… code (server secret)
* options.host the host exactly as connected, e.g. "shop.example.com"
* options.site { name, tagline, home_url, terms_page_url, … }
* options.listItems async ({ cursor, limit }) => ({ items, nextCursor, truncated? })
* options.reviewerAccess async () => ({ accountExists, canViewCatalog, ownerConfirmed })
* options.nonceStore { claim(nonce, ttlSeconds) } → false if already seen; use a shared store (Redis, database) when you run several instances
*/
export function createFeedHandler(options) {
const seen = new Map();
const nonces = options.nonceStore ?? {
claim(nonce, ttlSeconds) {
if ((seen.get(nonce) ?? 0) > Date.now()) return false;
seen.set(nonce, Date.now() + ttlSeconds * 1000);
return true;
},
};
return async function handle(request) {
const conn = parseConnectionCode(options.connectionCode);
if (!conn) return json(409, { error: 'not_connected' });
const url = new URL(request.url);
const endpoint = url.pathname.replace(/\/+$/, '').split('/').pop();
if (endpoint === 'proof') {
const challenge = url.searchParams.get('challenge') ?? '';
const ts = url.searchParams.get('ts') ?? '';
if (!/^[0-9a-f]{64}$/.test(challenge) || !/^\d+$/.test(ts)) return json(400, { error: 'bad_request' });
return json(200, { connection_id: conn.connectionId, host: options.host, proof: proofSignature(conn.signingKey, options.host, challenge, ts), plugin_version: VERSION });
}
// Signed endpoints
const h = (name) => request.headers.get(name) ?? '';
const ts = h('X-OnCharge-Scanner-Timestamp');
const nonce = h('X-OnCharge-Scanner-Nonce');
if (h('X-OnCharge-Scanner-Connection') !== conn.connectionId) return json(401, { error: 'unauthorized' });
if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return json(401, { error: 'unauthorized' });
if (!/^[0-9a-f]{32}$/.test(nonce)) return json(401, { error: 'unauthorized' });
let message;
if (endpoint === 'content') {
const cursor = url.searchParams.get('cursor') ?? '';
const limit = url.searchParams.get('limit') ?? '';
message = `oncharge-compliance-scanner.content.v1|GET|${CONTENT_ROUTE}|cursor=${cursor}&limit=${limit}|${ts}|${nonce}`;
} else if (endpoint === 'reviewer-access') {
message = `oncharge-compliance-scanner.reviewer-access.v1|GET|${REVIEWER_ROUTE}||${ts}|${nonce}`;
} else {
return json(404, { error: 'not_found' });
}
if (!sameHex(hmac(conn.signingKey, message), h('X-OnCharge-Scanner-Signature'))) return json(401, { error: 'unauthorized' });
if (!(await nonces.claim(nonce, 600))) return json(401, { error: 'unauthorized' }); // replay
if (endpoint === 'content') {
const cursor = Math.max(0, parseInt(url.searchParams.get('cursor') ?? '0', 10) || 0);
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit') ?? '50', 10) || 50));
const page = await options.listItems({ cursor, limit });
return json(200, { plugin_version: VERSION, site: options.site, items: page.items, next_cursor: page.nextCursor ?? null, truncated: Boolean(page.truncated) });
}
const r = options.reviewerAccess ? await options.reviewerAccess() : {};
const status = {
host: options.host,
ready: Boolean(r.accountExists && r.canViewCatalog && r.ownerConfirmed),
account_exists: Boolean(r.accountExists),
can_view_catalog: Boolean(r.canViewCatalog),
owner_confirmed: Boolean(r.ownerConfirmed),
checked_at: Math.floor(Date.now() / 1000),
nonce,
};
return json(200, { ...status, signature: reviewerStatusSignature(conn.signingKey, status) });
};
}
```
## With the Node SDK
```ts title="Any framework"
import { createComplianceFeed } from '@oncharge/node';
const feed = createComplianceFeed({
connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
host: 'shop.example.com',
site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
listItems: async ({ cursor, limit }) => loadPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
reviewerAccess: async () => ({ accountExists: true, canViewCatalog: true, ownerConfirmed: true }),
});
// feed.handle(request: Request): Promise
```
### Next.js
```ts title="app/.well-known/oncharge-compliance/[route]/route.ts"
import { createComplianceFeedRoute } from '@oncharge/node/next';
export const dynamic = 'force-dynamic';
export const { GET } = createComplianceFeedRoute({
connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
host: 'shop.example.com',
site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/' },
listItems: async ({ cursor, limit }) => loadPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
});
```
> **Coming soon.** `@oncharge/node` is not yet on npm. Until it is, use the reference implementation above: in Next.js, `export async function GET(request) { return handle(request); }` in the same route file.
## Content rules
The feed exists so OnCharge sees exactly what your buyers see. It must be read-only and must not hide, rewrite or add content for OnCharge. The scan checks your product pages, documents and policies against the RUO programme rules, for example: only approved products, original and accurate certificates of analysis (COAs), and product descriptions without human-use or health-benefit claims. Your onboarding contact can share the full rule list.
---
# Site check bot
When a business applies to take payments with OnCharge, OnCharge checks its website: what it sells, its policy pages and support contact details, and, for research-use-only (RUO) stores, the claims its pages, posts and product descriptions make and whether the OnCharge shopper gate covers the store. The check runs when you move past the step where you enter your website in onboarding, when you submit your application, whenever you choose **Scan again**, and during periodic reviews. This page describes the bot so you can recognise it, verify it and let it through your firewall.
## How to recognise it
- **User agent:** `OnchargeUnderwritingBot/1.0 (+https://oncharge.io)`. Match on the token `OnchargeUnderwritingBot`.
- **Signed requests:** requests to your store carry an `OnCharge-Scan` header that proves they come from OnCharge. See [Verify a request](#verify-a-request).
- **What it reads:** pages an anonymous visitor can open, with `GET` and `HEAD` only, and your store's public feeds: `robots.txt` and the sitemaps it lists, the WooCommerce Store API (`/wp-json/wc/store/v1/products`), Shopify's `/products.json`, WordPress posts and pages (`/wp-json/wp/v2/posts`, `/wp-json/wp/v2/pages`) and your RSS feed (`/feed/`). It never submits forms, adds to a cart, signs in or pays.
- **Pace:** one page at a time with a pause between requests (up to about 120 requests a minute) and at most about 60 pages per check. A check takes under a minute.
- **IP addresses:** the check runs on cloud infrastructure and has no fixed IP addresses. Allow it by user agent and, where your firewall supports it, by the signed header, not by IP address.
## What the check looks for
- Products OnCharge cannot support, or can support only in a specific programme.
- Terms, privacy, refund, shipping and contact pages, and a support email address or phone number.
- For research-use-only stores:
- claims of the kinds FDA cites in warning letters to research-use-only sellers: human-use language, dosing and administration, clinical or human-study results presented as benefits, disease and treatment claims, weight-loss, muscle, libido and tanning claims, comparisons with approved drugs and "pharmaceutical grade", and personal-use testimonials;
- compounds the programme excludes, including products renamed with codes whose addresses give the compound away;
- the [OnCharge shopper gate](#the-oncharge-shopper-gate) covering the store.
Onboarding shows each finding with the page, the passage, the rule and how to fix it. Fix them on your site, then choose **Scan again**: the automatic decision always uses the latest check.
## Verify a request
A user agent can be copied. To be sure a request comes from OnCharge, check its signature:
```
OnCharge-Scan: v=1; t=; kid=; sig=
```
1. Read the `;`-separated `name=value` pairs. Whitespace around them is allowed, their order is free and unknown names are ignored. A name given twice, or a part without `=`, makes the header invalid. `v` must be `1`.
2. Reject the request if `t` is more than 300 seconds away from your server's clock.
3. Build the signed message (UTF-8): `"v1\n" + t + "\n" + host + "\n" + pathAndQuery`. `host` is the request's `Host` in lower case without a trailing dot, with the port only when it is not the scheme's default (443 for HTTPS, 80 for HTTP). `pathAndQuery` is the request target exactly as received: the raw path (percent-encoding as sent, `/` when empty), then `?` and the query when the query is not empty.
4. Fetch the public keys from `https://app.oncharge.io/.well-known/oncharge-scan-keys.json`, a JSON Web Key Set of Ed25519 keys (`kty` `OKP`, `crv` `Ed25519`), and take the key whose `kid` matches. Cache the file for up to an hour, and refetch it at most once every five minutes when a request names a key you do not have.
5. `sig` is the Ed25519 signature in base64url without padding (86 characters). Verify it over the message with that key.
Node.js (18 or later):
```js
import { createPublicKey, verify } from 'node:crypto';
const KEYS_URL = 'https://app.oncharge.io/.well-known/oncharge-scan-keys.json';
let cache = { at: 0, tried: 0, keys: null };
async function loadKeys() {
cache.tried = Date.now();
try {
const res = await fetch(KEYS_URL, { signal: AbortSignal.timeout(3000) });
const body = res.ok ? await res.json() : null;
if (Array.isArray(body?.keys)) cache = { ...cache, at: Date.now(), keys: body.keys };
} catch {
// Keep the keys already held.
}
}
async function scanKey(kid) {
const find = () => (cache.keys ?? []).find((k) => k.kid === kid && k.kty === 'OKP' && k.crv === 'Ed25519');
const stale = Date.now() - cache.at > 3_600_000;
// Fetch when the copy is over an hour old or lacks this key, at most once every five minutes.
if ((stale || !find()) && Date.now() - cache.tried > 300_000) await loadKeys();
return find() ?? null;
}
function signedHost(host, scheme) {
const match = String(host ?? '').trim().toLowerCase().match(/^(\[[^\]]+\]|[^:]*)(?::(\d+))?$/);
if (!match) return '';
const name = match[1].replace(/\.$/, '');
const port = match[2] ?? '';
const isDefault = (scheme === 'https' && port === '443') || (scheme === 'http' && port === '80');
return port && !isDefault ? `${name}:${port}` : name;
}
function signedTarget(target) {
let value = String(target ?? '').split('#')[0];
if (value.startsWith('?')) value = `/${value}`;
if (value.endsWith('?')) value = value.slice(0, -1);
return value || '/';
}
/**
* True when the OnCharge-Scan header is valid for this request.
* host: the Host header. target: the raw request target (path and query as received).
* scheme: 'https' or 'http', as the request arrived.
*/
export async function isOnChargeScan(header, host, target, scheme = 'https') {
const params = new Map();
for (const piece of String(header ?? '').split(';')) {
const part = piece.trim();
if (!part) continue;
const at = part.indexOf('=');
if (at <= 0) return false;
const name = part.slice(0, at).trim().toLowerCase();
if (params.has(name)) return false;
params.set(name, part.slice(at + 1).trim());
}
const t = params.get('t') ?? '';
const kid = params.get('kid') ?? '';
const sig = params.get('sig') ?? '';
if (params.get('v') !== '1' || !/^\d{1,12}$/.test(t) || !kid || !/^[A-Za-z0-9_-]{86}$/.test(sig)) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - Number(t)) > 300) return false;
const jwk = await scanKey(kid);
if (!jwk) return false;
try {
const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, format: 'jwk' });
const message = `v1\n${t}\n${signedHost(host, scheme)}\n${signedTarget(target)}`;
return verify(null, Buffer.from(message, 'utf8'), key, Buffer.from(sig, 'base64url'));
} catch {
return false;
}
}
```
Call it with the `OnCharge-Scan` header, the `Host` header, the raw request target and the scheme (for example `req.headers.host`, `req.originalUrl` and `req.protocol` in Express, with `trust proxy` set when TLS ends at a proxy).
## The OnCharge shopper gate
Research-use-only stores keep their catalogue behind the OnCharge shopper gate: shoppers sign in and accept the research-use terms before they see products or prices. The check looks for the gate's markers on the pages it reads (``, an element with `data-oncharge-gate="v1"`, the gate script or frame from `app.oncharge.io/gate/v1/`, or an `OnCharge-Gate: v1` response header). The gate checks the `OnCharge-Scan` signature itself and shows the check your store as a visitor who has passed the gate would see it, so you do not need a firewall exception for the gate.
## Let the check through your firewall
If the check meets a security challenge or block page, onboarding names the firewall it found and shows that firewall's steps, which are the same as below. Every exception should only switch off bot detection, JavaScript or captcha challenges and rate limiting for the check: keep injection and attack rules on, because a user agent can be copied. Then choose **Scan again** in onboarding.
### Cloudflare
1. In the Cloudflare dashboard, open your domain and go to Security > Security rules > Create rule > Custom rules.
2. Use the expression (http.user_agent contains "OnchargeUnderwritingBot"). To be stricter, add: and len(http.request.headers["oncharge-scan"]) > 0
3. Under Choose action, pick Skip and tick All Super Bot Fight Mode rules, All rate limiting rules and Browser Integrity Check. Tick All remaining custom rules only if your own rules block bots. Put the rule first, then Deploy.
4. If Bot Fight Mode is on, turn it off under Security > Settings (filter by Bot traffic).
5. If Under Attack mode is on, turn it off in your domain's Overview (Quick Actions), or add a configuration rule (Rules > Overview > Create rule > Configuration Rule) with the same expression that sets I'm Under Attack off.
Note: Bot Fight Mode runs outside your rules: Skip, Bypass and Allow have no effect on it, and only an IP address rule can exempt a visitor. Our check has no fixed IP addresses, so Bot Fight Mode has to be off. Super Bot Fight Mode (Pro and above) can be skipped by the rule above.
Cloudflare documentation: https://developers.cloudflare.com/waf/custom-rules/skip/
### Vercel Firewall
1. In Vercel, open the project that serves your store and go to Firewall, then Configure > Add New > Rule.
2. Condition: User Agent, Contains, "OnchargeUnderwritingBot". To be stricter, add AND Request Header "OnCharge-Scan", Exists.
3. Then: Bypass. Save the rule and move it above any Deny or Challenge rule.
4. Choose Review Changes > Publish.
5. If Attack Mode is on, disable it from the Firewall menu while the check runs (it also switches itself off after the time you chose).
Note: Bypass skips your custom rules and the Bot Protection and AI Bots rulesets, but not Vercel's platform DDoS mitigations. If the check is still blocked with Attack Mode off, ask Vercel support.
Vercel Firewall documentation: https://vercel.com/docs/vercel-firewall/vercel-waf/custom-rules
### Bunny Shield
1. In the bunny.net dashboard, go to CDN, select your pull zone, then Edge Rules > Add Edge Rule.
2. Condition: Request Header, User-Agent, matching "\*OnchargeUnderwritingBot\*".
3. Actions: Disable Shield Bot Detection, Disable Shield Challenge and Disable Shield Rate Limiting. Add Disable Shield Access Lists only if you block countries or networks. Do not use Disable WAF or Disable Shield.
4. Save the rule. Bunny Shield's event logs show whether a request was still blocked.
Note: Bunny Shield's own WAF rules can only block, log or challenge, and its access lists match IP addresses, networks and countries only, so the edge rule is the way to let the check through.
Bunny Shield documentation: https://bunny.net/docs/cdn/edge-rules/
### Sucuri Website Firewall
1. In the Sucuri dashboard, open the Website Firewall for your site and go to Access Control > Block User Agents. Remove any entry that matches the check.
2. Under Security, turn off Enable Emergency DDOS protection unless you are under attack: it blocks every visitor without JavaScript except major search engines.
3. Under Audit Trails, find the blocked request and note its Block ID.
4. Open a support ticket asking Sucuri to allowlist the user agent "OnchargeUnderwritingBot", and include the Block ID.
Note: Sucuri has no user-agent allowlist in its dashboard. Allow URL Paths opens a path to every visitor and does not skip JavaScript challenges.
Sucuri Website Firewall documentation: https://docs.sucuri.net/website-firewall/configuration/security-options/
### Wordfence
1. In WordPress, go to Wordfence > Tools > Live Traffic, find the requests from "OnchargeUnderwritingBot" and read why they were blocked.
2. Go to Wordfence > Firewall > Blocking and delete any Custom Pattern rule whose Browser User Agent matches the check (for example \*bot\*).
3. Go to Wordfence > Firewall > All Firewall Options > Rate Limiting. Set "If anyone's requests exceed" and "If a crawler's page views exceed" to Unlimited, or at least 240 per minute with throttle, and raise "If a crawler's pages not found (404s) exceed".
4. Check that "Immediately block IPs that access these URLs" lists none of your store's pages, then Save Changes.
Note: Wordfence cannot allowlist a user agent, only IP addresses and a fixed list of services, and our check has no fixed IP addresses. Its rate limits count per IP address; the check makes up to about 120 requests a minute.
Wordfence documentation: https://www.wordfence.com/help/firewall/rate-limiting/
### Akamai
1. In Akamai Control Center, open the security configuration that protects your site (this needs Bot Manager).
2. Create a custom bot category, and add a custom-defined bot to it with a Request Header condition: User-Agent matches "\*OnchargeUnderwritingBot\*".
3. In the security policy's Bot Management settings, set that category's action to Allow (or Monitor).
4. Save and activate the configuration, on staging first and then production.
5. If App & API Protector still denies the check, look up the "Reference #" from the block page in Akamai's error translator and add an exception, or ask your Akamai account team.
Note: Akamai's own guides need a sign-in, so these menu names come from partner guides and may differ in your account. Your Akamai account team can make the change for you.
### Fastly Next-Gen WAF
1. In manage.fastly.com, go to Security > Next-Gen WAF > Rules, choose the workspace and Add workspace rule (in the older console: Rules > Site Rules > Add site rule).
2. Type: Request. Condition: User agent, Contains, "OnchargeUnderwritingBot". To be stricter, add AND Request header "OnCharge-Scan", Exists.
3. Action: Allow. Save the rule.
4. If you also use Fastly Bot Management, check its logs: it verifies bots by IP address, and our check has no fixed IP addresses.
Note: An Allow rule overrides blocking rules. Fastly does not document whether it also overrides rate limits and Bot Management challenges.
Fastly Next-Gen WAF documentation: https://www.fastly.com/documentation/guides/next-gen-waf/rules/working-with-request-rules/
### AWS WAF
1. In the AWS WAF console, open the web ACL (protection pack) attached to your CloudFront distribution or load balancer, and go to its rules.
2. Edit the Bot Control rule group (AWSManagedRulesBotControlRuleSet) and add a scope-down statement: NOT (header "user-agent" contains "OnchargeUnderwritingBot").
3. Add the same scope-down to your rate-based rules and to the Anonymous IP list rule group, whose HostingProviderIPList rule blocks requests from cloud providers.
4. Save, then check the logs' terminatingRule field to confirm the check is no longer stopped.
Note: An Allow rule ranked above the managed rule groups also works, but it skips every later rule, including the core attack rules, so the scope-down is narrower. Bot Control's targeted level challenges clients without a browser token, which our check cannot pass.
AWS WAF documentation: https://docs.aws.amazon.com/waf/latest/developerguide/waf-bot-control-example-user-agent-exception.html
### Netlify
1. In Netlify, go to Project configuration > Security > Firewall traffic rules and make sure the baseline and country rules do not block the check. These rules match only IP addresses and locations.
2. Under Project configuration > Security > Rate limiting, make sure no rule limits the check. On Enterprise you can add a Header condition that leaves out its user agent.
3. If you use Netlify's Web Application Firewall (Enterprise), set the rule that matches the check to Log, or add an exclusion.
4. If a User Agent Blocker extension or your own edge function blocks bots, allow "OnchargeUnderwritingBot" there.
Note: Netlify has no user-agent allow rule. Its platform DDoS protection is handled by Netlify support.
Netlify documentation: https://docs.netlify.com/manage/security/secure-access-to-sites/traffic-rules/
### Imperva
1. In the Imperva Cloud Security Console, open your website's Bot Access Control settings.
2. Add an exception for the user agent "OnchargeUnderwritingBot/1.0 (+https://oncharge.io)".
3. If the check is still challenged, turn off Challenge suspected bots and keep Block bad bots on.
4. If DDoS protection is set to always on, switch it to automatic or adaptive, or ask Imperva support: DDoS exceptions cannot match a user agent.
Note: Imperva's guides need a browser session to read, so menu names may differ in your console. Advanced Bot Protection is a separate product: ask Imperva to allow the user agent there.
### Kinsta
1. In MyKinsta, go to Sites, select your site and open Bot protection.
2. Under Exceptions, add: Allow, User agent, "OnchargeUnderwritingBot".
3. If the check is still challenged, set Protection level to Block malicious traffic (the default): the Block automations, Challenge bots and Challenge everyone levels stop it.
4. Exceptions are set per environment, so add it to each environment the check visits. For rules Kinsta manages, contact Kinsta Support.
Note: Bot protection is not available when your site sits behind another CDN or proxy; follow that provider's steps instead.
Kinsta documentation: https://kinsta.com/docs/wordpress-hosting/mykinsta-tools/wordpress-tools-bot-protection/
### WP Engine
1. In the WP Engine User Portal, go to Sites, select the environment and open Web Rules (it may be under Advanced).
2. Delete any Deny access rule with a User-Agent header condition that matches the check.
3. Open a support ticket asking WP Engine to exempt the user agent "OnchargeUnderwritingBot" from Global Edge Security bot rules and platform rate limits. Include the addresses, times and cf-ray values of blocked requests.
Note: A Web Rules Allow rule only lifts IP addresses denied by another rule, so blocks at the platform level need WP Engine support.
WP Engine documentation: https://wpengine.com/support/web-rules-engine/
### SiteGround
1. SiteGround's anti-bot system has no setting in Site Tools that lets a service through.
2. Contact SiteGround Support with the service name (OnCharge site check), your site's address, the user agent "OnchargeUnderwritingBot" and the times the check ran. There is no fixed IP address to give them.
3. Run the check again once they confirm.
Note: Only search engine crawlers are exempt; other automated visitors can be shown the robot challenge.
SiteGround documentation: https://www.siteground.com/kb/seeing-captcha-website/
### Any other firewall
1. Find the firewall: run curl -sI -A "OnchargeUnderwritingBot/1.0 (+https://oncharge.io)" followed by your store's address. The response headers usually name the vendor. Then find the request in the firewall's security or event log and note which rule stopped it.
2. Add an exception (Allow, Skip, Bypass or Exclude) for requests whose User-Agent contains "OnchargeUnderwritingBot". To be stricter, also require the request header "OnCharge-Scan" to be present. Limit it to bot detection, JavaScript or captcha challenges and rate limiting, and keep injection and attack rules on.
3. Place it before any blocking rule, then publish or activate it.
4. If your firewall can only allow IP addresses or verified bots, pause its bot challenge or "under attack" feature while the check runs, or ask the vendor's support to allow the user agent. Our check has no fixed IP addresses.
5. Run the curl command again and expect a 200 with no challenge, then run the check again.
---
# Risk engine
Every OnCharge checkout is screened before the card is submitted. The checkout page collects signals, OnCharge scores the attempt from 0 (low risk) to 100 (high risk), and your store's risk policy decides whether the payment goes ahead, needs an extra step, or is blocked. You do not need to integrate anything for screening to run; this page explains what happens and how to tune it.
## Signals
| Signal | What it looks at |
|---|---|
| Bot check | An invisible browser challenge score on the checkout page. |
| IP intelligence | VPN, Tor, proxy and data-centre (hosting) networks; IP country. |
| Email check | Invalid and disposable email addresses. |
| Phone check | Invalid numbers and VoIP lines. |
| Automation flags | Headless browsers and automation tools. |
| Timing | Checkouts completed faster than a person could. |
| Velocity | Attempts from the same IP or email in the last 5 minutes, hour and day. |
| Network reputation | Payment, refund and chargeback history of the same email or phone across OnCharge merchants (identifiers are stored only as keyed hashes). |
## Decisions
| Decision | What happens |
|---|---|
| `allow` | The payment goes ahead. |
| `step_up` | The shopper completes extra steps first, such as an SMS code, accepting terms, a signature or 3-D Secure. |
| `review` | Treated as a step-up; an SMS code is required if your policy says so. |
| `deny` | The payment is blocked with a generic message. |
With the default thresholds, a score of 30 or less is allowed, 31 to 59 is `review`, 60 to 79 is a step-up with an SMS code (or `review` if `require_otp_on_review` is off), and 80 or more is denied. Some signals decide directly, whatever the score: by default a headless browser is denied, and VPN or Tor traffic, data-centre networks and disposable emails get a step-up.
**Monitor vs. enforce.** In `monitor` mode (the default) every decision is recorded but payments are never blocked by the score; use it to see what the engine would do. Switch to `enforce` when you are happy with the results.
## Shared blocklist
When a shopper is banned (for example after a chargeback), their email and phone are blocked across OnCharge. A session created for a banned shopper fails with `403 global_ban`, and the `message` is safe to show the shopper. Identifiers are stored only as keyed hashes; the shopper is never told which store or reason caused the ban.
## Your store's policy
Read and change the policy with the API ([`GET`](https://oncharge.io/docs/api#getriskpolicy) and [`PUT /api/v1/risk/policies`](https://oncharge.io/docs/api#updateriskpolicy)):
```json title="Default policy"
{
"mode": "monitor",
"thresholds": { "score_allow": 30, "score_review": 60, "score_deny": 80 },
"step_up_rules": {
"require_otp_on_review": true,
"require_signature": true,
"require_terms": true,
"force_3ds_above": 70
},
"blocks": {
"vpn_tor": "step_up",
"datacenter_asn": "step_up",
"disposable_email": "step_up",
"voip_phone": "allow",
"high_risk_countries": [],
"headless_browser": "deny"
},
"velocity_limits": { "ip_5m": 5, "ip_1h": 15, "ip_24h": 50, "email_5m": 3, "email_1h": 10, "email_24h": 30 }
}
```
- Each section you send to `PUT` replaces that section; sections you leave out stay as they are.
- Thresholds must satisfy `score_allow < score_review < score_deny`.
- `blocks` values are `allow`, `step_up` or `deny`; `high_risk_countries` takes ISO country codes.
Before changing the policy, replay a past decision under the new policy with [`POST /api/v1/risk/simulate`](https://oncharge.io/docs/api#simulateriskpolicy). Nothing is saved.
## Decisions and feedback
- [`GET /api/v1/risk/decisions`](https://oncharge.io/docs/api#listriskdecisions) lists decisions (filter by `from`, `to`, `decision`; paginate with `limit` and `offset`).
- [`GET /api/v1/risk/decisions/{id}`](https://oncharge.io/docs/api#getriskdecision) returns one decision with its reasons, a short explanation and its outcome label.
- [`POST /api/v1/risk/feedback`](https://oncharge.io/docs/api#sendriskfeedback) tells OnCharge how an order turned out (`fraud_confirmed`, `false_positive`, `legitimate`, `chargeback`), which improves future scoring.
The session's `risk_decision` (`accept`, `review` or `reject`) and `risk_score` are also on [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession).
---
# Crypto payments plugin (WooCommerce)
**OnCharge Crypto Payments** (version 1.5.0) adds OnCharge's Crypto payments and Card to Crypto (card, Cash App and Venmo) to WooCommerce: four payment methods and pays each one out to your own wallet, in USDC on Polygon, as soon as it settles. No OnCharge account, application or API key is needed. With an OnCharge account you can also [see every payment in your dashboard](#dashboard).
| Method | How the customer pays |
|---|---|
| **OnCharge Card** | Debit or credit card on a licensed card checkout page, opened in a new tab. |
| **OnCharge Cash App** | Cash App, on a payment page shown in your checkout (with a link to open it separately). |
| **OnCharge Venmo** | Venmo, on a payment page shown in your checkout (with a link to open it separately). |
| **OnCharge Crypto** | The customer picks a coin and network (40+ options, including BTC, ETH, SOL, USDT and USDC), then pays the exact amount shown, with a QR code and copy buttons. |
Every payment is converted to native USDC on Polygon and split in one transaction: **91% to your wallet, 8% to OnCharge, 1% network gateway fee.** Provider, exchange and network fees are additional. The 8% is enforced by the plugin's payment service and has no merchant setting.
**Requirements:** WooCommerce 8.0+, PHP 8.1+, a store priced in **USD**, and a Polygon wallet you control. Classic checkout, Checkout Blocks and High-Performance Order Storage (HPOS) are supported. Order totals from **$2.00 to $50,000**.
## Install
1. Download the plugin: [oncharge.io/downloads/oncharge-crypto-payments.zip](https://oncharge.io/downloads/oncharge-crypto-payments.zip).
2. In WordPress, go to **Plugins → Add New → Upload Plugin**, choose the ZIP, then **Install Now** and **Activate**.
```bash title="Or with WP-CLI"
wp plugin install https://oncharge.io/downloads/oncharge-crypto-payments.zip --activate
```
### Updates {#updates}
From version 1.3.0 the plugin updates itself: WordPress checks OnCharge for new versions and installs them in the background. Every update is signed with OnCharge's update key, and its checksum is verified before it is installed, so a changed or unsigned package is refused. Automatic updates are on by default. To install updates yourself instead, select **Disable auto-updates** next to the plugin on the **Plugins** screen; WordPress then shows each update for you to install.
Sites on 1.2.0 or earlier install 1.3.0 by hand once, by uploading the ZIP above and choosing **Replace current with uploaded**. Later versions arrive on their own.
## Configure
Go to **WooCommerce → Settings → Payments**. Each method is its own payment method with its own switch, so you offer only the ones you want.
| Setting | Value |
|---|---|
| Enable | Tick to show the method at checkout. Off by default. |
| Title | What shoppers see. |
| Your Polygon USDC wallet | A `0x…` address you control. Set it **separately for each method** you enable. |
Use a self-custodial wallet. Exchange deposit addresses are not recommended.
## See your payments in OnCharge {#dashboard}
Connect the plugin to your OnCharge account to list its payments in the dashboard, with what reached your wallet and a link to each payout transaction. The plugin works the same without it.
1. In the OnCharge dashboard, open **Payments → Card to Crypto** and select **Create plugin key** for your store. Copy the key: it is shown once. No verification is needed.
2. In WordPress, open **WooCommerce → OnCharge**, paste the key and select **Connect**. The page confirms the store it connected to.
Payments made after you connect appear within seconds, with their status (paid, needs review, waiting or not paid), the method the customer used, the amount, the USDC paid to your wallet and the Polygon payout transaction. Export them as CSV for your records. Earlier payments are not added.
- The key only adds this site's payments to your store's list: it cannot read data or move money. Revoke it in the dashboard at any time, and create a new one.
- No customer names or email addresses are sent with it. Each record keeps the order number, amount, method, payout wallet and transaction.
- These payments are already in your wallet, so they never appear in your OnCharge balance, payouts or fees.
### Automatic safeguards {#safeguards}
- **Sanctions screening.** The payout wallet is checked against the OFAC sanctions list before each payment is set up. A listed wallet is refused, with or without a key, and a key used with it is switched off.
- **New-store limits.** For a store's first 30 days, a connected store takes up to $500 per card, Cash App or Venmo payment and $2,000 of them in any 24 hours. A payment over that is declined at checkout, and the customer can pay the same order with crypto ([see below](#declined)). Crypto payments have no limit.
- **Automatic pause.** If several of a store's recent card payments could not be verified when they were paid out, its Card to Crypto pauses for seven days and turns back on by itself. The dashboard shows why and until when.
## Switch between Cash App, Venmo and card
Cash App, Venmo and card share one payment for the order: the same deposit wallet and amount. On the payment page they appear as tabs, and every page loads at once, so the Cash App and Venmo QR codes are ready before the customer switches:
- The method the customer chose shows first. Venmo's page loads immediately; Cash App's native invoice is prepared in the background, once per order.
- Switching keeps the same order and records the new method on it. Changing method at checkout (on the order's pay page) reuses the same payment too.
- Card opens a secure card page in a new tab.
- Checkout preconnects to the payment pages while the customer fills in the form, so the frames open faster.
- From 1.4.0 card, Cash App and Venmo pages open on OnCharge's checkout host, `ccheckout.oncharge.io`. One page keeps its own name: Cash App's native invoice (the QR code customers scan) is served by Cash App's payment partner on its own host and cannot be renamed. From 1.5.0 the plugin accepts only OnCharge's checkout host for the other pages.
Switching is offered between methods you have enabled that pay out to the **same wallet**. A customer should pay once: a payment through any of them completes the order.
## How checkout works
1. At **Place order**, the plugin saves a private payment session for the order and opens the payment step. Each payment window lasts 20 minutes.
2. The customer pays with the method they chose. Card, Cash App and Venmo need the billing email.
3. The order is marked paid only after a signed confirmation that **both** transfers (91% to you and 8% to OnCharge) reached their wallets in native USDC on Polygon, with at least 64 confirmations. The plugin checks from the payment callback, a background job and the payment page itself.
A payment that does not prove both transfers stays unpaid or **on hold** for review, and one transaction can complete only one order. Browser events never mark an order paid.
## When OnCharge declines a payment {#declined}
OnCharge can decline a payment before it is set up: a Card to Crypto payment (card, Cash App or Venmo) while the store's Card to Crypto is paused or when it is over a new store's limits ([safeguards](#safeguards)), or any payment whose payout wallet cannot be used with OnCharge. From 1.5.0 the customer does not have to start again:
- **Same order, same total.** After a declined card, Cash App or Venmo payment, checkout says why and offers your Crypto method for the same order, if you have it enabled. The order's pay page shows only the methods still allowed.
- **Never charged twice.** OnCharge declines before it sets up a payment, so a declined attempt has nothing to pay and the customer is told they have not been charged. Only OnCharge's explicit answer counts as a decline: a timeout or other error keeps the order on its method and asks the customer not to pay again, as before. If an earlier attempt for the order went unanswered, that attempt may have set up a payment, so a later decline offers nothing else: the customer is asked not to pay again, and the order note asks you to check the order.
- **Same total.** The other method pays the total the order had when it was declined. If the order has changed since, the customer is asked to contact the store.
- **Declines are kept.** The declined method, and any method the decline does not allow, is not offered again for that order, also on its pay page. Once the customer starts paying another way, the order stays on that method.
- **Declined wallet.** A payout wallet that cannot be used with OnCharge is declined for every method, so no OnCharge method is offered for that order. The order note asks you to set a different wallet under **WooCommerce → Settings → Payments**.
Each decline is recorded in the order notes, with what was declined and what the customer can use instead.
## What your customers see
Hosted card and app pages may open in a new tab, and providers can ask the customer to verify their identity. If a payment is short or under review, the order stays on hold: ask the customer not to pay again while you check it.
The checkout shows a small OnCharge mark with a link to the plugin page.
## Refunds
Payouts reach your own wallet, so you send refunds yourself from that wallet. The plugin never starts automatic refunds or second payments.
## Need more methods?
For Apple Pay, Google Pay and the other methods on the hosted checkout, or for 100+ coins paid out in the same coin, use the [Gateway API](https://oncharge.io/docs/gateway-api). For card processing through your own merchant account, use [OnCharge Secure Checkout for WooCommerce](https://oncharge.io/docs/woocommerce).
---
# Gateway API
The OnCharge Gateway API takes Crypto payments and Card to Crypto (card, wallet and pay-app payments paid out in USDC) and forwards each one to a wallet you own as soon as it settles. There is no payout schedule: every payout is split on-chain in one transaction. Create wallets with a [gateway key](#accounts) from your OnCharge dashboard (open as soon as you sign up): OnCharge then signs every callback it sends you and shows each payment in your dashboard.
| Host | Use |
|---|---|
| `https://capi.oncharge.io` | API calls from your server |
| `https://ccheckout.oncharge.io` | Checkout pages you send the customer to |
**Split:** 94% of each payment to your wallet, 5% to OnCharge, 1% network gateway fee. Card to Crypto payments carry the payment method's own published fee, deducted before the payout, and blockchain network fees are additional. Check the live configuration at [`GET /healthz`](#health).
**Card to Crypto payments** arrive as USDC on Polygon. **Crypto payments** arrive in the coin the customer paid.
Looking for the WooCommerce plugin instead? See [Crypto payments plugin](https://oncharge.io/docs/crypto-plugin). For card processing through your own merchant account, see the [Quickstart](https://oncharge.io/docs/quickstart).
## How a payment works {#flow}
1. **Create a wallet for the order** on your server, with your gateway key, your payout wallet and a callback URL unique to the order.
2. **Send the customer to pay** on the hosted checkout, or show a crypto address on your own page.
3. **Receive the callback** when the payment arrives. Verify OnCharge's signature, then fulfil the order.
```bash title="The whole flow with curl"
# 1. Wallet for order 1001, with your gateway key; its callbacks come through OnCharge
curl -G 'https://capi.oncharge.io/control/wallet.php' \
-H 'X-OnCharge-Key: ocg_…' \
--data-urlencode 'address=0xYourPolygonUsdcWallet' \
--data-urlencode 'callback=https://shop.example.com/oncharge/callback?order=1001&token=9f2c41d7' \
--data-urlencode 'oncharge_relay=1'
# 2. Send the customer to the address_in it returned (already URL-encoded)
https://ccheckout.oncharge.io/pay.php?address=ADDRESS_IN&amount=49.90&email=shopper%40example.com¤cy=USD
```
## Cards, wallets and pay apps {#cards}
Card to Crypto: customers pay by card, Apple Pay, Google Pay, Cash App, Venmo and more. The payment arrives as USDC, and the gateway forwards it to your Polygon wallet.
### Create a payment wallet {#card-wallet}
`GET https://capi.oncharge.io/control/wallet.php`
| Parameter | Required | Description |
|---|---|---|
| `address` | yes | Your USDC payout wallet on Polygon (`0x…`, an address you control). |
| `callback` | yes | URL-encoded callback URL, unique to this order. Include your order id and a secret token. |
| `oncharge_relay` | yes | `1`: callbacks come through OnCharge, signed with your key ([Callbacks](#callbacks)). Send your gateway key as the `X-OnCharge-Key` header. |
| Response field | Description |
|---|---|
| `address_in` | Encrypted wallet reference. Pass it to the checkout page as `address`. It is already URL-encoded: append it as it is. |
| `polygon_address_in` | The order's Polygon deposit address. Matches `address_in` in the callback. |
| `callback_url` | The callback URL as registered. |
| `ipn_token` | Token for occasional status reads. Store it with the order. |
The same callback URL always returns the same wallet, so rebuilding a checkout link is safe.
```js title="Node.js"
const callbackUrl = `https://shop.example.com/oncharge/callback?order=${order.id}&token=${order.callbackToken}`;
const url = new URL('https://capi.oncharge.io/control/wallet.php');
url.searchParams.set('address', process.env.ONCHARGE_PAYOUT_WALLET);
url.searchParams.set('callback', callbackUrl);
url.searchParams.set('oncharge_relay', '1');
const wallet = await fetch(url, { headers: { 'X-OnCharge-Key': process.env.ONCHARGE_GATEWAY_KEY } }).then((r) => r.json());
```
```php title="PHP"
$wallet = json_decode(file_get_contents('https://capi.oncharge.io/control/wallet.php?' . http_build_query([
'address' => getenv('ONCHARGE_PAYOUT_WALLET'),
'callback' => $callbackUrl,
'oncharge_relay' => '1',
]), false, stream_context_create(['http' => ['header' => 'X-OnCharge-Key: ' . getenv('ONCHARGE_GATEWAY_KEY')]])), true);
```
### Hosted checkout {#pay}
`GET https://ccheckout.oncharge.io/pay.php` — a page you send the customer to. It lists every payment method available for the customer's country, amount and currency.
| Parameter | Required | Description |
|---|---|---|
| `address` | yes | `address_in` from the wallet, as returned. |
| `amount` | yes | Order total. |
| `email` | yes | The customer's email address. |
| `currency` | yes | Three-letter currency code. Some methods accept USD only: convert first with [Convert to USD](#convert-usd). |
| `logo` | no | URL of your logo. |
| `background`, `theme`, `button` | no | Page, accent and button colours: hex codes or CSS colour names. |
### Send the customer to one method {#process-payment}
`GET https://ccheckout.oncharge.io/process-payment.php` — skips the method list and opens one payment method. Use it to build your own buttons and choose exactly which methods your checkout offers.
| Parameter | Required | Description |
|---|---|---|
| `address` | yes | `address_in` from the wallet. |
| `amount` | yes | Order total. |
| `provider` | yes | Method id from [List payment methods](#providers), such as `cashapp`, `venmo`, `applepay` or `googlepay`, or `card` for the card page. |
| `email` | yes | The customer's email address. |
| `currency` | yes | Three-letter currency code. |
```html title="Your own buttons"
Pay with Cash App
Pay with Apple Pay
Pay by card
More ways to pay
```
Check each method's minimum order and region in [List payment methods](#providers) before showing its button. The amount is visible to the customer: always compare what arrives with what you expect.
### Cash App and Venmo side by side {#pay-apps}
All the Card to Crypto methods of one wallet pay the same deposit address, so you can offer Cash App, Venmo and card for one order without creating another wallet. For the fastest page:
1. Build the Cash App, Venmo and card links from the same `address_in` (`provider=cashapp`, `provider=venmo`, `provider=card`).
2. On your server, resolve the Cash App link to Cash App's native invoice (the page with the QR code) once, so the browser skips a redirect. `Gateway.preparePayApps()` does this for you.
3. Load both frames at once and keep the inactive one behind its tab. Add `` for `ccheckout.oncharge.io` on the checkout page.
4. Card opens a licensed card page in a new tab.
`Gateway.preparePayApps()` in [`@oncharge/node`](https://oncharge.io/docs/sdks#gateway) does steps 1 and 2, and `` in [`@oncharge/react`](https://oncharge.io/docs/sdks#react) does 3 and 4. Tell customers to pay once: a payment through either page completes the order.
Cash App's native invoice is the one payment page that keeps its own name: it is served by Cash App's payment partner on its own host and cannot be renamed. Every other page is on `ccheckout.oncharge.io`.
## Crypto on your own page {#crypto}
Show the customer an address, an exact amount and a QR code. Payments are forwarded to your wallet in the same coin.
Coins are written as paths: `btc`, `eth`, `sol`, `ltc`, `doge`, `xrp`, `trc20/usdt`, `polygon/usdc`, `bep20/usdt`, `base/usdc` and so on. [List coins](#coins) returns them all. Use a payout wallet on the coin's network: one EVM address covers Ethereum, BNB Chain, Polygon, Base, Arbitrum, Optimism, Avalanche, Linea and other EVM networks.
### Create a crypto deposit address {#crypto-wallet}
`GET https://capi.oncharge.io/crypto/{coin}/wallet.php`
| Parameter | Required | Description |
|---|---|---|
| `address` | yes | Your payout wallet on the coin's network. For XRP: `r…` or `r…?dt=TAG`. |
| `callback` | yes | URL-encoded callback URL, unique to this order. |
| `pending` | no | `1` also sends a callback (with `pending=1`) when the transaction is first seen. |
| `confirmations` | no | Confirmations required before the confirmed callback (at least 1). |
Returns `address_in` (the address the customer pays), `callback_url` and `ipn_token`.
### Price an order in crypto {#crypto-convert}
`GET https://capi.oncharge.io/crypto/{coin}/convert.php?value=100&from=usd`
Returns `value_coin` (the amount to request) and `exchange_rate`.
```json title="Response"
{ "status": "success", "value_coin": "0.00166672", "exchange_rate": "0.0000166672" }
```
### QR code {#qrcode}
`GET https://capi.oncharge.io/crypto/{coin}/qrcode.php?address={address_in}&amount={value_coin}`
Returns `qr_code`, a base64 PNG (`data:image/png;base64,…`). `amount` is optional.
## Hosted crypto checkout {#hosted}
One link, every coin: the customer chooses the coin on a hosted page.
### Create a hosted crypto checkout {#multi-hosted}
`POST https://capi.oncharge.io/crypto/multi-hosted-wallet.php` with a JSON body. Give one payout wallet per network you accept; networks left out are not offered.
| Field | Required | Description |
|---|---|---|
| `evm`, `btc`, `bitcoincash`, `ltc`, `doge`, `solana`, `trc20`, `xmr`, `zec`, `ton`, `xrp` | at least one | Your wallet on each network you accept. `evm` covers ETH, USDT, USDC and tokens on EVM networks. |
| `fiat_amount` | yes | Order total. |
| `fiat_currency` | yes | Order currency, such as `USD`. |
| `callback` | yes | Callback URL unique to this order. |
Returns `payment_token`, `callback_url` and `ipn_token`.
```bash title="curl"
curl -X POST 'https://capi.oncharge.io/crypto/multi-hosted-wallet.php' \
-H 'Content-Type: application/json' \
-d '{"evm":"0xYourEvmWallet","btc":"bc1qYourBitcoinWallet","fiat_amount":49.9,"fiat_currency":"USD","callback":"https://shop.example.com/oncharge/callback?order=1001&token=9f2c41d7"}'
```
### Hosted crypto page {#hosted-page}
`GET https://ccheckout.oncharge.io/crypto/hosted.php?payment_token={payment_token}&add_fees=1`
`add_fees=1` adds the network fee to what the customer pays. The `logo`, `background`, `theme` and `button` branding options work here too.
## Rates, coins and payment methods {#data}
Read-only endpoints for building your checkout. They are safe to call from a browser (CORS is open).
### List payment methods {#providers}
`GET https://capi.oncharge.io/control/provider-status/`
Returns `providers[]` with `id` (the value for `provider`), `status` (`active` when available), `minimum_amount`, `minimum_currency` and `fees` (the method's published fee). Label each button in your own words (Cash App, Apple Pay, Card…).
### List coins {#coins}
`GET https://capi.oncharge.io/crypto/info.php`
Every supported coin and token, grouped by network, with its logo and minimum payment. Minimums reflect the split payout (two recipients), so they are higher than for a single-wallet payout.
### Coin details {#coin-info}
`GET https://capi.oncharge.io/crypto/{coin}/info.php` returns `coin`, `minimum` and `prices` (one price per fiat currency).
### Network fee estimate {#fees}
`GET https://capi.oncharge.io/crypto/{coin}/fees.php` returns `estimated_cost` (in the coin) and `estimated_cost_currency` (in each fiat currency).
### Convert to USD {#convert-usd}
`GET https://capi.oncharge.io/control/convert.php?value=49.90&from=eur` returns `value_coin` (in USD) and `exchange_rate`.
### Health {#health}
`GET https://capi.oncharge.io/healthz`
```json title="Response"
{ "service": "oncharge-gateway", "status": "configured", "api": "capi.oncharge.io", "checkout": "ccheckout.oncharge.io", "commission_percent": 5, "merchant_percent": 94, "sub_affiliates": true }
```
## Payment status {#status}
For occasional checks only: update orders from the [callback](#callbacks), not by polling.
| Endpoint | Parameters |
|---|---|
| `GET /control/payment-status.php` | `ipn_token` (card, wallet and pay-app payments) |
| `GET /crypto/payment-status.php` | `ipn_token`, `ticker` (the coin path) |
| `GET /crypto/control/swap-status.php` | `exchange_id` |
Card status returns `status` (`paid` or `unpaid`), `value_coin`, `txid_out` and `coin`.
These reads are rate limited upstream. The gateway keeps final answers for 24 hours and in-progress answers for 30 seconds, so repeated reads of one payment do not add to the limit. A `429` response carries `Retry-After`: wait that long before asking again. Every status response carries `X-OnCharge-Status-Cache` (`miss`, `hit`, `shared` or `bypass`).
## Swaps {#swaps}
The customer sends one coin and your wallet receives another.
| Endpoint | Parameters |
|---|---|
| `GET /crypto/swap-info.php` | none: lists swappable coins as paths |
| `GET /crypto/{from}/swap.php` | `ticker_to`, `address` (your receiving wallet), `amount`, `callback` |
| `GET /crypto/control/swap-status.php` | `exchange_id` (the `data.id` that `swap.php` returned) |
`swap.php` returns `data`: the exchange's `id`, `status`, `amount_from`, `amount_to` (an estimate: the rate floats), `exchange_address_wallet` (where to send the coins) and `expires_at`. Its `status` moves through `waiting`, `confirming`, `exchanging` and `sending` to `finished`, or ends `failed` or `expired`.
Every swap call creates a new exchange: never retry it automatically. Follow it with `swap-status.php`, or with the callback you passed.
## Partner splits {#partners}
Agencies and platforms can earn on the payments of merchants they bring. The merchant's 94% is shared between the merchant and your wallet; OnCharge's 5% and the 1% gateway fee are unchanged.
`GET https://capi.oncharge.io/control/custom-sub-affiliate.php` (also available as `/set-affiliate.php`)
| Parameter | Required | Description |
|---|---|---|
| `address` | yes | The merchant's Polygon USDC wallet. |
| `callback` | yes | Callback URL unique to this order. |
| `merchant_fee` | yes | Merchant share, such as `0.92`. |
| `sub_affiliate_fee` | yes | Your share, such as `0.02`. `merchant_fee + sub_affiliate_fee` must equal `0.94`. |
| `sub_affiliate` | yes | Your EVM wallet. |
Shares that do not add up, or a missing wallet, are refused with HTTP 400.
## Callbacks {#callbacks}
When a payment arrives, OnCharge requests your callback URL (`GET`) with your own parameters plus the payment data, for wallets created with your gateway key and `oncharge_relay=1`:
| Parameter | Description |
|---|---|
| `value_coin` | Amount received. Card to Crypto payments arrive in USDC after the method's own fee. |
| `coin` | Coin received, such as `polygon_usdc`, `btc` or `trc20_usdt`. |
| `txid_in` | Transaction that paid the order. Credit each one once. |
| `txid_out` | Transaction that forwarded the funds to you. |
| `address_in` | The order's deposit address. |
| `value_forwarded_coin` | Total forwarded to all payout wallets. |
| `address_out` | Share received by each payout wallet. |
| `pending` | `1` on an unconfirmed crypto notice. Do not ship yet. |
### Verify the signature {#signature}
Every callback OnCharge sends you is signed with your gateway key's signing secret:
- `X-OnCharge-Signature: t=,v1=`: an HMAC-SHA256, with your signing secret (`ocgs_…`), of `.`.
- `X-OnCharge-Event-Id`: the payment. A repeat has the same id.
The full URL is **your callback URL as registered** (scheme, host and path) followed by `?` and **the raw query string exactly as it arrived**. Read the raw query from the request line; do not rebuild it from parsed parameters, because one changed byte invalidates the signature. Reject a signature that does not match, or a `t` more than five minutes old.
```js title="Node.js (Express)"
import { createHmac, timingSafeEqual } from 'node:crypto';
const CALLBACK_URL = 'https://shop.example.com/oncharge/callback'; // as registered
app.get('/oncharge/callback', async (req, res) => {
const rawQuery = req.originalUrl.split('?')[1] ?? '';
const { t = '', v1 = '' } = Object.fromEntries(String(req.get('X-OnCharge-Signature') ?? '').split(',').map((p) => p.trim().split('=')));
const expected = createHmac('sha256', process.env.ONCHARGE_SIGNING_SECRET).update(`${t}.${CALLBACK_URL}?${rawQuery}`).digest('hex');
const fresh = Math.abs(Date.now() / 1000 - Number(t)) <= 300;
if (!fresh || v1.length !== expected.length || !timingSafeEqual(Buffer.from(v1), Buffer.from(expected))) return res.sendStatus(403);
// …check your order token, ignore pending=1, credit txid_in once, compare coin and amount…
res.send('ok');
});
```
```php title="PHP"
$raw = $_SERVER['QUERY_STRING'] ?? '';
parse_str(str_replace(',', '&', str_replace(' ', '', $_SERVER['HTTP_X_ONCHARGE_SIGNATURE'] ?? '')), $sig);
$t = (string) ($sig['t'] ?? '');
$expected = hash_hmac('sha256', $t . '.https://shop.example.com/oncharge/callback?' . $raw, (string) getenv('ONCHARGE_SIGNING_SECRET'));
if ($t === '' || abs(time() - (int) $t) > 300 || !hash_equals($expected, (string) ($sig['v1'] ?? ''))) {
http_response_code(403);
exit;
}
```
### Then check the payment {#checks}
1. **Your token.** Anyone can create a wallet whose callback names one of your orders. A token only your server can produce (for example an HMAC of the order id) proves the order reference is yours.
2. **Pending notices.** Ignore `pending=1` until the confirmed callback arrives.
3. **Each transaction once.** Callbacks repeat: answer `200` and credit each `txid_in` once.
4. **Coin, address and amount.** Compare `coin`, `address_in` and `value_coin` with the order before releasing goods. Card to Crypto payments arrive after the method's own fee, so decide what share of the total you accept.
Never use the gateway's parameter names (`value_coin`, `coin`, `txid_in`, `txid_out`, `address_in`, `value_forwarded_coin`, `address_out`, `pending`) in your own callback URL. When a name appears twice, use the last value: the gateway appends its parameters after yours.
## Accounts and keys {#accounts}
Create wallets with a **gateway key**: OnCharge then signs the callbacks it sends you, and every wallet and payment shows up in your dashboard under **Payments**, next to your other payments. Keys need no verification: create one as soon as you sign up.
Every payout wallet and swap destination a key is used with is screened against the OFAC sanctions list. A listed wallet switches the key off, and the dashboard says so. For a store's first 30 days, a card payment over $500, or over $2,000 of card payments in 24 hours, pauses the store's Card to Crypto in the plugin until the 24 hours have room again; it turns back on by itself.
1. In the dashboard, open **Payments → Gateway API** and select **Create key**. Copy the key (`ocg_…`) and its signing secret (`ocgs_…`): they are shown once.
2. Send the key with every call, as a header or a query parameter:
```bash title="A wallet linked to your account"
curl -G 'https://capi.oncharge.io/control/wallet.php' \
-H 'X-OnCharge-Key: ocg_…' \
--data-urlencode 'address=0xYourPolygonUsdcWallet' \
--data-urlencode 'callback=https://shop.example.com/oncharge/callback?order=1001&token=9f2c41d7'
```
| Parameter | Where | Description |
|---|---|---|
| `X-OnCharge-Key` | header | Your gateway key. Or pass it as the `oncharge_key` query parameter. |
| `oncharge_relay=1` | query | Send this wallet's callbacks through OnCharge, signed with your key (see [Callback relay](#relay)). Or the `X-OnCharge-Relay: 1` header. |
- The key is removed before the request leaves OnCharge: the payment network never sees it.
- Payments appear when OnCharge sees them: through the relay, or when you read a payment's status through the gateway.
- Calls without a key, or with a revoked key, work exactly as before; they just do not show up in your dashboard.
- Keep the key on your server. Revoke it in the dashboard at any time.
## Callback relay {#relay}
Add `oncharge_relay=1` (with your key) when you create a wallet, and OnCharge receives the payment callback first: it checks the network's signature, records the payment in your dashboard, then sends you the same callback, retrying until your server answers `2xx`.
- **Same URL, same parameters.** You receive your callback URL with the gateway's parameters appended, exactly as without the relay. The wallet's `callback_url` in the response is still yours, and the same callback URL still returns the same wallet.
- **Signed by OnCharge.** Relayed callbacks carry `X-OnCharge-Signature: t=,v1=`: an HMAC-SHA256, with your key's signing secret, of `.`. Reject it if the signature does not match or `t` is more than five minutes old. `X-OnCharge-Event-Id` names the payment; a repeat has the same id.
- **Retries.** After 1 minute, 5 and 15 minutes, then 1, 3, 6, 12 and 24 hours. A crypto payment's unconfirmed notice (`pending=1`) and its confirmed callback are each delivered once.
```js title="Node.js: check a relayed callback"
import { createHmac, timingSafeEqual } from 'node:crypto';
function relayedCallbackIsValid(fullUrl, header, signingSecret) {
const { t, v1 } = Object.fromEntries(String(header ?? '').split(',').map((p) => p.trim().split('=')));
if (!t || !v1 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = createHmac('sha256', signingSecret).update(`${t}.${fullUrl}`).digest('hex');
return v1.length === expected.length && timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
}
// fullUrl is the callback URL exactly as it arrived: https://shop.example.com/oncharge/callback?order=1001&…
```
Then run the same [checks](#checks) as for a direct callback.
## Webhooks and the payments API {#webhooks}
With your gateway key, each payment and conversion is also an OnCharge event, sent to the [webhook endpoints](https://oncharge.io/docs/webhooks) you set up in the dashboard and kept in [`GET /api/v1/events`](https://oncharge.io/docs/api#listevents) for 30 days:
| Event | When | `data.rail` |
|---|---|---|
| `payment.pending` | A payment is seen on the chain and not confirmed yet. | `crypto`, or `card_to_crypto` for a card wallet |
| `payment.captured` | The payment is confirmed and forwarded to your wallet. | the same |
| `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired` | A conversion starts, or ends. | `crypto` |
Each is sent once per state, with OnCharge references (`ocpay_…`, `ocswp_…`), your wallet masked and the public transaction hashes. Payments also appear in [`GET /api/v1/payments`](https://oncharge.io/docs/api#listpayments) (`source=gateway`). The callbacks above stay as they are: use whichever your integration prefers.
## Plugins and modules {#plugins}
Compatible open-source white-label gateway modules run on OnCharge unchanged. In the module's settings:
| Setting | Value |
|---|---|
| API Domain | `capi.oncharge.io` |
| Custom / Checkout Domain | `ccheckout.oncharge.io` |
| Wallet | Your Polygon USDC wallet |
Modules with both settings exist for Magento 2, PrestaShop, OpenCart and WHMCS: [contact OnCharge support](/contact) and we send you the one for your cart. For WooCommerce, use the [OnCharge Crypto Payments plugin](https://oncharge.io/docs/crypto-plugin).
## Errors {#errors}
| Status | Meaning |
|---|---|
| `400` | A parameter was refused, for example partner shares that do not add up or a network the gateway does not support. |
| `405` | Wrong method: wallet creation is `GET`, the hosted crypto checkout is `POST`. |
| `429` | Status reads are rate limited: wait for `Retry-After`. |
| `502` | The upstream payment network did not answer. Retry `GET` requests later. |
## Security notes {#security}
- Keep your callback secret on your server. Never put it in browser code.
- Use a self-custodial payout wallet you control; exchange deposit addresses are not recommended.
- Price orders on the server. The amount in a checkout link can be seen and edited by the customer.
- Update orders from verified callbacks. Use the status endpoints only for occasional checks.
---
# Advertising
OnCharge Advertising runs your Google and TikTok ads and sets up Meta tracking and your Meta catalog ($99 per month plus 10% of the ad spend on campaigns OnCharge runs; campaigns you run yourself, including all Meta campaigns, carry no fee). It is a separate service from payment processing: choose it at **Get Started** in the [merchant portal](https://app.oncharge.io). This page covers what your store needs for it: the tracking tag, attribution for custom storefronts, the product catalog API, the WooCommerce setup and how OnCharge runs your TikTok ads.
> **Your whole catalog is submitted.** OnCharge sends every product, research-use-only (RUO) products included, to the ad platforms. Google, Meta and TikTok each review products and ads against their own policies: some products are approved (capsules often are), others are disapproved, and the result for each product shows in the portal under **Advertising → Catalog**. OnCharge keeps back only products that name a controlled substance. It never uses other pages or other wording to get a product past a platform's review.
## The tracking tag
One tag sends your storefront's events to Google, Meta and TikTok through OnCharge, with the IDs set up in the portal under **Advertising → Tracking**. Put it in the `` of every page:
```html title="Every page"
```
`YOUR_STORE_ID` is the store's ID (a UUID) from the portal's **Stores** page. The tag needs no API key and must never be given one.
### Events
Queue events before the tag has loaded, or call it directly once it has:
```html title="Product page"
```
```js title="After the tag has loaded"
window.OnChargeGrowth.track('add_to_cart', {
value: 98.0,
currency: 'USD',
items: [{ id: '205', name: 'Linen shirt - Blue, M', price: 49.0, quantity: 2 }],
});
```
| Event | When | Parameters |
|---|---|---|
| `page_view` | Each page view (in a single-page app, each route change) | |
| `view_item` | A product page | `value`, `currency`, `items` |
| `add_to_cart` | A product added to the cart | `value`, `currency`, `items` |
| `begin_checkout` | The checkout page | `value`, `currency`, `items` |
| `purchase` | The order confirmation page, once per order | `event_id`, `transaction_id`, `value`, `currency`, `items` |
| Parameter | Type | Notes |
|---|---|---|
| `event_id` | string | Optional; lets ad platforms drop duplicates. For `purchase`, use the OnCharge checkout `session_id` of the order: OnCharge also reports the purchase from its servers with that ID, so it is counted once. |
| `value` | number | In major units (`49.0`, not `4900`). |
| `currency` | string | ISO 4217, e.g. `USD`. |
| `transaction_id` | string | Your order number. |
| `items[]` | array | `{ id, name?, price?, quantity }`. Use the same `id` as in your [catalog](#product-catalog-api). |
### Consent
The tag applies Consent Mode v2 with the consent setting chosen in the portal. If your site has its own consent banner, pass the visitor's choices to the tag whenever they change:
```js title="From your consent banner"
window.OnChargeGrowth.consent({
ad_storage: 'granted',
analytics_storage: 'granted',
ad_user_data: 'granted',
ad_personalization: 'denied',
});
```
Each signal is `'granted'` or `'denied'`. The WooCommerce plugin does this for you with any consent plugin that supports the WP Consent API.
## Attribution for custom storefronts
When a shopper arrives from an ad, the tag stores the click and browser IDs in a first-party cookie, `_oc_attr` (path `/`): base64url-encoded JSON. When your server creates the [checkout session](https://oncharge.io/docs/checkout), send that object as `metadata.attribution`, so OnCharge can report the purchase to the ad platform the shopper came from. The values are only forwarded to the platform they belong to and are never used for the payment.
| Field | Source |
|---|---|
| `gclid`, `gbraid`, `wbraid` | Google Ads click |
| `ga_client_id`, `ga_session_id` | Google Analytics (`_ga`, `_ga_` cookies) |
| `fbclid`, `fbp`, `fbc` | Meta click and browser IDs (`_fbp`, `_fbc` cookies) |
| `ttclid`, `ttp` | TikTok click and browser IDs (`_ttp` cookie) |
| `landing_url` | First page of the visit |
| `user_agent` | The shopper's browser |
| `consent` | `{ ad_storage, analytics_storage, ad_user_data, ad_personalization }`, each `granted` or `denied` |
Treat the cookie as untrusted input: keep only these fields, drop values that are not strings or are too long (2 KB for `landing_url`, 512 characters otherwise), and never cut a click ID short.
```js title="attribution.mjs (Node)"
const FIELDS = ['gclid', 'gbraid', 'wbraid', 'ga_client_id', 'ga_session_id', 'fbclid', 'fbp', 'fbc', 'ttclid', 'ttp', 'landing_url', 'user_agent'];
const CONSENT = ['ad_storage', 'analytics_storage', 'ad_user_data', 'ad_personalization'];
/** metadata.attribution from the _oc_attr cookie value, or undefined. */
export function attributionFromCookie(raw, userAgent) {
let data = {};
try {
if (raw && raw.length <= 4096) data = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
} catch {
data = {};
}
const out = {};
for (const field of FIELDS) {
const value = data?.[field];
const max = field === 'landing_url' ? 2048 : 512;
if (typeof value === 'string' && value.length > 0 && value.length <= max) out[field] = value;
}
if (!out.user_agent && userAgent) out.user_agent = String(userAgent).slice(0, 512);
const consent = {};
for (const key of CONSENT) if (['granted', 'denied'].includes(data?.consent?.[key])) consent[key] = data.consent[key];
if (Object.keys(consent).length) out.consent = consent;
return Object.keys(out).some((k) => k !== 'user_agent') ? out : undefined;
}
// When creating the session:
// body.metadata = { ...body.metadata, attribution: attributionFromCookie(req.cookies._oc_attr, req.headers['user-agent']) };
```
## Product catalog API
Shopping ads need your products in Google Merchant Center and the Meta catalog. Send them to OnCharge and it keeps both up to date. Requests are signed like every other API call (see [Authentication & signing](https://oncharge.io/docs/authentication)); full field lists are in the [API reference](https://oncharge.io/docs/api#catalog).
```http
POST /api/v1/catalog/products/batch
```
```json title="Request"
{
"items": [
{
"id": "205",
"item_group_id": "200",
"title": "Linen shirt - Blue, M",
"description": "Soft linen shirt.",
"link": "https://shop.example.com/product/linen-shirt/?attribute_pa_color=blue",
"image_link": "https://shop.example.com/wp-content/uploads/linen-shirt-blue.jpg",
"price_minor": 4900,
"sale_price_minor": 3900,
"currency": "USD",
"availability": "in_stock",
"brand": "Acme",
"gtin": "0012345678905",
"product_type": "Apparel > Shirts",
"attributes": { "Color": "Blue", "Size": "M" }
},
{ "id": "310", "title": "Lab vial", "link": "https://shop.example.com/product/vial/", "price_minor": 8000, "currency": "USD", "ruo": true }
],
"deletes": ["198"]
}
```
```json title="Response"
{
"results": [
{ "id": "205", "status": "created", "advertisable": true, "ruo": false, "excluded_reason": null },
{ "id": "310", "status": "created", "advertisable": false, "ruo": true, "excluded_reason": "missing_image" },
{ "id": "198", "status": "deleted" }
],
"counts": { "created": 2, "updated": 0, "unchanged": 0, "deleted": 1, "not_found": 0, "rejected": 0 }
}
```
- Up to **500** products and deletes per request, each `id` once (at most 50 characters). Prices are in minor units, as shown in your store.
- Send a variant per row with `item_group_id` set to the parent; don't send the parent itself.
- A product sent again is updated; an identical one is not rewritten (`unchanged`). A delete takes the product off the ad platforms.
- Titles are cut to 150 characters and descriptions to 5,000; HTML is removed; a GTIN is kept only when it is 8–14 digits.
### What OnCharge sends, and what it keeps back
Every product is sent to the ad platforms, and each platform reviews it against its own policies. A disapproval comes back with the platform's reason and shows on the portal's **Advertising → Catalog** page. `ruo: true` is a label only: an RUO product is sent like any other.
OnCharge keeps a product back (stored, and listed on the Catalog page with the reason, but not sent) only for one of these `excluded_reason` values:
| Result | Why |
|---|---|
| `merchant_excluded` | You sent `excluded: true`. |
| `controlled_substance` | The product names a controlled substance (U.S. DEA schedules I to V). Controlled substances are never sent to an ad platform or advertised. |
| `insecure_link` | The link is not `https://`. A new product with an http link is rejected; one already stored is excluded. |
| `missing_image` | No `image_link`. |
| `zero_price` | `price_minor` is 0. |
### Keeping the catalog in sync
1. Send changed products as they change (batch them, for example every minute).
2. Once a day, send everything.
3. Then page through `GET /api/v1/catalog/products?limit=500&offset=…` (sign an empty body; the query string is not signed) and delete IDs you no longer sell.
The WooCommerce plugin does all three for you.
## WooCommerce
The OnCharge Secure Checkout plugin (1.5.0 or later) includes everything above. In WordPress, go to **WooCommerce → Settings → Integration → OnCharge Marketing**. It uses the Store ID, API Key and API Secret you entered in the payment settings (see [WooCommerce](https://oncharge.io/docs/woocommerce)).
| Setting | What it does |
|---|---|
| Tracking tag | Adds the tag and sends `view_item`, `add_to_cart` (classic, AJAX and Blocks), `begin_checkout` and `purchase` (once per order, with the OnCharge session ID as `event_id`). Checkout sessions carry `metadata.attribution`. |
| Cookie consent | Passes visitors' choices from a WP Consent API consent plugin to the tag. |
| Product sync | Sends published products and variations; changes within a minute, everything daily, and removes products you deleted. |
| Categories to exclude | Products in these categories are never advertised. |
| RUO categories | Products in these categories are labelled RUO in your OnCharge catalog. The label is information only: they are sent to the ad platforms like any other product, and the tag loads on their pages. |
The settings page shows the last sync, counts, errors and products OnCharge rejected, with a **Sync all products now** button. On your home page the plugin also adds the Google site-verification tag OnCharge needs to verify your site in Merchant Center.
## TikTok
OnCharge runs your TikTok ads from its own TikTok Business Center, as your agency: in TikTok it appears as your partner, **OnCharge Group LLC**. Set it up in the portal under **Advertising → TikTok**.
### Your TikTok ad account
| | Use my TikTok ad account | Create one for me |
|---|---|---|
| Owner | You | Your business, under OnCharge's Business Center |
| Who pays TikTok | You, with your TikTok payment method | OnCharge, from your prepaid advertising balance (spend at cost plus the 10% management fee) |
| Setup | Share the account with OnCharge as a partner | One click, once Advertising is active and billing is set up |
**Use my TikTok ad account.** In TikTok Business Center go to **Business settings → Users → Partners → Add partner**, enter OnCharge's Business Center ID `7707361902699298817`, choose **Ad accounts**, select the store's ad account and give it the **Operator** permission. Then enter the ad account ID on the TikTok page and choose **Check connection**.
**Create one for me.** OnCharge creates the ad account with the business details from your OnCharge application: your registered business name, website, country and contact details. They cannot be typed in at this step; contact support if they are wrong. OnCharge keeps about three days of your approved budget in the account, never more than your advertising balance covers. If your balance cannot cover more spend, OnCharge pauses the campaigns and moves the unused money back. OnCharge creates TikTok ad accounts for stores in the RUO programme too; TikTok reviews each account and its ads against its own policies.
### Campaigns
OnCharge Ads AI writes a TikTok Smart+ plan for your store: a campaign name, a daily budget, the countries, three to five ad texts, the button (for example **Shop now**) and a short brief for the video. TikTok's Smart+ then chooses the audience (adults only), bids and placements. Nothing launches until you, or OnCharge on your behalf, approve the plan.
| Rule | Limit |
|---|---|
| Budget | At least $20 a day (TikTok's minimum), so at least $600 a month |
| Ad text | 12–100 characters each, up to 5; no emoji, web addresses or phone numbers |
| Landing page | An `https://` page of your own store |
| Video | MP4, MOV or MPEG, up to 500 MB; vertical 9:16, 9–30 seconds works best |
| Brand profile (video ads) | Your own brand name, 2–40 characters; square PNG or JPEG logo, 100 pixels or more, up to 500 KB |
Before you approve, add the creative: upload a video, or use one of your TikTok posts with its Spark Ads authorization code (in the TikTok app open the post, then **Ad settings → Ad authorization**, and generate a code). Video ads appear on TikTok under your brand: on the TikTok page save a display name (your store's own brand name, 2–40 characters) and a square PNG or JPEG logo (at least 100 pixels wide, up to 500 KB). OnCharge sets up this profile in your ad account once and uses it for every video ad; until it is saved, approved video campaigns wait. Ads made from a Spark Ads post appear under that post's TikTok account instead. Your store's TikTok pixel must be in the ad account so Smart+ can optimise for purchases; for an account OnCharge creates, OnCharge adds a pixel when your store has none.
Approving needs an advertising balance that covers three days of the plan's management fee, and of its spend when OnCharge pays TikTok. OnCharge then builds the campaign switched off, adds its ad group and ad, and switches it on.
### TikTok Autopilot
Autopilot runs TikTok for you from **Advertising → TikTok Autopilot**.
1. **Connect TikTok.** Sign in to TikTok once. OnCharge adds its Business Center as a partner with Admin access to the ad account you pick, and makes sure the account has a pixel for your store. If the ad account is not in a Business Center you manage, TikTok does not allow this step to be done for you: the page shows the three clicks to do it by hand, or OnCharge can create an ad account for you.
2. **Brand kit.** OnCharge reads your website for your name, logo, colours and product pictures, and each product's search title and description. Correct anything and upload your own pictures and videos (PNG, JPEG, MP4 or MOV). List what your ads must never say; every video is checked against it.
3. **Research.** OnCharge finds your competitors, the ads they keep running on Google (from the Ads Transparency Center, with how long each has run) and how your products are worded in search results, and OnCharge Ads AI turns that into angles and opening lines. TikTok and Meta do not publish an ad library for ordinary ads in the United States, so competitor ads come from Google's.
4. **Videos.** OnCharge Creative Studio makes vertical 10–15 second videos, each on a different angle, starting from your own product picture where there is one. A concept is set aside before any video is made if it makes a medical or health claim, promises a result, describes use on or in the body, addresses a viewer's personal attributes, breaks your own list, or names a controlled substance.
5. **Testing.** Each approved video runs as its own ad with its own daily budget ($25 by default; TikTok's minimum is $20). After about twice your target cost per sale without a sale, an ad is stopped. An ad that sells under the target for two days gets more budget, one step a day (20% by default). New videos lean towards the angles that have sold for your store.
| Mode | New ad goes live | Losing ad is stopped | Winner's budget is raised |
|---|---|---|---|
| Manual Review | You approve | You approve | You approve |
| Semi Auto | You approve | Automatic | You approve |
| Full Autopilot | Automatic | Automatic | Automatic |
Your limits apply in every mode: a daily limit for all ads together, the most one ad may reach, how many ads run at a time and how fast a budget may grow. Choosing Full Autopilot asks you to agree to those limits, and raising one later asks again. Nothing is raised or launched that your advertising balance does not cover. Every decision is listed with the numbers behind it, and you can pause Autopilot or any single ad at any time.
### Changes and results
From the TikTok page you can pause a campaign or everything, switch them back on, change a daily budget or replace the ad text. OnCharge applies each change in TikTok within minutes. Outside Full Autopilot (below), nothing that raises spend happens automatically: when your balance runs out OnCharge pauses every campaign in the account, and after you add funds you approve restarting them. Spend, purchases and purchase value appear on the TikTok page, updated every few hours.
> **TikTok reviews every ad.** OnCharge submits your plan as it is, and TikTok approves or disapproves it against its own policies. OnCharge's own check before approval blocks one thing: a plan, ad text or landing page that names a controlled substance. Categories TikTok is known to restrict are shown as a note on the plan, not a block. OnCharge does not use other pages, other wording or other workarounds to get an ad through review.
---
# Partner Network
The OnCharge Partner Network writes original articles for your store's own blog and connects you with related stores in the network ($99 per month). Join from **Marketing → SEO / GEO → Partner Network** in the [merchant portal](https://app.oncharge.io). This page covers what the network does on your site and what your site needs.
> **Partner links are sponsored links.** When an article mentions another member store, the article opens with a partner content notice and the link carries `rel="sponsored"`, as search engines and the FTC require. Partner mentions bring visitors and awareness; they never pass search ranking. Keep the notice and the `rel` attribute exactly as published.
## What you get
- Up to four articles a month, written for your customers about what you sell, linking to your own products and categories.
- Mentions of your store in other members' articles, where they genuinely help their readers. Visits arrive tagged `utm_source=`, `utm_medium=partner`, `utm_campaign=partner-network`.
- Checks on every article before you see it: no health, dosing or clinical claims, no invented facts or reviews, no copied text.
- A daily check that published partner mentions are still in place.
## Publishing
**WordPress (and WooCommerce) sites** publish in one click. In WordPress, open **Users → Profile → Application Passwords**, create one named "Partner Network" for an Administrator, Editor or Author, and paste it into the portal with the username. OnCharge only creates, updates and unpublishes the articles it writes, and you can revoke the password in WordPress at any time. The site's REST API and application passwords must be switched on (some security plugins and code snippets switch them off; if so, the portal tells you when you connect). Enter your site's address as your browser shows it, with or without www.
Use **Connect with WordPress** to approve OnCharge on WordPress's own authorisation screen (no password to copy), or enter an application password yourself.
**Your own platform (webhook):** for headless, custom and other platforms that can receive a request. Prove you control the domain (below), give an https endpoint, and OnCharge POSTs each approved article to it:
```
POST
X-OnCharge-Event: article.publish | article.unpublish | ping
X-OnCharge-Signature: t=,v1=." with your signing secret>
{ "type": "article.publish", "created": 1794787200,
"data": { "id", "title", "slug", "html", "excerpt", "meta_description", "topics", "word_count" } }
```
Publish the `html` as given and answer `200`/`201` with `{"url": "https:///", "id": ""}`. `article.unpublish` (`data: { id, url, ref }`) asks you to take a post down; `ping` (sent by **Send a test**) only needs a `2xx`. Reject requests whose signature does not match or whose `t` is more than five minutes old. Answers of `429` or `5xx` are retried; redirects are not followed.
**Any other site, by hand:** approve an article, copy its HTML into a new post in your site's HTML editor without changing it, publish it, and paste the post's address into the portal. OnCharge opens the page to confirm the article, its partner links and the notice are there.
**Proving you control a site** (webhook and by hand; not needed for your OnCharge store's own domain): the portal shows a code. Add it as a DNS TXT record on `_oncharge.` (value `oncharge-site-verification=`), or put `` in your home page's ``.
## Partners
Articles mention stores that complement yours: a lab-testing service in a research store's article, a grinder shop in a coffee roaster's. A store whose main line is something you sell is never mentioned in your articles, and you can name stores never to be paired with (neither side mentions the other). Articles build on facts from your own pages, such as specifications, formats and testing details, and never invent others.
## Sample article
Before joining, enter your site's address under **See a sample article** to get a real article for it, written and checked as members' are. Nothing is charged or published. You can see three a day; a site's sample is kept for a day.
## Stores that list controlled substances
A store whose catalogue lists a controlled substance (anything on the DEA's schedules I–V, under its own name or a brand name) cannot be in the Partner Network. That is the network's only product rule; your ad platforms' own rules still apply to ads. A listing counts by its name and address, not by words in its description. OnCharge reads your product and category listings (WooCommerce and Shopify product feeds, the product and category addresses in your sitemap, and product links on your home page):
- when you enter your site to join, and again right before the first charge: a store with such listings cannot join and is not charged;
- when you connect a site, and before each sample article;
- every day while you are a member, and when you choose **Check again**.
If listings are found, the portal lists each one and why. Until they are removed, your store gets no new articles, approved articles wait, and other members do not mention it. Articles that mention a store held out this way are withdrawn: OnCharge unpublishes them where it publishes for the member (WordPress back to draft, or `article.unpublish` to the member's platform) and otherwise asks the member to unpublish them; each publisher gets a replacement article sooner. Remove the listings, then choose **Check again**: the block lifts on the first check that reads your whole catalogue and finds none. Your membership and its fee continue meanwhile, and you can cancel at any time.
An article or blog post that names a controlled substance does not keep your store out, but it is never linked from any article, and articles never name one.
## Results
The portal shows, for the last 30 days, the visits and paid orders that partner mentions brought you, by partner, and the visits your articles sent to partners. Orders paid through OnCharge checkout are counted automatically from their referral tags. To count visits, add one line to your site's pages; it sets no cookies and sends nothing about your visitors:
```html
```
WordPress members can also choose the blog category articles are filed under; by default they go where the site files most of its posts.
You read every article before it goes live unless you turn on **Publish automatically**. You can unpublish any article from the portal; its partner mentions end with it.
## Keeping mentions in place
While an article is on your site, keep its partner links, their `rel="sponsored"` attribute and the partner content notice. If a mention is missing or changed on three daily checks, the portal tells you; if it is still missing 14 days later, your store receives no partner mentions for 60 days.
## Research-use-only stores
Stores in the RUO program can be members. Their articles, and any article that mentions them, describe RUO products only as materials for laboratory research and carry a not-for-human-or-veterinary-use notice. Other members see mentions of RUO stores only if they allow them in their Partner Network settings.
## Terms
The [Partner Network Terms](https://oncharge.io/partner-network-terms) cover fees, cancellation and the rules above.
---
# WooCommerce
The **OnCharge Secure Checkout** plugin (version 1.7.0) adds a "Credit / Debit Card" payment method to WooCommerce. It creates checkout sessions, embeds the checkout, updates orders from OnCharge's webhooks, sends each order's shipping address and reports tracking numbers automatically so delivered orders are paid out. Since 1.5.0 it also connects the store to OnCharge Advertising: the tracking tag, shop events and a product sync for Google and Meta shopping ads (see [Advertising](#advertising)). No code is needed.
**Requirements:** WordPress 5.8+, WooCommerce 7.0+, PHP 7.4+, HTTPS. Compatible with High-Performance Order Storage (HPOS), the classic `[woocommerce_checkout]` checkout and the Blocks checkout.
## Install
1. In the [merchant portal](https://app.oncharge.io), download the plugin ZIP for your store.
2. In WordPress, go to **Plugins → Add New → Upload Plugin**, choose the ZIP, then **Install Now** and **Activate**.
3. Go to **WooCommerce → Settings → Payments → OnCharge Secure Checkout**.
## Configure
| Setting | Value |
|---|---|
| Enable | Tick to show the payment method at checkout. |
| Title / Description | What shoppers see, e.g. "Credit / Debit Card". |
| Store ID | Your store's ID from the merchant portal. |
| API Key | `oc_key_…` |
| API Secret | `oc_sec_…` (kept on the server, never sent to the browser) |
| Webhook Signing Secret | `oc_cbsec_…`, shown once when you register the store's webhook URL (below). New in 1.4.0. |
| API Base URL | `https://app.oncharge.io` (leave the default) |
| Pay Iframe Base URL | `https://app.oncharge.io` (leave the default) |
| Debug Mode | Logs to `wp-content/debug.log`. Turn off in production. |
Make sure your store's domain (as in **Settings → General → Site Address**) is registered for the store under **Security → Domains** in the portal; the plugin sends it with every request.
Then register the plugin's webhook URL, `https:///?wc-api=oncharge_callback`, for the store in the portal and paste the signing secret it shows into **Webhook Signing Secret**.
## How checkout works
1. When the shopper chooses the card method, the plugin creates a checkout session from the cart on your server and shows the OnCharge checkout in an iframe.
2. At **Place order**, WooCommerce creates the order (on hold) and the plugin attaches the order ID and shipping address to the session.
3. The shopper completes the payment in the iframe.
4. OnCharge's webhook moves the order to **Processing** when the payment is captured.
| Webhook event | Order change |
|---|---|
| `payment.authorized`, `payment.captured` | Payment complete (Processing). |
| `payment.refused`, `payment.cancelled`, `payment.expired` | Failed. |
| `payment.pending` | Order note. |
| `refund.succeeded`, `refund.failed` | Order note (with the refunded amount on success). |
| `chargeback.opened` | On hold, for review. |
| `chargeback.won`, `chargeback.lost` | Order note. |
| `delivery.confirmed` | Order note. |
Since 1.4.0 the plugin reads the v2 webhook format: it finds the order from `data.session_id`, checks the timestamped `OnCharge-Signature` first (with the Webhook Signing Secret, then the API secret; deliveries older than 5 minutes are refused), falls back to the legacy `X-Oncharge-Signature` only when the new header is absent, and ignores repeated deliveries of the same `OnCharge-Event-Id`.
Make sure your firewall, security plugin or CDN allows `POST` requests to `?wc-api=oncharge_callback`.
Refunds made from the WooCommerce order screen are sent to OnCharge.
## Shipping and tracking
OnCharge releases an order's payout 1 day after the carrier confirms delivery to the shipping address (see [Shipments & payouts](https://oncharge.io/docs/shipments)). The plugin handles both halves:
- **Shipping address:** sent with the session, or attached at **Place order**. Orders that need no shipping (virtual or downloadable products) are left out.
- **Tracking numbers:** reported for orders paid through OnCharge when the order is marked **Completed**, when a shipping integration sends a ShipStation-style ship notification, and by an hourly sweep over the last 45 days of Processing and Completed orders.
Tracking numbers are read from:
| Source | Order meta |
|---|---|
| The plugin's **OnCharge delivery** box | `_oncharge_tracking_items` |
| WooCommerce Shipment Tracking, Advanced Shipment Tracking | `_wc_shipment_tracking_items` |
| WooCommerce Shipping labels | `wc_connect_labels` |
| ShipStation-style meta | `_tracking_number` + `_tracking_provider` |
| Anything else | the `oncharge_order_shipments` filter |
```php title="functions.php"
add_filter( 'oncharge_order_shipments', function ( $shipments, $order ) {
$shipments[] = array( 'carrier' => 'UPS', 'tracking_number' => '1Z999AA10123456784' );
return $shipments;
}, 10, 2 );
```
The **OnCharge delivery** box on the order edit screen shows what was sent and the carrier's result, and lets you enter a carrier (USPS, UPS, FedEx, DHL Express) and tracking number by hand. Accepted and rejected numbers are added as order notes.
## Advertising {#advertising}
If you chose OnCharge Advertising, open **WooCommerce → Settings → Integration → OnCharge Marketing**. It uses the Store ID, API Key and API Secret above.
| Setting | What it does |
|---|---|
| Tracking tag | Adds the OnCharge tag (`https://app.oncharge.io/js/v1/growth.js`) and sends `view_item`, `add_to_cart` (classic, AJAX and Blocks), `begin_checkout` and `purchase`. The purchase uses the order's OnCharge session ID as its event ID, so it is not counted twice with OnCharge's server-side report. Checkout sessions carry the shopper's ad click IDs as `metadata.attribution`. |
| Cookie consent | With a consent plugin that supports the WP Consent API, visitors' marketing and statistics choices are passed to the tag, and ad IDs are not sent without consent. |
| Product sync | Sends published products and variations (price, sale price, stock, images, brand, GTIN/MPN, category) to OnCharge for Google Merchant Center and the Meta catalog: changes within about a minute, everything once a day, and products you delete are removed. Uses Action Scheduler. |
| Categories to exclude | Products in these categories and their subcategories are never advertised. |
| RUO categories | Products in these categories and their subcategories are labelled research-use-only (RUO) in your OnCharge catalog. The label is information only: they are sent to the ad platforms like any other product, each platform reviews them against its own policies, and the tag loads on their pages. |
The status panel on the same page shows the last sync, what was added or rejected, errors and the totals OnCharge holds, with **Sync all products now**. The plugin also adds the Google site-verification meta tag to your home page. Details: [Advertising](https://oncharge.io/docs/advertising).
## RUO compliance scanner
Research-use-only (RUO) stores also install the **OnCharge Compliance Scanner** plugin, which serves the [compliance feed](https://oncharge.io/docs/compliance-feed) so OnCharge can review a gated catalogue. It is read-only: it never changes, hides or gates your content, and shares only published products, pages and posts.
1. Upload and activate the plugin (**Plugins → Add New → Upload Plugin**).
2. In the merchant portal, start a store connection and copy the connection code (`occs_…`, shown once).
3. In WordPress, go to **Settings → OnCharge Compliance Scanner**, paste the code and select **Save connection code**.
4. Back in the portal, select **Verify connection**, then run a scan.
5. Set up reviewer access: create a separate customer-level WordPress account with the same research access a verified buyer has, sign in as it once to check it shows products and prices, then enter its username under **Reviewer access** and tick the confirmation. Give the login to OnCharge yourself; the plugin never sends usernames or passwords.
The Compliance Scanner updates itself like Secure Checkout (from version 1.1.0; see [Updates](#updates)).
If your research gate blocks the WordPress REST API, allow the `oncharge-compliance-scanner/v1` routes. A gate plugin can answer the catalogue check itself with the `oncharge_compliance_scanner_reviewer_can_view_catalog` filter.
## Updates {#updates}
From version 1.6.0 the plugin updates itself. WordPress checks OnCharge for new versions twice a day and installs them in the background, the same way it updates plugins from WordPress.org.
- **Signed:** every update is signed with OnCharge's update key, and its checksum is verified before WordPress installs it. A changed or unsigned package is refused, so nothing else can push code to your store.
- **Your API key:** the download uses the store API key from the plugin settings. Keep it set, and updates keep working after you rotate it.
- **Turning it off:** Automatic updates are on by default. To install updates yourself instead, select **Disable auto-updates** next to the plugin on the **Plugins** screen; WordPress then shows each update for you to install.
Stores on 1.5.0 or earlier install 1.6.0 by hand once: download the ZIP from the merchant portal, upload it under **Plugins → Add New → Upload Plugin**, and choose **Replace current with uploaded**. Later versions arrive on their own.
## Troubleshooting
**The payment form does not load**
- Your site must use HTTPS.
- If you send a `Content-Security-Policy`, add `https://app.oncharge.io` to `frame-src`.
- Your domain must be registered for the store; the checkout can only be framed by registered domains.
- Turn on Debug Mode and check `wp-content/debug.log` for the API error code.
**Orders stay on hold**
- Check that `?wc-api=oncharge_callback` is reachable from the internet and not blocked by a firewall or security plugin.
- Check the order notes and `debug.log` for webhook errors.
**`invalid_signature` or `timestamp_expired` in the log**
- Paste the API secret again (no extra spaces) and check that it belongs to the same key.
- For webhook signature errors, paste the **Webhook Signing Secret** again; if you registered the webhook URL again, the portal issued a new secret.
- Make sure the server clock is correct (within 5 minutes).
**`domain_mismatch`**
- Register the exact host from **Settings → General → Site Address** (with or without `www`) for the store.
**Tracking numbers rejected**
- See the order note for the reason. OnCharge confirms deliveries by USPS, UPS, FedEx and DHL Express.
---
# Magento 2 (beta)
> **Beta.** The `OnCharge_Payments` module has passed its library tests (request signing, webhook verification, the compliance protocol test vectors, paging, carriers, amounts) but has not yet run on a live store. Its [README](https://oncharge.io/docs/files/magento/README.md) is the full reference. Contact OnCharge to join the beta.
The module adds OnCharge as a payment method to Magento Open Source and Adobe Commerce **2.4.4 or later** (PHP 8.1+). It creates the checkout session for each order with its shipping address, shows the OnCharge checkout by redirect or embedded in a store page, updates orders from signed webhooks, reports shipment tracking so delivered orders are paid out, refunds online from credit memos, and serves the [RUO compliance feed](https://oncharge.io/docs/compliance-feed).
## Install
The module is a Composer package (`oncharge/module-payments`). Add the package source OnCharge gives you as a Composer repository, then:
```bash
composer require oncharge/module-payments:^1.0
bin/magento module:enable OnCharge_Payments
bin/magento setup:upgrade
bin/magento setup:di:compile # production mode only
bin/magento setup:static-content:deploy -f # production mode only
bin/magento cache:flush
```
Magento's cron must run: the module uses it to process webhooks and resend pending tracking numbers.
## Configure
**Stores → Configuration → Sales → Payment Methods → OnCharge**
| Setting | |
|---|---|
| Enabled, Title, Description | What shoppers see at checkout. |
| API Key / API Secret | From the OnCharge portal. The secret is stored encrypted and never reaches the browser. |
| Environment | Production (`https://app.oncharge.io`). Use a custom base URL only if OnCharge support asks. |
| Payment Action | **Sale**: the order is invoiced when OnCharge confirms the payment. **Authorize**: the payment is recorded and you create the invoice (Capture Online checks with OnCharge that the payment was captured). |
| Checkout Display | **Redirect** to the OnCharge checkout page, or **Embedded** on a payment page in your store using the [hosted script](https://oncharge.io/docs/checkout#script-tag). |
| Callback Signing Secret | Register `https:///oncharge/webhook` as the store's webhook URL in the OnCharge portal and paste the `oc_cbsec_…` secret it shows once. |
| Countries, order total limits, sort order, debug logging | Standard payment method options. |
Register your store's domain under **Security → Domains** in the OnCharge portal: OnCharge accepts return URLs and framing only on registered domains.
## How it works
| In Magento | With OnCharge |
|---|---|
| The customer places the order | The order is created as **Pending Payment**. |
| The browser goes to `/oncharge/checkout/start` | [`POST /api/v1/checkout/sessions`](https://oncharge.io/docs/api#createcheckoutsession) with the amount, the increment ID as `order_id`, the shipping address and line items, and an idempotency key; then the redirect or the embedded page. |
| The shopper returns to `/oncharge/checkout/return` | The session status picks the page to show (success, or the cart restored). It never changes the order. |
| OnCharge calls `/oncharge/webhook` | `OnCharge-Signature` is verified (legacy header only when it is absent) and event IDs are deduplicated. `payment.captured` invoices the order (Sale) or records the authorization (Authorize) after checking amount and currency; `payment.refused` and `payment.cancelled` cancel it; `refund.succeeded` confirms refunds; `chargeback.opened` puts the order on hold; `delivery.confirmed` adds a comment. |
| A shipment tracking number is saved | [`POST /api/v1/shipments`](https://oncharge.io/docs/shipments); Magento carrier codes map to USPS, UPS, FedEx or DHL Express. The result is added as an order comment, and pending numbers are resent by cron every 15 minutes. |
| An online credit memo | [`POST /api/v1/refunds`](https://oncharge.io/docs/api#createrefund) with an idempotency key. |
## RUO stores: compliance review
The same settings page has a **Compliance Review** group:
1. In the OnCharge portal, add your store host, choose **Magento** and set the base path to `/oncharge/compliance`. Paste the one-time connection code (`occs_…`) into **Connection Code** and save.
2. Select **Verify connection** in the portal.
3. Set up reviewer access: a separate customer account with the same access a verified buyer has. Enter its email, sign in as it once to check that it shows every product with its price, then set **I Signed In as This Account** to **Yes**.
The feed serves active CMS pages and every enabled product with its own page (including products hidden from search), up to 5,000 items, at:
```text
GET /oncharge/compliance/proof?challenge=&ts=
GET /oncharge/compliance/content?cursor=&limit= (signed)
GET /oncharge/compliance/reviewer-access (signed)
```
## Building your own Magento integration
If you prefer to integrate yourself, follow [Custom & headless](https://oncharge.io/docs/headless): create the session from your payment method's server-side code, render the checkout with the [script tag](https://oncharge.io/docs/checkout#script-tag), handle webhooks in a CSRF-exempt controller and report tracking from a `sales_order_shipment_track_save_after` observer. The [PHP signing example](https://oncharge.io/docs/authentication#php) works as-is.
---
# Wix (beta)
> **Beta.** The OnCharge Wix integration is tested against a fake OnCharge and Wix's documented payloads, but has not yet run on a live Wix site. Its [README](https://oncharge.io/docs/files/wix/README.md) is the full reference, including what remains unverified. Contact OnCharge to join the beta.
The integration is a Velo **Payment Provider service plugin** plus backend code you add to your site. It takes card payments through the OnCharge hosted checkout, keeps Wix orders in step with OnCharge, reports shipment tracking (OnCharge pays out once the carrier confirms delivery), refunds from the Wix dashboard, and serves the [RUO compliance feed](https://oncharge.io/docs/compliance-feed).
**Requirements:** a Wix premium plan that accepts payments, a connected custom domain (OnCharge accepts return URLs and webhooks only on registered domains), and Dev Mode. Wix allows this kind of plugin only on the owner's own site, not in the App Market.
## How it plugs into Wix
| Wix calls | When | The integration |
|---|---|---|
| `connectAccount()` | You select **Connect** under Accept Payments | Checks the API key and secret with a signed request. |
| `createTransaction()` | A buyer places an order | [`POST /api/v1/checkout/sessions`](https://oncharge.io/docs/api#createcheckoutsession) (with the shipping address, line items and `Idempotency-Key: wix-`) and sends the buyer to the OnCharge checkout. |
| `refundTransaction()` | You refund from the Orders page | [`POST /api/v1/refunds`](https://oncharge.io/docs/api#createrefund). |
Payment results reach Wix through an HTTP function that verifies the OnCharge webhook and updates the Wix transaction. Fulfillments are reported to [`POST /api/v1/shipments`](https://oncharge.io/docs/shipments), with an hourly job resending numbers OnCharge could not judge yet.
## Set up
1. **Turn on Dev Mode** in the Wix editor (Wix Studio has the code panel on by default).
2. **Add the payment plugin:** Code sidebar → **Public & Backend** → **Service Plugins** → **+** → **Payment**, named `oncharge`. Replace the generated files with the integration's.
3. **Add the backend files** from the integration package (`http-functions.js`, `events.js`, `jobs.config` and the `oncharge/` folder), and install `@wix/stores` and `@wix/essentials`.
4. **Create the CMS collection** `OnChargeLog` with admin-only permissions (fields `kind` and `data`). It holds session IDs, handled webhook IDs, compliance nonces and pending tracking numbers; no card data or secrets.
5. **Save the secrets** in **Developer Tools → Secrets Manager**: `oncharge_api_key`, `oncharge_api_secret`, `oncharge_webhook_secret` and, for RUO stores, `oncharge_compliance_code`. They are read only in backend code.
6. **Edit `backend/oncharge/config.js`**: your site's domain, policy page paths and reviewer settings.
7. **Publish the site.** Service plugins, HTTP functions and backend events run only on the published site.
8. **In the OnCharge portal:** register the site's domain under **Security → Domains**, and register `https:///_functions/onchargeWebhook` as the store's webhook URL. Save the signing secret it shows as `oncharge_webhook_secret`, then publish again.
9. **Connect OnCharge in Wix:** Dashboard → Settings → **Accept Payments** → **See More Payment Options** → OnCharge → **Connect**. OnCharge then appears at checkout as "Credit / Debit Card".
## Endpoints
Wix names an HTTP function after its exported JavaScript function, which cannot contain a hyphen, so the paths are camel case.
| URL | Purpose |
|---|---|
| `POST https:///_functions/onchargeWebhook` | OnCharge webhooks |
| `GET https:///_functions/onchargeReturn` | Return URL of each checkout session (signed state; redirects to the matching Wix page) |
| `GET https:///_functions/onchargeCompliance/proof` | Compliance feed: ownership proof |
| `GET https:///_functions/onchargeCompliance/content` | Compliance feed: catalogue (signed) |
| `GET https:///_functions/onchargeCompliance/reviewer-access` | Compliance feed: reviewer login status (signed) |
Webhooks: `payment.captured` approves the Wix transaction after checking amount and currency; `payment.pending`, `payment.refused` and `payment.cancelled` set the matching Wix status; refund, chargeback and delivery events are logged. Refunds issued in the OnCharge portal are not mirrored into Wix.
## RUO stores: compliance review
In the OnCharge portal, add your host, choose **Wix** and set the feed base path to **`/_functions/onchargeCompliance`**. Save the connection code as `oncharge_compliance_code`, publish, then select **Verify connection**. For reviewer access, create a separate site member with the same access a verified buyer has, set its login email in `config.js`, sign in as it once to check it shows every product with its price, confirm it in `config.js` and publish.
## Notes
- All OnCharge API calls run in backend code, where the secrets are available. Page code never sees them.
- Use USPS, UPS, FedEx or DHL Express in Wix fulfillments so OnCharge can confirm delivery; other carriers are sent without a carrier name.
---
# Next.js
This guide adds OnCharge to a Next.js (App Router) store: a server action creates the checkout session, a client component embeds the checkout, a route handler receives webhooks, and an admin action reports shipments. It uses `@oncharge/node` and `@oncharge/js`.
> **Coming soon to npm.** `@oncharge/node` and `@oncharge/js` are not yet published. Until they are, use the dependency-free [`onchargeRequest()` helper](https://oncharge.io/docs/authentication#nodejs), the [webhook verifier](https://oncharge.io/docs/webhooks#nodejs) and the [plain iframe component](#without-the-sdks) at the end of this page.
## Environment
```bash title=".env.local"
ONCHARGE_API_KEY=oc_key_...
ONCHARGE_API_SECRET=oc_sec_...
ONCHARGE_WEBHOOK_SECRET=oc_cbsec_...
```
Never prefix these with `NEXT_PUBLIC_`: that would ship them to the browser.
## 1. A server-only client
```ts title="lib/oncharge.ts"
import 'server-only';
import { OnCharge } from '@oncharge/node';
export const oncharge = new OnCharge({
apiKey: process.env.ONCHARGE_API_KEY!,
apiSecret: process.env.ONCHARGE_API_SECRET!,
});
```
## 2. Create the session on the server
Compute the amount from your own database, never from the browser.
```ts title="app/checkout/[orderId]/page.tsx"
import { oncharge } from '@/lib/oncharge';
import { getOrder } from '@/lib/orders';
import { CheckoutFrame } from './checkout-frame';
export const dynamic = 'force-dynamic';
export default async function CheckoutPage({ params }: { params: Promise<{ orderId: string }> }) {
const { orderId } = await params;
const order = await getOrder(orderId);
const session = await oncharge.checkout.sessions.create(
{
amount: order.totalCents,
currency: 'USD',
reference: `order-${order.id}`,
order_id: order.id,
return_url: `https://shop.example.com/checkout/${order.id}/complete`,
customer_email: order.email,
shipping: order.requiresShipping
? {
name: order.shipping.name,
line1: order.shipping.line1,
line2: order.shipping.line2,
city: order.shipping.city,
state: order.shipping.state,
postal_code: order.shipping.postalCode,
country: order.shipping.country,
}
: undefined,
},
{ idempotencyKey: `order-${order.id}` },
);
await saveSessionId(order.id, session.session_id);
return ;
}
```
The same idempotency key returns the same open session if the page is reloaded within 50 minutes.
These pages are written for Next.js 15, where `params` is a promise. On Next.js 14, `params` is a plain object: type it as `{ orderId: string }` and read `params.orderId` without `await`.
## 3. Embed the checkout
```tsx title="app/checkout/[orderId]/checkout-frame.tsx"
'use client';
import { useRouter } from 'next/navigation';
import { OnChargeCheckout } from '@oncharge/js/react';
export function CheckoutFrame({ url, orderId }: { url: string; orderId: string }) {
const router = useRouter();
return (
router.push(`/checkout/${orderId}/complete`)}
onRedirect={({ url: target }) => window.location.assign(target)}
onError={(error) => console.warn('OnCharge checkout error', error)}
/>
);
}
```
Prefer a full-page redirect? Replace the component with `redirect(session.checkout_url)` from `next/navigation` in the page.
## 4. Receive webhooks
```ts title="app/api/webhooks/oncharge/route.ts"
import { createWebhookHandler } from '@oncharge/node/next';
import { markOrderPaid, markOrderFailed, recordRefund, flagOrder } from '@/lib/orders';
export const { POST } = createWebhookHandler({
secret: process.env.ONCHARGE_WEBHOOK_SECRET!,
async onEvent(event) {
const orderId = event.data.order_id;
switch (event.type) {
case 'payment.captured':
await markOrderPaid(orderId, event.data.session_id);
break;
case 'payment.refused':
case 'payment.cancelled':
await markOrderFailed(orderId);
break;
case 'refund.succeeded':
await recordRefund(orderId, event.data.amount);
break;
case 'chargeback.opened':
await flagOrder(orderId);
break;
}
},
});
```
Register `https://shop.example.com/api/webhooks/oncharge` as the store's webhook URL in the merchant portal. The handler skips repeated event IDs in memory; on serverless or with several instances, pass `eventIdStore: { has(id), add(id) }` backed by your database so a retry that lands on another instance is still recognised.
## 5. The return page
```tsx title="app/checkout/[orderId]/complete/page.tsx"
import { getOrder } from '@/lib/orders';
export const dynamic = 'force-dynamic';
export default async function Complete({ params }: { params: Promise<{ orderId: string }> }) {
const { orderId } = await params;
const order = await getOrder(orderId);
return order.paid ? Thank you! Your order is confirmed.
: We are confirming your payment. This page will update shortly.
;
}
```
`order.paid` is set by the webhook. To check without waiting, call `oncharge.checkout.sessions.retrieve(sessionId)` with the saved session ID.
## 6. Report shipments
```ts title="app/admin/orders/actions.ts"
'use server';
import { oncharge } from '@/lib/oncharge';
export async function markShipped(orderId: string, carrier: string, trackingNumber: string) {
const result = await oncharge.shipments.report({
order_id: orderId,
shipments: [{ carrier, tracking_number: trackingNumber }],
});
const rejected = result.shipments.filter((s) => s.status === 'rejected');
if (rejected.length) throw new Error(rejected.map((s) => s.message).join('; '));
}
```
## 7. Refunds
```ts
await oncharge.refunds.create({ session_id: sessionId, amount: 1500, currency: 'USD', reference: `refund-${refundId}` });
```
## 8. RUO stores: the compliance feed
```ts title="app/.well-known/oncharge-compliance/[route]/route.ts"
import { createComplianceFeedRoute } from '@oncharge/node/next';
import { listPublishedCatalog } from '@/lib/catalog';
export const dynamic = 'force-dynamic';
export const { GET } = createComplianceFeedRoute({
connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
host: 'shop.example.com',
site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
listItems: async ({ cursor, limit }) => listPublishedCatalog(cursor, limit), // → { items, nextCursor, truncated? }
});
```
See [RUO compliance feed](https://oncharge.io/docs/compliance-feed).
## Content Security Policy
If you set a CSP in `next.config.js` or middleware, allow the checkout frame:
```js title="next.config.js"
const csp = ["frame-src 'self' https://app.oncharge.io"].join('; ');
module.exports = {
async headers() {
return [{ source: '/checkout/:path*', headers: [{ key: 'Content-Security-Policy', value: csp }] }];
},
};
```
## Without the SDKs
Until the packages are published, this client component replaces `OnChargeCheckout`:
```tsx title="app/checkout/[orderId]/checkout-frame.tsx"
'use client';
import { useEffect, useMemo, useRef, useState } from 'react';
export function CheckoutFrame({ url, orderId }: { url: string; orderId: string }) {
const frame = useRef(null);
const [height, setHeight] = useState(480);
const [src, setSrc] = useState(null);
const nonce = useMemo(() => Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join(''), []);
useEffect(() => {
const checkout = new URL(url);
checkout.searchParams.set('embed', '1');
checkout.searchParams.set('parent_origin', window.location.origin);
checkout.searchParams.set('embed_nonce', nonce);
setSrc(checkout.toString());
function onMessage(event: MessageEvent) {
if (event.origin !== checkout.origin || event.source !== frame.current?.contentWindow) return;
const msg = event.data;
if (!msg || msg.source !== 'oncharge-checkout' || msg.version !== 1 || msg.nonce !== nonce) return;
if ((msg.type === 'ready' || msg.type === 'resize') && typeof msg.height === 'number') setHeight(Math.max(480, Math.ceil(msg.height)));
if (msg.type === 'complete') window.location.href = `/checkout/${orderId}/complete`;
if (msg.type === 'redirect' && typeof msg.url === 'string') window.location.assign(msg.url);
}
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
}, [url, orderId, nonce]);
if (!src) return null;
return ;
}
```
On the server, `session.checkout_url` becomes `new URL(session.iframe_url, 'https://app.oncharge.io').href`.
---
# React
A React single-page app (Vite, Create React App and similar) cannot hold your API secret, so the integration has two halves:
- **Your backend** (here, Express) creates checkout sessions, receives webhooks and reports shipments.
- **Your React app** asks the backend for a checkout URL and shows it with ``.
> **Coming soon to npm.** `@oncharge/node` and `@oncharge/js` are not yet published. Until they are, use the [`onchargeRequest()` helper](https://oncharge.io/docs/authentication#nodejs) on the backend and the [plain iframe component](https://oncharge.io/docs/nextjs#without-the-sdks) in React (drop the `'use client'` line).
## Backend
```js title="server/index.mjs"
import express from 'express';
import { OnCharge } from '@oncharge/node';
const app = express();
const oncharge = new OnCharge({ apiKey: process.env.ONCHARGE_API_KEY, apiSecret: process.env.ONCHARGE_API_SECRET });
// Webhooks need the raw body, so register this route before express.json().
app.post('/api/webhooks/oncharge', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = OnCharge.webhooks.constructEvent(req.body.toString('utf8'), req.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET, {
toleranceSeconds: 300,
});
} catch {
return res.status(400).send('Invalid signature');
}
if (event.type === 'payment.captured') await orders.markPaid(event.data.order_id, event.data.session_id);
if (event.type === 'payment.refused' || event.type === 'payment.cancelled') await orders.markFailed(event.data.order_id);
res.sendStatus(200);
});
app.use(express.json());
// The browser sends only the order ID; the amount comes from your database.
app.post('/api/checkout', async (req, res) => {
const order = await orders.get(req.body.orderId);
if (!order || order.paid) return res.status(404).json({ error: 'order_not_found' });
const session = await oncharge.checkout.sessions.create(
{
amount: order.totalCents,
currency: order.currency,
reference: `order-${order.id}`,
order_id: order.id,
return_url: `https://shop.example.com/orders/${order.id}`,
customer_email: order.email,
shipping: order.shippingAddress, // { name, line1, line2, city, state, postal_code, country }
},
{ idempotencyKey: `order-${order.id}` },
);
res.json({ checkoutUrl: session.checkout_url });
});
app.listen(3001);
```
## React component
```tsx title="src/Checkout.tsx"
import { useEffect, useState } from 'react';
import { OnChargeCheckout } from '@oncharge/js/react';
export function Checkout({ orderId }: { orderId: string }) {
const [checkoutUrl, setCheckoutUrl] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ orderId }),
})
.then((res) => (res.ok ? res.json() : Promise.reject(new Error('Could not start checkout'))))
.then((data) => setCheckoutUrl(data.checkoutUrl))
.catch((err) => setError(err.message));
}, [orderId]);
if (error) return {error}
;
if (!checkoutUrl) return Loading secure checkout…
;
return (
{
window.location.href = `/orders/${orderId}`;
}}
onRedirect={({ url }) => window.location.assign(url)}
onError={(err) => console.warn(err)}
/>
);
}
```
The order page reads the order from your backend; it shows "paid" once the `payment.captured` webhook has arrived.
## Notes
- Never put `ONCHARGE_API_SECRET` in `VITE_*`, `REACT_APP_*` or any variable your bundler exposes.
- The page that shows the checkout must be on a registered store domain over HTTPS. For local development, use the [redirect flow](https://oncharge.io/docs/checkout#hosted-redirect) or register a staging domain.
- Report tracking numbers from your backend with `oncharge.shipments.report(...)` when orders ship. See [Shipments & payouts](https://oncharge.io/docs/shipments).
---
# HTML & iframe
Any website with a small server-side endpoint can take OnCharge payments. The endpoint creates the checkout session (it holds the API secret); the page shows the checkout with a script tag or a plain iframe.
## The page
```html title="checkout.html"
Checkout
Pay for order #1001
```
`mountCheckout` adds the embed parameters, checks each message's origin, source and nonce, and resizes the frame; the options are listed under [Script tag](https://oncharge.io/docs/checkout#script-tag). Prefer no external script? Use the [plain iframe and message listener](https://oncharge.io/docs/checkout#embedded-iframe) instead.
No JavaScript at all? Make `/create-checkout` respond with a `303` redirect to the checkout URL and submit a normal form to it. That is the [hosted redirect](https://oncharge.io/docs/checkout#hosted-redirect) flow.
## The endpoint
Each version reads the order from your database, creates the session and returns `{ "checkoutUrl": … }`. They use the signing helpers from [Authentication & signing](https://oncharge.io/docs/authentication#examples), saved as their own files without the example calls at the bottom.
### Node (Express)
```js title="server.mjs"
import express from 'express';
import { onchargeRequest } from './oncharge.mjs'; // the Authentication page's helper, without its example calls
const app = express();
app.use(express.static('public'));
app.post('/create-checkout', express.json(), async (req, res) => {
const order = await db.orders.find(req.body.orderId); // your data
const session = await onchargeRequest(
'POST',
'/api/v1/checkout/sessions',
{
amount: order.totalCents,
currency: 'USD',
reference: `order-${order.id}`,
order_id: String(order.id),
return_url: `https://shop.example.com/order-complete.html?order=${order.id}`,
customer_email: order.email,
shipping: order.shipping, // { name, line1, line2, city, state, postal_code, country }
},
{ idempotencyKey: `order-${order.id}` },
);
res.json({ checkoutUrl: new URL(session.iframe_url, 'https://app.oncharge.io').href });
});
app.listen(3000);
```
### PHP
```php title="create-checkout.php"
$order['total_cents'],
'currency' => 'USD',
'reference' => 'order-' . $order['id'],
'order_id' => (string) $order['id'],
'return_url' => 'https://shop.example.com/order-complete.php?order=' . $order['id'],
'customer_email' => $order['email'],
'shipping' => $order['shipping'], // name, line1, line2, city, state, postal_code, country
], 'order-' . $order['id']);
header('Content-Type: application/json');
echo json_encode(['checkoutUrl' => 'https://app.oncharge.io' . $session['iframe_url']]);
```
### Python (Flask)
```python title="app.py"
from flask import Flask, jsonify, request
from oncharge import oncharge_request # the Authentication page's helper, without its example calls
app = Flask(__name__, static_folder="public", static_url_path="")
@app.post("/create-checkout")
def create_checkout():
order = find_order(request.get_json()["orderId"]) # your data
session = oncharge_request(
"POST",
"/api/v1/checkout/sessions",
{
"amount": order["total_cents"],
"currency": "USD",
"reference": f"order-{order['id']}",
"order_id": str(order["id"]),
"return_url": f"https://shop.example.com/order-complete.html?order={order['id']}",
"customer_email": order["email"],
"shipping": order["shipping"],
},
idempotency_key=f"order-{order['id']}",
)
return jsonify(checkoutUrl="https://app.oncharge.io" + session["iframe_url"])
```
## Then
1. Add a [webhook endpoint](https://oncharge.io/docs/webhooks) (examples for Node, PHP and Python) and mark orders paid on `payment.captured`.
2. Report tracking numbers when you ship: [Shipments & payouts](https://oncharge.io/docs/shipments).
3. Register the domain that serves `checkout.html` for the store in the merchant portal.
## Site builders (Webflow, Framer, Squarespace, …)
Site builders let you add the page part with an **embed / custom code** element, but you still need a server for `/create-checkout` and the webhook, because the API secret cannot live in the page. Use a small serverless function (on any host you like) with the Node or Python endpoint above, call it from the embed, and register both the site's domain and the function's webhook URL in the portal. Order data then lives in your own backend, not in the site builder.
---
# Custom & headless
This page is the complete server-side contract for a custom or headless store (your own checkout, or a commerce backend with a separate storefront). Every platform guide is a special case of it.
## The flow
```text
Shopper Your storefront / server OnCharge
| checkout ------> 1. POST /api/v1/checkout/sessions -------> session_id, iframe_url
| <------- 2. show checkout (redirect or iframe on your domain)
| pays in the OnCharge checkout --------------------------------->
| 3. POST /api/v1/checkout/sessions/{id}/order (if the order was created after the session)
| 4. webhook payment.captured <---------------- signed POST to your endpoint
| 5. fulfil, then POST /api/v1/shipments -----> carrier tracking
| 6. webhook delivery.confirmed <-------------- payout released 1 day later
```
## What to store
Keep these on your order record:
| Field | From |
|---|---|
| `oncharge_session_id` | `session_id` from session creation. Every later call uses it. |
| `oncharge_status` | The latest webhook `data.status`. |
| `oncharge_reference` | The `reference` you sent (your order number or cart ID). |
| Processed webhook IDs | `OnCharge-Event-Id`, to skip duplicates. |
## 1. Create the session
Server-side, from the cart or order you hold. Never accept an amount from the browser.
- `reference`: your order number, or the cart ID if the order does not exist yet.
- `Idempotency-Key`: the same order or cart ID, so double clicks and retries return the same session.
- `shipping`: the delivery address for anything you ship (needed for payout on delivery).
- `return_url`: on a registered store domain.
- If the cart changes (amount, currency or address), create a new session with a new idempotency key (for example `cart-123-v2`).
## 2. Show the checkout
Redirect to `https://app.oncharge.io` + `iframe_url`, or embed it on a page served from a registered domain. See [Checkout](https://oncharge.io/docs/checkout).
## 3. Attach the order (cart-first checkouts)
If your platform creates the order only after payment starts, attach it as soon as it exists:
```http
POST /api/v1/checkout/sessions/{session_id}/order
{ "order_id": "1001", "shipping": { … } }
```
Values are set once. Retry failures for up to 24 hours (after that, and after tracking is reported, the address can no longer be recorded).
## 4. Webhooks
Handle at least `payment.captured`, `payment.refused`, `payment.cancelled`, `refund.succeeded` and `chargeback.opened`. See [Webhooks](https://oncharge.io/docs/webhooks). Reconcile anything missed by reading [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession), for example for orders still pending after an hour.
| Session status | Set your order to |
|---|---|
| `created`, `pending` | Awaiting payment |
| `authorized` | Payment approved (wait for capture) |
| `captured` | Paid |
| `refused`, `cancelled`, `expired`, `error` | Payment failed / abandoned |
## 5. Shipments
Report carrier and tracking numbers with [`POST /api/v1/shipments`](https://oncharge.io/docs/shipments) when labels are created or orders are marked shipped (USPS, UPS, FedEx, DHL Express). Store the per-number results; show rejected numbers to your staff. Poll [`GET /api/v1/shipments?session_id=…`](https://oncharge.io/docs/api#getdeliverystatus) or listen for `delivery.confirmed`.
## 6. Refunds, cancellations, disputes
- **Refund** a captured payment: [`POST /api/v1/refunds`](https://oncharge.io/docs/api#createrefund) with `Idempotency-Key` = your refund ID.
- **Cancel** an authorized, uncaptured payment: [`POST /api/v1/checkout/sessions/{id}/cancel`](https://oncharge.io/docs/api#cancelcheckoutsession).
- **Disputes**: list with [`GET /api/v1/disputes`](https://oncharge.io/docs/api#listdisputes) and upload evidence before `defense_deadline`. When a dispute has `responded_by: "oncharge"`, the OnCharge team submits the response from your uploads and the defend, accept and auto-defend calls return `409 responded_by_oncharge`; otherwise defend or accept it yourself. Or use the merchant portal.
## Retries and errors
| Situation | Do this |
|---|---|
| Network error or timeout | Retry with the same `Idempotency-Key`. |
| `429 rate_limited` | Wait until `X-RateLimit-Reset`, then retry. |
| `5xx` | Retry with exponential backoff. |
| `401` | Fix signing (see [Errors](https://oncharge.io/docs/authentication#errors)); do not retry blindly. |
| `400 validation_error` | Fix the request; the message names each invalid field. |
| `409` | The action does not fit the payment's state; read the session first. |
## Platform notes
**Shopify (headless / Hydrogen).** OnCharge is not a Shopify payments app, so it cannot appear inside Shopify's own checkout. A headless storefront with its own checkout page can take payment with OnCharge and then record the order in Shopify from your server (for example as a paid draft order via the Admin API) when the `payment.captured` webhook arrives. Check that this fits your Shopify plan and terms before you build it.
**Medusa, Saleor, commercetools and similar.** Implement OnCharge as a payment provider/plugin of the platform: create the session in the provider's "initiate payment" step, attach the order on "authorize", map webhooks to the platform's payment status updates, and report tracking from the fulfilment step.
**Mobile apps.** Create the session from your backend and open the checkout URL in the system browser or an in-app browser tab, with `return_url` pointing at a page (or universal link) that returns to the app. Confirm the payment from your backend, never from the app.
---
# API reference
Every endpoint of the OnCharge merchant API, generated from the [OpenAPI 3.1 spec](https://oncharge.io/openapi.json) (version 1.0.0). The base URL is `https://app.oncharge.io`. Every request is signed as described in [Authentication & signing](https://oncharge.io/docs/authentication): the `X-Oncharge-Key`, `X-Oncharge-Timestamp` and `X-Oncharge-Signature` headers are required on every call and are not repeated below.
- Amounts are integers in minor units; currencies are ISO 4217 codes.
- Errors are JSON `{ "error": "", "message": "" }`. Every endpoint can also return `401` (authentication: `missing_auth`, `invalid_timestamp`, `timestamp_expired`, `invalid_key`, `invalid_signature`), `403` (`store_inactive`: the store is pending or suspended; `domain_mismatch`), `429` (`rate_limited`), `500` (`internal_error`) and `503` (`service_unavailable`); see [Errors](https://oncharge.io/docs/authentication#errors). Endpoint tables below list only the other statuses.
- Every endpoint accepts an optional `X-Store-Domain` header; if a request carries `Origin`, `Referer` or `X-Store-Domain`, one of them must match a registered store domain.
- Send `Idempotency-Key` on session creation, cancellation and refunds.
## Checkout sessions {#checkout-sessions}
Start a payment and show OnCharge's hosted or embedded checkout.
### Create a checkout session {#createcheckoutsession}
```http
POST /api/v1/checkout/sessions
```
Creates a checkout session for one order or cart. Show the shopper the returned
`iframe_url` (a path on `https://app.oncharge.io`), either embedded in an iframe on one of
your registered domains or as a full-page redirect.
`return_url` must be on one of the store's registered domains. Sessions expire 30 minutes
after creation.
Send an `Idempotency-Key` to make retries safe: while a session created with the same key
is still open (`created` or `pending`) and less than 50 minutes old, the same session is
returned with status 200 instead of a new one.
For physical goods, send `shipping`: OnCharge releases the payout after the carrier
confirms delivery to this address, and the address cannot be changed later. When the
session is for an existing order (`order_id` is given) and the order ships by carrier,
`shipping` is required (`422 shipping_address_required`). A session created from a cart,
before the order exists, may attach the address later with
`POST /api/v1/checkout/sessions/{session_id}/order`; such a response carries
`shipping_required: true`, and tracking for the order is refused until the address is on file.
Card payments are accepted in `USD` only for now (`400 currency_not_supported`).
On a store that sells both shipped and unshipped things, set `requires_shipping` on each
line item: an order with a shipped item is paid out after carrier-confirmed delivery, one
without it 7 days after payment.
A store closed to new payments answers `403 store_checkout_closed`; a session that is already open can then no longer be paid (the checkout shows an error).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `amount` | integer (≥ 1) | Yes | Amount in the currency's minor unit (cents for USD). |
| `currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `reference` | string (min 1 chars, max 255 chars) | Yes | Your reference for this payment (order number or cart ID). Returned in webhooks. |
| `return_url` | string (uri) | Yes | Where the shopper is sent after checkout. Must be on a registered store domain. |
| `order_id` | string (max 255 chars) | No | Your order ID, if the order already exists. Otherwise attach it later. |
| `customer_email` | string (email) | No | |
| `customer_phone` | string | No | E.164 format recommended (`+15551234567`). |
| `metadata` | object | No | Your own key-value data, stored with the session. |
| `shipping` | object | No | Where the order ships. OnCharge matches the carrier's delivery location against `postal_code` (US, first five digits) or `city` + `state`. Send at least `postal_code` or `city`. |
| `shipping.name` | string (max 200 chars) | No | |
| `shipping.line1` | string (max 300 chars) | No | |
| `shipping.line2` | string (max 300 chars) | No | |
| `shipping.city` | string (max 120 chars) | No | |
| `shipping.state` | string (max 120 chars) | No | |
| `shipping.postal_code` | string (max 20 chars) | No | |
| `shipping.country` | string (max 60 chars) | No | ISO 3166-1 alpha-2 code recommended (`US`). |
| `line_items` | array of object | No | |
| `line_items[].description` | string | Yes | |
| `line_items[].quantity` | integer (≥ 1) | Yes | |
| `line_items[].amount_including_tax` | integer (≥ 0) | Yes | Line amount in minor units, tax included. |
| `line_items[].requires_shipping` | boolean | No | Whether this item is shipped. On a store that sells both shipped and unshipped things, an order with any shipped item is paid out after carrier-confirmed delivery; one whose items all say `false`, 7 days after payment. Without it, the order is decided by whether it has a shipping address. |
| `line_items[].tax_category` | one of `general_goods`, `nontaxable`, `services`, `electronic_services`, `clothing`, `software_download`, `saas`, `books`, `ebooks`, `music_download`, `dietary_supplements`, `otc_drugs`, `cosmetics`, `candy`, `groceries`, `prepared_food`, `pet_food`, `gift_cards` | No | An OnCharge product tax category. |
| `customer_id` | string (uuid) | No | Your OnCharge customer (POST /api/v1/customers): the payment is theirs, and a card they choose to save is saved for them. |
| `save_card` | boolean | No | Offer the shopper to save their card for your store: a box they must tick (card payments on stores with their own card account). Charge the saved card later with POST /api/v1/customers/{customer_id}/charges. Needs `customer_id` or `customer_email`. Default `false`. |
| `tax` | object | No | Sales tax for this payment, when your store has it on (Settings → Sales tax). With `enabled`, `amount` is the order as you list it (before tax, unless your store lists prices with tax included); line items (`amount_including_tax` is then each line's total as listed) and `shipping_amount` must add up to it. Tax is calculated for the shipping address, or `billing_address` when nothing ships. See /docs/sales-tax. |
| `tax.enabled` | boolean | Yes | Calculate sales tax. Store plugins that already add their platform's tax should leave this off. |
| `tax.shipping_amount` | integer (≥ 0) | No | The shipping charge inside `amount`, minor units: taxed as shipping. |
| `tax.billing_address` | object | No | |
| `tax.billing_address.line1` | string (max 300 chars) | No | |
| `tax.billing_address.line2` | string (max 300 chars) | No | |
| `tax.billing_address.city` | string (max 120 chars) | No | |
| `tax.billing_address.state` | string (max 120 chars) | No | Two-letter US state (or its name). |
| `tax.billing_address.postal_code` | string (max 20 chars) | Yes | Five-digit US ZIP code (ZIP+4 accepted). |
| `tax.billing_address.country` | string (max 60 chars) | No | US only for now. Defaults to US. |
```json title="Request"
{
"amount": 4900,
"currency": "USD",
"reference": "order-1001",
"return_url": "https://shop.example.com/checkout/complete?order=1001",
"order_id": "1001",
"customer_email": "shopper@example.com",
"shipping": {
"name": "Alex Rivera",
"line1": "500 Market St",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
"country": "US"
},
"line_items": [
{
"description": "Example product",
"quantity": 1,
"amount_including_tax": 4900
}
]
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `status` | one of `created`, `pending`, `authorized`, `captured`, `refused`, `cancelled`, `error`, `expired` | Yes | `created` (waiting for the shopper), `pending` (the shopper must complete a step), `authorized` (approved, not yet captured), `captured` (paid), `refused` (declined), `cancelled`, `error`, `expired` (not paid within 30 minutes). |
| `iframe_url` | string | Yes | Path of the checkout page relative to `https://app.oncharge.io`, including the pay token. Prefix it with the API base URL to get the full checkout URL. |
| `pay_token` | string | Yes | Short-lived token (30 minutes) that authorizes the checkout page. Already included in `iframe_url`. |
| `created_at` | string (date-time) | Yes | |
| `expires_at` | string (date-time) | Yes | |
| `shipping_required` | boolean | No | Present (true) when the order ships by carrier and has no shipping address yet. Attach it with `POST /api/v1/checkout/sessions/{session_id}/order`; tracking is refused until it is on file. |
| `amount` | integer | No | With sales tax: what the shopper pays (the calculated total, once the address is known). |
| `tax` | object or null | No | Sales tax on a payment; null when it is not taxed. |
| `tax.status` | one of `awaiting_address`, `calculated`, `pending`, `failed`, `collected`, `partly_refunded`, `refunded` | Yes | `awaiting_address`: no address yet, the payment waits. `calculated`: not paid yet. `pending`: tax included, charged while the calculation was unavailable; worked out shortly. `failed`: the calculation failed (`error`), the payment waits. `collected`, `partly_refunded`, `refunded`: paid, and how much of the tax was given back. |
| `tax.inclusive` | boolean | Yes | true when the listed prices include the tax. |
| `tax.currency` | string or null | Yes | |
| `tax.subtotal` | integer or null | Yes | Before tax, minor units. |
| `tax.amount` | integer or null | Yes | The tax, minor units. |
| `tax.total` | integer or null | Yes | What the customer pays, minor units. |
| `tax.shipping` | integer | Yes | The shipping charge inside the total, minor units. |
| `tax.jurisdictions` | array of object | Yes | |
| `tax.jurisdictions[].state` | string or null | No | |
| `tax.jurisdictions[].rate` | string | No | Combined percent, e.g. "8.25". |
| `tax.jurisdictions[].amount` | integer | No | |
| `tax.refunded` | integer | Yes | Tax given back so far with refunds and lost disputes, minor units. |
| `tax.error` | string or null | Yes | `tax_address_invalid` or `tax_unavailable` when `status` is `failed`. |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"status": "created",
"iframe_url": "/checkout/8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11?token=pt_eyJzZXNzaW9uSWQiOi4uLn0.3f9c",
"pay_token": "pt_eyJzZXNzaW9uSWQiOi4uLn0.3f9c",
"created_at": "2026-01-01T00:00:00.000Z",
"expires_at": "2026-01-01T00:30:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay: an open session created with the same `Idempotency-Key` within the last 50 minutes. A fresh `pay_token` is issued. |
| `201` | Session created. |
| `400` | `validation_error`, `invalid_json`, `invalid_return_url` (the return URL is not on a registered store domain), `no_domains` (the store has no registered domain) or `currency_not_supported` (card payments are accepted in USD only). |
| `403` | `store_inactive` (the store is not active yet, for example while its processing account is being opened, or it is suspended), `store_checkout_closed` (OnCharge has closed the store to new payments, for example while the account is being offboarded; shipments and refunds still work), `domain_mismatch`, or `global_ban` (the shopper's email or phone is blocked across OnCharge; show the `message` to the shopper and do not retry). |
| `422` | `shipping_address_required`: the order ships by carrier and `order_id` was given, but no `shipping` address (postal code or city). The order is paid out only after the carrier confirms delivery to that address. Show the `message` to the shopper. |
### Retrieve a checkout session {#getcheckoutsession}
```http
GET /api/v1/checkout/sessions/{session_id}
```
Returns the session's current status. Use it to confirm a payment server-side (for
example when the shopper lands on your `return_url`) in addition to webhooks.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `session_id` | path | string (uuid) | Yes | The checkout session ID returned when the session was created. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `store_id` | string (uuid) | Yes | |
| `order_id` | string or null | No | |
| `amount` | integer (≥ 1) | Yes | Amount in the currency's minor unit (cents for USD). |
| `currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `status` | one of `created`, `pending`, `authorized`, `captured`, `refused`, `cancelled`, `error`, `expired` | Yes | `created` (waiting for the shopper), `pending` (the shopper must complete a step), `authorized` (approved, not yet captured), `captured` (paid), `refused` (declined), `cancelled`, `error`, `expired` (not paid within 30 minutes). |
| `payment_reference` | string | Yes | OnCharge's reference for the payment: `ocpay_` and the session id in lowercase hex without dashes, for every session. Never a payment processor id. |
| `psp_reference` | string or null | No | Kept with its meaning for existing integrations: for a session created before the reference cutoff (2026-12-01T00:00:00Z by default; see the OnCharge references guide), its original payment reference (null before payment); for a session created at or after it, the same `ocpay_` reference as `payment_reference`. New integrations should read `payment_reference`. **Deprecated.** |
| `payment_method` | one of `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm`, `afterpay`, or `null` | No | How the shopper paid: `card`, or a way to pay beyond cards the store turned on (bank debit, Cash App Pay, Klarna, Affirm, Afterpay; see the Payment methods guide). Null for crypto. |
| `settlement` | one of `verify_deposits`, `processing`, `settled`, or `null` | No | A bank debit's collection: `verify_deposits` while the shopper confirms their account with the test deposits, `processing` while the debit is collected (up to 4 business days), `settled` once it cleared. Null for every other method. Ship once `status` is `captured`. |
| `risk_decision` | one of `accept`, `review`, `reject`, or `null` | No | Outcome of the checkout risk check. |
| `risk_score` | number or null | No | Risk score 0–100. |
| `created_at` | string (date-time) | Yes | |
| `updated_at` | string (date-time) | Yes | |
| `expires_at` | string (date-time) | Yes | |
| `tax` | object or null | No | Sales tax on a payment; null when it is not taxed. |
| `tax.status` | one of `awaiting_address`, `calculated`, `pending`, `failed`, `collected`, `partly_refunded`, `refunded` | Yes | `awaiting_address`: no address yet, the payment waits. `calculated`: not paid yet. `pending`: tax included, charged while the calculation was unavailable; worked out shortly. `failed`: the calculation failed (`error`), the payment waits. `collected`, `partly_refunded`, `refunded`: paid, and how much of the tax was given back. |
| `tax.inclusive` | boolean | Yes | true when the listed prices include the tax. |
| `tax.currency` | string or null | Yes | |
| `tax.subtotal` | integer or null | Yes | Before tax, minor units. |
| `tax.amount` | integer or null | Yes | The tax, minor units. |
| `tax.total` | integer or null | Yes | What the customer pays, minor units. |
| `tax.shipping` | integer | Yes | The shipping charge inside the total, minor units. |
| `tax.jurisdictions` | array of object | Yes | |
| `tax.jurisdictions[].state` | string or null | No | |
| `tax.jurisdictions[].rate` | string | No | Combined percent, e.g. "8.25". |
| `tax.jurisdictions[].amount` | integer | No | |
| `tax.refunded` | integer | Yes | Tax given back so far with refunds and lost disputes, minor units. |
| `tax.error` | string or null | Yes | `tax_address_invalid` or `tax_unavailable` when `status` is `failed`. |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"order_id": "string",
"amount": 4900,
"currency": "USD",
"status": "created",
"payment_reference": "ocpay_3f2a9c1e0b7d4e6f8a1b2c3d4e5f6a7b",
"psp_reference": "string",
"payment_method": "card",
"settlement": "verify_deposits",
"risk_decision": "accept",
"risk_score": 0,
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z",
"expires_at": "2026-01-01T00:00:00.000Z",
"tax": {
"status": "awaiting_address",
"inclusive": true,
"currency": "string",
"subtotal": 0,
"amount": 0,
"total": 0,
"shipping": 0,
"jurisdictions": [
{
"state": "string",
"rate": "string",
"amount": 0
}
],
"refunded": 0,
"error": "string"
}
}
```
| Status | Meaning |
|---|---|
| `200` | The session. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Attach your order to a session {#attachorder}
```http
POST /api/v1/checkout/sessions/{session_id}/order
```
For sessions created from a cart before your order existed: records your `order_id` and
the shipping destination. Each value is set once; later calls do not overwrite it.
The shipping address is recorded only if the session has none yet, no tracking number has
been reported, and the session is less than 24 hours old. Check `shipping_recorded` and
`shipping_on_file` in the response.
An order that ships by carrier is paid out only after delivery to its shipping address. If
it is attached without one and none is on file, the `order_id` is still recorded and the
response is `422 shipping_address_required`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `session_id` | path | string (uuid) | Yes | The checkout session ID returned when the session was created. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `order_id` | string (min 1 chars, max 255 chars) | No | |
| `shipping` | object | No | Where the order ships. OnCharge matches the carrier's delivery location against `postal_code` (US, first five digits) or `city` + `state`. Send at least `postal_code` or `city`. |
| `shipping.name` | string (max 200 chars) | No | |
| `shipping.line1` | string (max 300 chars) | No | |
| `shipping.line2` | string (max 300 chars) | No | |
| `shipping.city` | string (max 120 chars) | No | |
| `shipping.state` | string (max 120 chars) | No | |
| `shipping.postal_code` | string (max 20 chars) | No | |
| `shipping.country` | string (max 60 chars) | No | ISO 3166-1 alpha-2 code recommended (`US`). |
```json title="Request"
{
"order_id": "1001",
"shipping": {
"name": "Alex Rivera",
"line1": "500 Market St",
"city": "San Francisco",
"state": "CA",
"postal_code": "94105",
"country": "US"
}
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `order_id` | string or null | Yes | |
| `shipping_recorded` | boolean | Yes | true if this call recorded the shipping address. |
| `shipping_on_file` | boolean | Yes | true if the session has a shipping destination (from this or an earlier call). |
| `amount` | integer | No | With sales tax: the total now that the address is known. |
| `tax` | object or null | No | Sales tax on a payment; null when it is not taxed. |
| `tax.status` | one of `awaiting_address`, `calculated`, `pending`, `failed`, `collected`, `partly_refunded`, `refunded` | Yes | `awaiting_address`: no address yet, the payment waits. `calculated`: not paid yet. `pending`: tax included, charged while the calculation was unavailable; worked out shortly. `failed`: the calculation failed (`error`), the payment waits. `collected`, `partly_refunded`, `refunded`: paid, and how much of the tax was given back. |
| `tax.inclusive` | boolean | Yes | true when the listed prices include the tax. |
| `tax.currency` | string or null | Yes | |
| `tax.subtotal` | integer or null | Yes | Before tax, minor units. |
| `tax.amount` | integer or null | Yes | The tax, minor units. |
| `tax.total` | integer or null | Yes | What the customer pays, minor units. |
| `tax.shipping` | integer | Yes | The shipping charge inside the total, minor units. |
| `tax.jurisdictions` | array of object | Yes | |
| `tax.jurisdictions[].state` | string or null | No | |
| `tax.jurisdictions[].rate` | string | No | Combined percent, e.g. "8.25". |
| `tax.jurisdictions[].amount` | integer | No | |
| `tax.refunded` | integer | Yes | Tax given back so far with refunds and lost disputes, minor units. |
| `tax.error` | string or null | Yes | `tax_address_invalid` or `tax_unavailable` when `status` is `failed`. |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"order_id": "string",
"shipping_recorded": true,
"shipping_on_file": true,
"amount": 0,
"tax": {
"status": "awaiting_address",
"inclusive": true,
"currency": "string",
"subtotal": 0,
"amount": 0,
"total": 0,
"shipping": 0,
"jurisdictions": [
{
"state": "string",
"rate": "string",
"amount": 0
}
],
"refunded": 0,
"error": "string"
}
}
```
| Status | Meaning |
|---|---|
| `200` | What is on file for the session now. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `session_not_found`: no such session for this store. |
| `422` | `shipping_address_required`: the order ships by carrier and no shipping address is on file (none was sent, or it can no longer be recorded). |
### Cancel an authorized payment {#cancelcheckoutsession}
```http
POST /api/v1/checkout/sessions/{session_id}/cancel
```
Cancels a payment that is `authorized` but not yet captured. Captured payments must be
refunded instead. Send an empty body (`""`) and sign it as such.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `session_id` | path | string (uuid) | Yes | The checkout session ID returned when the session was created. |
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `status` | `"cancelled"` | Yes | |
| `psp_reference` | string | No | Opaque reference of the cancellation. |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"status": "cancelled",
"psp_reference": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The payment was cancelled. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invalid_state` (only `authorized` sessions can be cancelled) or `missing_psp_ref`. |
| `502` | `provider_error` or `provider_unavailable`: the payment network did not accept the request. Retry later. |
## Shipments {#shipments}
Report carrier tracking so delivered orders are paid out.
### Report tracking numbers for a paid order {#reportshipments}
```http
POST /api/v1/shipments
```
Reports the carrier and tracking number(s) a paid order shipped with. OnCharge confirms
delivery with the carrier and pays the order out once every package is delivered to the
order's shipping address.
Identify the order by `session_id` or by your `order_id` (the latest captured session with
that order ID). Supported carriers: USPS, UPS, FedEx and DHL Express, by name or by the
codes shipping tools use (e.g. `ups_walleted`, `stamps_com`, `fedex_ground`). `carrier` may be
omitted, or be one OnCharge does not recognise, when the tracking number's format identifies
the carrier (UPS `1Z…`, USPS IMpb/S10; FedEx and DHL Express numbers when no carrier is given). Reporting a number that is already on the order again is harmless. Each
tracking number is accepted or rejected individually.
To replace a tracking number (the package was lost, returned, or the label cancelled, and the
order was shipped again), name it in `replaces`. Without `replaces`, a new number replaces
every package of the order that has a problem. A replaced number stays tied to the order.
An order that is not confirmed delivered is refunded to the shopper automatically: 30 days
after payment with no tracking, 45 days with no confirmed delivery (`delivery.auto_refund_at`).
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `session_id` | string (uuid) | No | |
| `order_id` | string (min 1 chars, max 255 chars) | No | |
| `shipments` | array of object (≥ 1 items, ≤ 10 items) | Yes | |
| `shipments[].carrier` | string or null (max 60 chars) | No | USPS, UPS, FedEx or DHL Express, or a shipping tool's code for one. Optional when the tracking number format identifies the carrier. |
| `shipments[].tracking_number` | string (min 1 chars, max 80 chars) | Yes | Spaces and dashes are ignored; 8–40 letters and digits after normalization. |
| `shipments[].replaces` | string or null (max 80 chars) | No | The tracking number (or shipment id) on this order that this one replaces. |
```json title="Request"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"shipments": [
{
"carrier": "ups",
"tracking_number": "1Z999AA10123456784"
}
]
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `shipments` | array of object | Yes | |
| `shipments[].tracking_number` | string | Yes | |
| `shipments[].carrier` | one of `usps`, `ups`, `fedex`, `dhl_express` | No | Normalized carrier. Common spellings are accepted on input (`USPS`, `United States Postal Service`, `UPS`, `FedEx`, `FedEx Ground`, `DHL`, `DHL Express`, …). |
| `shipments[].status` | one of `accepted`, `rejected` | Yes | |
| `shipments[].error` | one of `carrier_not_supported`, `tracking_number_invalid`, `carrier_mismatch`, `tracking_number_in_use`, `too_many_shipments`, `replacement_not_found`, `replacement_not_allowed` | No | |
| `shipments[].message` | string | No | |
| `shipments[].replaced` | array of string | No | Tracking numbers this one replaced. |
| `delivery` | object | Yes | |
| `delivery.state` | one of `not_tracked`, `awaiting_shipment`, `in_transit`, `delivered`, `on_hold`, `refunded` | Yes | `not_tracked` (no delivery tracking for this order, e.g. digital goods, or not paid yet), `awaiting_shipment`, `in_transit`, `delivered` (confirmed; payout released on schedule), `on_hold` (see `hold_reason`), `refunded`. |
| `delivery.hold_reason` | string or null | Yes | |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"shipments": [
{
"tracking_number": "1Z999AA10123456784",
"carrier": "ups",
"status": "accepted"
}
],
"delivery": {
"state": "in_transit",
"hold_reason": null
}
}
```
| Status | Meaning |
|---|---|
| `200` | Per-number results and the order's delivery state. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `session_not_found`: no such order for this store. |
| `409` | `order_not_paid`: tracking can be added once the order has been paid. `order_refunded`: the order was refunded in full. |
| `422` | `shipping_address_missing`: the order ships by carrier but has no shipping address, so its delivery cannot be confirmed. |
### Get an order's delivery status {#getdeliverystatus}
```http
GET /api/v1/shipments
```
The order's delivery state and every reported tracking number with the carrier's result.
The query string is not part of the signature: sign the path `/api/v1/shipments`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `session_id` | query | string (uuid) | Yes | The checkout session ID. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `delivery` | object | Yes | |
| `delivery.state` | one of `not_tracked`, `awaiting_shipment`, `in_transit`, `delivered`, `on_hold`, `refunded` | Yes | `not_tracked` (no delivery tracking for this order, e.g. digital goods, or not paid yet), `awaiting_shipment`, `in_transit`, `delivered` (confirmed; payout released on schedule), `on_hold` (see `hold_reason`), `refunded`. |
| `delivery.hold_reason` | string or null | Yes | Plain-language reason when `state` is `on_hold`. |
| `delivery.delivered_at` | string (date-time) or null | Yes | When the last package was confirmed delivered. |
| `delivery.shipments` | array of object | Yes | |
| `delivery.shipments[].id` | string (uuid) | Yes | |
| `delivery.shipments[].carrier` | one of `usps`, `ups`, `fedex`, `dhl_express` | Yes | Normalized carrier. Common spellings are accepted on input (`USPS`, `United States Postal Service`, `UPS`, `FedEx`, `FedEx Ground`, `DHL`, `DHL Express`, …). |
| `delivery.shipments[].carrier_label` | string | Yes | |
| `delivery.shipments[].tracking_number` | string | Yes | |
| `delivery.shipments[].status` | one of `pending`, `pre_transit`, `in_transit`, `out_for_delivery`, `delivered`, `available_for_pickup`, `return_to_sender`, `failure`, `cancelled`, `unknown` | Yes | Latest carrier status. |
| `delivery.shipments[].result` | one of `checking`, `confirmed`, `problem`, `replaced` | Yes | `confirmed` when delivery to the order address is verified; `problem` lists reasons in `problems` (re-ship and replace the number, or refund); `replaced` when another number took its place. |
| `delivery.shipments[].problems` | array of string | Yes | |
| `delivery.shipments[].delivered_at` | string (date-time) or null | No | |
| `delivery.shipments[].delivered_to` | string or null | No | City, state and postal code the carrier reported. |
| `delivery.shipments[].note` | string or null | No | |
| `delivery.shipments[].removable` | boolean | Yes | |
| `delivery.shipments[].created_at` | string (date-time) | Yes | |
| `delivery.shipments[].replaceable` | boolean | No | |
| `delivery.shipments[].replaced_by` | string (uuid) or null | No | |
| `delivery.action_required` | string or null | No | What to do now, if anything (add tracking, re-ship or refund). |
| `delivery.auto_refund_at` | string (date-time) or null | No | When the shopper is refunded in full automatically if the order is still not confirmed delivered. |
| `delivery.can_add_tracking` | boolean | No | |
| `delivery.shipping_address_missing` | boolean | No | |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"delivery": {
"state": "not_tracked",
"hold_reason": "string",
"delivered_at": "2026-01-01T00:00:00.000Z",
"shipments": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"carrier": "usps",
"carrier_label": "UPS",
"tracking_number": "string",
"status": "pending",
"result": "checking",
"problems": [
null
],
"delivered_at": "2026-01-01T00:00:00.000Z",
"delivered_to": "string",
"note": "string",
"removable": true,
"created_at": "2026-01-01T00:00:00.000Z",
"replaceable": true,
"replaced_by": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11"
}
],
"action_required": "string",
"auto_refund_at": "2026-01-01T00:00:00.000Z",
"can_add_tracking": true,
"shipping_address_missing": true
}
}
```
| Status | Meaning |
|---|---|
| `200` | Delivery status. |
| `400` | `invalid_request`: `session_id` is missing or not a UUID. |
| `404` | `session_not_found`: no such order for this store. |
## Refunds {#refunds}
Refund captured payments.
### Refund a captured payment {#createrefund}
```http
POST /api/v1/refunds
```
Refunds all or part of a `captured` payment. Always send an `Idempotency-Key` (for example
your refund ID) so a retried request cannot refund twice: a repeat with the same key
returns the first refund with `idempotent: true`.
The final outcome arrives as a `refund.succeeded` webhook.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `amount` | integer (≥ 1) | Yes | Amount in the currency's minor unit (cents for USD). |
| `currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `reference` | string (max 255 chars) | No | Your reference for the refund. |
```json title="Request"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"amount": 1500,
"currency": "USD",
"reference": "refund-1001-1"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `refund_id` | string | Yes | |
| `session_id` | string (uuid) | Yes | |
| `status` | one of `refund_requested`, `refunded` | Yes | `refunded` if already complete, otherwise `refund_requested` until the `refund.succeeded` webhook. |
| `amount` | integer (≥ 1) | Yes | Amount in the currency's minor unit (cents for USD). |
| `currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
```json title="Response"
{
"refund_id": "string",
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"status": "refund_requested",
"amount": 4900,
"currency": "USD"
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay of an earlier refund with the same `Idempotency-Key`. |
| `201` | Refund requested. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invalid_state`: only `captured` payments can be refunded (cancel `authorized` ones), or `missing_psp_ref`. |
| `502` | `provider_error` or `provider_unavailable`: the payment network did not accept the request. Retry later. |
## Disputes {#disputes}
Read and respond to disputes (chargebacks).
### List disputes {#listdisputes}
```http
GET /api/v1/disputes
```
The store's 50 most recent disputes, newest first.
Newest first, paged by cursor: pass `next_cursor` back as `cursor`. Filters are optional.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `status` | query | one of `open`, `won`, `lost` | No | |
| `reason` | query | one of `fraudulent`, `product_not_received`, `product_unacceptable`, `duplicate`, `subscription_canceled`, `credit_not_processed`, `unrecognized`, `general` | No | |
| `due_before` | query | string (date) | No | Evidence due on or before this day (UTC). |
| `from` | query | string (date) | No | Opened on or after this day (UTC). |
| `to` | query | string (date) | No | Opened on or before this day (UTC). |
| `min` | query | string | No | Smallest amount, in major units. |
| `max` | query | string | No | Largest amount, in major units. |
| `q` | query | string | No | A dispute or payment reference, a dispute id, or an order number. |
| `limit` | query | integer | No | |
| `cursor` | query | string | No | `next_cursor` of the previous page. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `disputes` | array of object | Yes | |
| `disputes[].id` | string (uuid) | Yes | |
| `disputes[].reference` | string | No | OnCharge's reference for the dispute (`ocdsp_` and its id in hex). |
| `disputes[].store_id` | string (uuid) | Yes | |
| `disputes[].session_id` | string (uuid) or null | Yes | The checkout session of the disputed payment. |
| `disputes[].merchant_reference` | string or null | Yes | Your own order reference. |
| `disputes[].payment_reference` | string or null | Yes | Kept with its meaning for existing integrations: for a payment created before the reference cutoff (2026-12-01T00:00:00Z by default; see the OnCharge references guide), the payment reference this field always carried; for a payment created at or after it, the payment's `ocpay_` reference. New integrations should read `oncharge_payment_reference`. |
| `disputes[].oncharge_payment_reference` | string or null | No | The disputed payment's OnCharge reference (`ocpay_…`), for every dispute; the same as the checkout session's `payment_reference`. Null when no payment is linked. |
| `disputes[].original_amount` | integer or null | Yes | Amount of the original payment, minor units. |
| `disputes[].dispute_amount` | integer or null | Yes | Disputed amount, minor units. |
| `disputes[].currency` | string or null | Yes | |
| `disputes[].reason` | string or null | Yes | |
| `disputes[].reason_label` | string | No | The reason in plain words. |
| `disputes[].reason_code` | string or null | Yes | |
| `disputes[].status` | one of `notification_of_chargeback`, `chargeback`, `second_chargeback`, `prearbitration`, `defense_pending`, `defended`, `accepted`, `won`, `lost` | Yes | |
| `disputes[].status_label` | string | No | The status in plain words. |
| `disputes[].defense_deadline` | string (date-time) or null | Yes | When evidence must be in. |
| `disputes[].evidence_submitted_at` | string (date-time) or null | Yes | |
| `disputes[].closed_at` | string (date-time) or null | Yes | |
| `disputes[].responded_by` | one of `oncharge`, `merchant` | Yes | `oncharge`: the OnCharge team submits the response using the evidence you upload; defend, accept and auto-defend return `409 responded_by_oncharge`. `merchant`: you can defend or accept it through the API. |
| `disputes[].created_at` | string (date-time) | Yes | |
| `disputes[].updated_at` | string (date-time) | Yes | |
| `next_cursor` | string or null | No | Pass as `cursor` for the next page; null on the last page. |
```json title="Response"
{
"disputes": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"reference": "string",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"merchant_reference": "string",
"payment_reference": "string",
"oncharge_payment_reference": "string",
"original_amount": 0,
"dispute_amount": 0,
"currency": "string",
"reason": "string",
"reason_label": "string",
"reason_code": "string",
"status": "notification_of_chargeback",
"status_label": "string",
"defense_deadline": "2026-01-01T00:00:00.000Z",
"evidence_submitted_at": "2026-01-01T00:00:00.000Z",
"closed_at": "2026-01-01T00:00:00.000Z",
"responded_by": "oncharge",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z"
}
],
"next_cursor": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Disputes. |
### Retrieve a dispute {#getdispute}
```http
GET /api/v1/disputes/{dispute_id}
```
A dispute with the evidence files uploaded for it.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `dispute_id` | path | string (uuid) | Yes | |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `dispute` | object | Yes | A dispute (chargeback) on one of your payments. |
| `dispute.id` | string (uuid) | Yes | |
| `dispute.reference` | string | No | OnCharge's reference for the dispute (`ocdsp_` and its id in hex). |
| `dispute.store_id` | string (uuid) | Yes | |
| `dispute.session_id` | string (uuid) or null | Yes | The checkout session of the disputed payment. |
| `dispute.merchant_reference` | string or null | Yes | Your own order reference. |
| `dispute.payment_reference` | string or null | Yes | Kept with its meaning for existing integrations: for a payment created before the reference cutoff (2026-12-01T00:00:00Z by default; see the OnCharge references guide), the payment reference this field always carried; for a payment created at or after it, the payment's `ocpay_` reference. New integrations should read `oncharge_payment_reference`. |
| `dispute.oncharge_payment_reference` | string or null | No | The disputed payment's OnCharge reference (`ocpay_…`), for every dispute; the same as the checkout session's `payment_reference`. Null when no payment is linked. |
| `dispute.original_amount` | integer or null | Yes | Amount of the original payment, minor units. |
| `dispute.dispute_amount` | integer or null | Yes | Disputed amount, minor units. |
| `dispute.currency` | string or null | Yes | |
| `dispute.reason` | string or null | Yes | |
| `dispute.reason_label` | string | No | The reason in plain words. |
| `dispute.reason_code` | string or null | Yes | |
| `dispute.status` | one of `notification_of_chargeback`, `chargeback`, `second_chargeback`, `prearbitration`, `defense_pending`, `defended`, `accepted`, `won`, `lost` | Yes | |
| `dispute.status_label` | string | No | The status in plain words. |
| `dispute.defense_deadline` | string (date-time) or null | Yes | When evidence must be in. |
| `dispute.evidence_submitted_at` | string (date-time) or null | Yes | |
| `dispute.closed_at` | string (date-time) or null | Yes | |
| `dispute.responded_by` | one of `oncharge`, `merchant` | Yes | `oncharge`: the OnCharge team submits the response using the evidence you upload; defend, accept and auto-defend return `409 responded_by_oncharge`. `merchant`: you can defend or accept it through the API. |
| `dispute.created_at` | string (date-time) | Yes | |
| `dispute.updated_at` | string (date-time) | Yes | |
| `evidence` | array of object | Yes | |
| `evidence[].id` | string (uuid) | Yes | |
| `evidence[].doc_type` | string | Yes | |
| `evidence[].filename` | string or null | Yes | |
| `evidence[].uploaded_at` | string (date-time) | Yes | |
```json title="Response"
{
"dispute": {
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"reference": "string",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"merchant_reference": "string",
"payment_reference": "string",
"oncharge_payment_reference": "string",
"original_amount": 0,
"dispute_amount": 0,
"currency": "string",
"reason": "string",
"reason_label": "string",
"reason_code": "string",
"status": "notification_of_chargeback",
"status_label": "string",
"defense_deadline": "2026-01-01T00:00:00.000Z",
"evidence_submitted_at": "2026-01-01T00:00:00.000Z",
"closed_at": "2026-01-01T00:00:00.000Z",
"responded_by": "oncharge",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z"
},
"evidence": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"doc_type": "string",
"filename": "string",
"uploaded_at": "2026-01-01T00:00:00.000Z"
}
]
}
```
| Status | Meaning |
|---|---|
| `200` | The dispute. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Upload dispute evidence {#uploaddisputeevidence}
```http
POST /api/v1/disputes/{dispute_id}/evidence
```
Uploads one evidence document as `multipart/form-data`. **Sign this request with an empty
body**: the body hash in the signing string is the SHA-256 of the empty string
(`e3b0c442…b855`), not of the multipart payload.
Upload evidence for every dispute, including those the OnCharge team responds to (`responded_by: "oncharge"`): the team uses your uploads.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `dispute_id` | path | string (uuid) | Yes | |
**Request body** (`multipart/form-data`)
| Field | Type | Required | Description |
|---|---|---|---|
| `file` | string (binary) | Yes | The document (PDF or image). |
| `doc_type` | string | Yes | What the document is. |
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `evidence` | object | Yes | |
| `evidence.id` | string (uuid) | Yes | |
| `evidence.doc_type` | string | Yes | |
| `evidence.filename` | string or null | Yes | |
| `evidence.uploaded_at` | string (date-time) | Yes | |
```json title="Response"
{
"evidence": {
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"doc_type": "string",
"filename": "string",
"uploaded_at": "2026-01-01T00:00:00.000Z"
}
}
```
| Status | Meaning |
|---|---|
| `201` | Evidence stored. |
| `400` | `missing_field`: `file` and `doc_type` are required. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Accept a dispute {#acceptdispute}
```http
POST /api/v1/disputes/{dispute_id}/accept
```
Concedes the dispute. The disputed amount is not contested. Send an empty body. Disputes with `responded_by: "oncharge"` are answered by the OnCharge team: this returns `409 responded_by_oncharge`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `dispute_id` | path | string (uuid) | Yes | |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `dispute_id` | string (uuid) | Yes | |
| `accepted` | boolean | Yes | |
```json title="Response"
{
"dispute_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"accepted": true
}
```
| Status | Meaning |
|---|---|
| `200` | Result. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `responded_by_oncharge`: the OnCharge team responds to this dispute for you; upload your evidence before the deadline instead. `missing_ref`: the dispute cannot be answered yet. |
| `502` | `dispute_action_failed`: the action could not be completed right now. Retry later or contact support. |
### Submit a dispute defense {#defenddispute}
```http
POST /api/v1/disputes/{dispute_id}/defend
```
Submits the defense with the evidence already uploaded. Send an empty body. Disputes with `responded_by: "oncharge"` are answered by the OnCharge team: this returns `409 responded_by_oncharge`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `dispute_id` | path | string (uuid) | Yes | |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `dispute_id` | string (uuid) | Yes | |
| `defended` | boolean | Yes | |
```json title="Response"
{
"dispute_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"defended": true
}
```
| Status | Meaning |
|---|---|
| `200` | Result. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `responded_by_oncharge`: the OnCharge team responds to this dispute for you; upload your evidence before the deadline instead. `missing_ref`: the dispute cannot be answered yet. |
| `502` | `dispute_action_failed`: the action could not be completed right now. Retry later or contact support. |
### Build and submit a defense automatically {#autodefenddispute}
```http
POST /api/v1/disputes/{dispute_id}/auto-defend
```
Builds an evidence packet from the order's checkout records and uploaded evidence and
submits the defense. Send an empty body. Disputes with `responded_by: "oncharge"` are answered by the OnCharge team: this returns `409 responded_by_oncharge`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `dispute_id` | path | string (uuid) | Yes | |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `dispute_id` | string (uuid) | Yes | |
| `success` | boolean | Yes | |
| `message` | string | No | `Defence submitted.` on success, otherwise a neutral explanation. |
| `evidence_count` | integer | No | |
| `defense_text_preview` | string | No | |
| `win_probability` | number or null | No | |
| `ai_recommendation` | string or null | No | |
```json title="Response"
{
"dispute_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"success": true,
"message": "string",
"evidence_count": 0,
"defense_text_preview": "string",
"win_probability": 0,
"ai_recommendation": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Result. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `responded_by_oncharge`: the OnCharge team responds to this dispute for you; upload your evidence before the deadline instead. `missing_ref`: the dispute cannot be answered yet. |
| `500` | `build_failed` (the evidence packet could not be built) or `internal_error`. |
## Customers {#customers}
Your store's customers and the cards they saved with you, and charges to a saved card while the customer is away.
### List customers {#listcustomers}
```http
GET /api/v1/customers
```
Your store's customers, newest first, with their totals.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `q` | query | string | No | An OnCharge customer ID, or part of an email, name, phone or your reference. |
| `email` | query | string (email) | No | |
| `reference` | query | string | No | |
| `limit` | query | integer | No | |
| `cursor` | query | string | No | `next_cursor` of the previous page. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `object` | `"list"` | Yes | |
| `data` | array of object | Yes | |
| `data[].id` | string (uuid) | Yes | |
| `data[].object` | `"customer"` | Yes | |
| `data[].store_id` | string (uuid) | Yes | |
| `data[].email` | string or null | Yes | |
| `data[].name` | string or null | Yes | |
| `data[].phone` | string or null | Yes | |
| `data[].reference` | string or null | Yes | Your own ID for this customer. |
| `data[].metadata` | object | Yes | |
| `data[].source` | string | Yes | How OnCharge first met the customer, in plain words. |
| `data[].created_at` | string (date-time) | Yes | |
| `data[].totals` | object | Yes | |
| `data[].totals.payments` | integer | Yes | Paid payments. |
| `data[].totals.lifetime_value` | array of object | Yes | What the customer paid, less refunds, per currency. |
| `data[].totals.refunded` | array of object | Yes | |
| `data[].totals.disputes` | integer | Yes | |
| `data[].totals.last_payment_at` | string (date-time) or null | Yes | |
| `data[].payment_methods` | array of object | No | On a single customer: the saved cards that can be charged. |
| `data[].payment_methods[].id` | string (uuid) | Yes | |
| `data[].payment_methods[].object` | `"payment_method"` | Yes | |
| `data[].payment_methods[].type` | `"card"` | Yes | |
| `data[].payment_methods[].brand` | string | Yes | |
| `data[].payment_methods[].last4` | string | Yes | |
| `data[].payment_methods[].exp_month` | integer (≥ 1, ≤ 12) | Yes | |
| `data[].payment_methods[].exp_year` | integer | Yes | |
| `data[].payment_methods[].funding` | one of `credit`, `debit`, `prepaid`, `unknown`, or `null` | No | |
| `data[].payment_methods[].country` | string or null | No | |
| `data[].payment_methods[].wallet` | string or null | No | Apple Pay or Google Pay when the card was saved from one. |
| `data[].payment_methods[].is_default` | boolean | Yes | |
| `data[].payment_methods[].status` | one of `active`, `removed` | Yes | |
| `data[].payment_methods[].expired` | boolean | Yes | |
| `data[].payment_methods[].saved_via` | one of `checkout`, `save_card_page` | Yes | |
| `data[].payment_methods[].created_at` | string (date-time) | Yes | |
| `data[].payment_methods[].last_used_at` | string (date-time) or null | No | |
| `data[].payment_methods[].updated_by_card_network_at` | string (date-time) or null | No | When the card network last sent new details for this card (a renewed or replaced card). |
| `data[].payment_methods[].removed_at` | string (date-time) or null | No | |
| `data[].saved_cards` | integer | No | In lists: how many saved cards the customer has. |
| `next_cursor` | string or null | Yes | |
```json title="Response"
{
"object": "list",
"data": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "customer",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"email": "string",
"name": "string",
"phone": "string",
"reference": "string",
"metadata": {},
"source": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"totals": {
"payments": 0,
"lifetime_value": [
null
],
"refunded": [
null
],
"disputes": 0,
"last_payment_at": "2026-01-01T00:00:00.000Z"
},
"payment_methods": [
{
"id": null,
"object": null,
"type": null,
"brand": null,
"last4": null,
"exp_month": null,
"exp_year": null,
"funding": null,
"country": null,
"wallet": null,
"is_default": null,
"status": null,
"expired": null,
"saved_via": null,
"created_at": null,
"last_used_at": null,
"updated_by_card_network_at": null,
"removed_at": null
}
],
"saved_cards": 0
}
],
"next_cursor": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | A page of customers. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
### Add a customer {#createcustomer}
```http
POST /api/v1/customers
```
Adds a customer to your store. One email, and one reference, is one customer of a store: a second
is refused with `409 customer_exists` and the existing customer's ID in `customer_id`.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `email` | string (email) (max 320 chars) | No | |
| `name` | string (max 200 chars) | No | |
| `phone` | string (max 40 chars) | No | |
| `reference` | string (max 255 chars) | No | |
| `metadata` | object | No | |
```json title="Request"
{
"email": "ann@example.com",
"name": "Ann Smith",
"reference": "crm-1042",
"metadata": {
"tier": "gold"
}
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"customer"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `email` | string or null | Yes | |
| `name` | string or null | Yes | |
| `phone` | string or null | Yes | |
| `reference` | string or null | Yes | Your own ID for this customer. |
| `metadata` | object | Yes | |
| `source` | string | Yes | How OnCharge first met the customer, in plain words. |
| `created_at` | string (date-time) | Yes | |
| `totals` | object | Yes | |
| `totals.payments` | integer | Yes | Paid payments. |
| `totals.lifetime_value` | array of object | Yes | What the customer paid, less refunds, per currency. |
| `totals.lifetime_value[].currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `totals.lifetime_value[].amount` | integer | Yes | Minor units. |
| `totals.refunded` | array of object | Yes | |
| `totals.refunded[].currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `totals.refunded[].amount` | integer | Yes | Minor units. |
| `totals.disputes` | integer | Yes | |
| `totals.last_payment_at` | string (date-time) or null | Yes | |
| `payment_methods` | array of object | No | On a single customer: the saved cards that can be charged. |
| `payment_methods[].id` | string (uuid) | Yes | |
| `payment_methods[].object` | `"payment_method"` | Yes | |
| `payment_methods[].type` | `"card"` | Yes | |
| `payment_methods[].brand` | string | Yes | |
| `payment_methods[].last4` | string | Yes | |
| `payment_methods[].exp_month` | integer (≥ 1, ≤ 12) | Yes | |
| `payment_methods[].exp_year` | integer | Yes | |
| `payment_methods[].funding` | one of `credit`, `debit`, `prepaid`, `unknown`, or `null` | No | |
| `payment_methods[].country` | string or null | No | |
| `payment_methods[].wallet` | string or null | No | Apple Pay or Google Pay when the card was saved from one. |
| `payment_methods[].is_default` | boolean | Yes | |
| `payment_methods[].status` | one of `active`, `removed` | Yes | |
| `payment_methods[].expired` | boolean | Yes | |
| `payment_methods[].saved_via` | one of `checkout`, `save_card_page` | Yes | |
| `payment_methods[].created_at` | string (date-time) | Yes | |
| `payment_methods[].last_used_at` | string (date-time) or null | No | |
| `payment_methods[].updated_by_card_network_at` | string (date-time) or null | No | When the card network last sent new details for this card (a renewed or replaced card). |
| `payment_methods[].removed_at` | string (date-time) or null | No | |
| `saved_cards` | integer | No | In lists: how many saved cards the customer has. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "customer",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"email": "string",
"name": "string",
"phone": "string",
"reference": "string",
"metadata": {},
"source": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"totals": {
"payments": 0,
"lifetime_value": [
{
"currency": "USD",
"amount": 0
}
],
"refunded": [
{
"currency": "USD",
"amount": 0
}
],
"disputes": 0,
"last_payment_at": "2026-01-01T00:00:00.000Z"
},
"payment_methods": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "string",
"exp_month": 1,
"exp_year": 0,
"funding": "credit",
"country": "string",
"wallet": "string",
"is_default": true,
"status": "active",
"expired": true,
"saved_via": "checkout",
"created_at": "2026-01-01T00:00:00.000Z",
"last_used_at": "2026-01-01T00:00:00.000Z",
"updated_by_card_network_at": "2026-01-01T00:00:00.000Z",
"removed_at": "2026-01-01T00:00:00.000Z"
}
],
"saved_cards": 0
}
```
| Status | Meaning |
|---|---|
| `201` | Customer added. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `409` | `customer_exists`: the store already has a customer with that email or reference (`customer_id`). |
### Retrieve a customer {#retrievecustomer}
```http
GET /api/v1/customers/{customer_id}
```
One of your store's customers, with totals and saved cards. Another store's customer answers 404.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `customer_id` | path | string (uuid) | Yes | An OnCharge customer ID of your store. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"customer"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `email` | string or null | Yes | |
| `name` | string or null | Yes | |
| `phone` | string or null | Yes | |
| `reference` | string or null | Yes | Your own ID for this customer. |
| `metadata` | object | Yes | |
| `source` | string | Yes | How OnCharge first met the customer, in plain words. |
| `created_at` | string (date-time) | Yes | |
| `totals` | object | Yes | |
| `totals.payments` | integer | Yes | Paid payments. |
| `totals.lifetime_value` | array of object | Yes | What the customer paid, less refunds, per currency. |
| `totals.lifetime_value[].currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `totals.lifetime_value[].amount` | integer | Yes | Minor units. |
| `totals.refunded` | array of object | Yes | |
| `totals.refunded[].currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `totals.refunded[].amount` | integer | Yes | Minor units. |
| `totals.disputes` | integer | Yes | |
| `totals.last_payment_at` | string (date-time) or null | Yes | |
| `payment_methods` | array of object | No | On a single customer: the saved cards that can be charged. |
| `payment_methods[].id` | string (uuid) | Yes | |
| `payment_methods[].object` | `"payment_method"` | Yes | |
| `payment_methods[].type` | `"card"` | Yes | |
| `payment_methods[].brand` | string | Yes | |
| `payment_methods[].last4` | string | Yes | |
| `payment_methods[].exp_month` | integer (≥ 1, ≤ 12) | Yes | |
| `payment_methods[].exp_year` | integer | Yes | |
| `payment_methods[].funding` | one of `credit`, `debit`, `prepaid`, `unknown`, or `null` | No | |
| `payment_methods[].country` | string or null | No | |
| `payment_methods[].wallet` | string or null | No | Apple Pay or Google Pay when the card was saved from one. |
| `payment_methods[].is_default` | boolean | Yes | |
| `payment_methods[].status` | one of `active`, `removed` | Yes | |
| `payment_methods[].expired` | boolean | Yes | |
| `payment_methods[].saved_via` | one of `checkout`, `save_card_page` | Yes | |
| `payment_methods[].created_at` | string (date-time) | Yes | |
| `payment_methods[].last_used_at` | string (date-time) or null | No | |
| `payment_methods[].updated_by_card_network_at` | string (date-time) or null | No | When the card network last sent new details for this card (a renewed or replaced card). |
| `payment_methods[].removed_at` | string (date-time) or null | No | |
| `saved_cards` | integer | No | In lists: how many saved cards the customer has. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "customer",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"email": "string",
"name": "string",
"phone": "string",
"reference": "string",
"metadata": {},
"source": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"totals": {
"payments": 0,
"lifetime_value": [
{
"currency": "USD",
"amount": 0
}
],
"refunded": [
{
"currency": "USD",
"amount": 0
}
],
"disputes": 0,
"last_payment_at": "2026-01-01T00:00:00.000Z"
},
"payment_methods": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "string",
"exp_month": 1,
"exp_year": 0,
"funding": "credit",
"country": "string",
"wallet": "string",
"is_default": true,
"status": "active",
"expired": true,
"saved_via": "checkout",
"created_at": "2026-01-01T00:00:00.000Z",
"last_used_at": "2026-01-01T00:00:00.000Z",
"updated_by_card_network_at": "2026-01-01T00:00:00.000Z",
"removed_at": "2026-01-01T00:00:00.000Z"
}
],
"saved_cards": 0
}
```
| Status | Meaning |
|---|---|
| `200` | The customer. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### List saved cards {#listsavedcards}
```http
GET /api/v1/customers/{customer_id}/payment-methods
```
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `customer_id` | path | string (uuid) | Yes | An OnCharge customer ID of your store. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `object` | `"list"` | Yes | |
| `data` | array of object | Yes | |
| `data[].id` | string (uuid) | Yes | |
| `data[].object` | `"payment_method"` | Yes | |
| `data[].type` | `"card"` | Yes | |
| `data[].brand` | string | Yes | |
| `data[].last4` | string | Yes | |
| `data[].exp_month` | integer (≥ 1, ≤ 12) | Yes | |
| `data[].exp_year` | integer | Yes | |
| `data[].funding` | one of `credit`, `debit`, `prepaid`, `unknown`, or `null` | No | |
| `data[].country` | string or null | No | |
| `data[].wallet` | string or null | No | Apple Pay or Google Pay when the card was saved from one. |
| `data[].is_default` | boolean | Yes | |
| `data[].status` | one of `active`, `removed` | Yes | |
| `data[].expired` | boolean | Yes | |
| `data[].saved_via` | one of `checkout`, `save_card_page` | Yes | |
| `data[].created_at` | string (date-time) | Yes | |
| `data[].last_used_at` | string (date-time) or null | No | |
| `data[].updated_by_card_network_at` | string (date-time) or null | No | When the card network last sent new details for this card (a renewed or replaced card). |
| `data[].removed_at` | string (date-time) or null | No | |
```json title="Response"
{
"object": "list",
"data": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "string",
"exp_month": 1,
"exp_year": 0,
"funding": "credit",
"country": "string",
"wallet": "string",
"is_default": true,
"status": "active",
"expired": true,
"saved_via": "checkout",
"created_at": "2026-01-01T00:00:00.000Z",
"last_used_at": "2026-01-01T00:00:00.000Z",
"updated_by_card_network_at": "2026-01-01T00:00:00.000Z",
"removed_at": "2026-01-01T00:00:00.000Z"
}
]
}
```
| Status | Meaning |
|---|---|
| `200` | The customer's saved cards that can be charged. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Create a save-card page {#createsetupsession}
```http
POST /api/v1/customers/{customer_id}/payment-methods
```
Creates a page where the customer saves a card without paying. Send them to `url`: it shows
the consent text first and the card form only after they agree; the card is saved for your
store only. The same `Idempotency-Key` returns the same page.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
| `customer_id` | path | string (uuid) | Yes | An OnCharge customer ID of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `return_url` | string (uri) | No | https, on one of your store's domains: where the customer returns once the card is saved. |
| `metadata` | object | No | |
| `expires_in_hours` | integer (≥ 1, ≤ 72) | No | Default `24`. |
```json title="Request"
{
"return_url": "https://shop.example.com/account"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"setup_session"` | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `status` | one of `open`, `succeeded`, `failed`, `expired` | Yes | |
| `url` | string (uri) | Yes | Send the customer here. |
| `return_url` | string or null | No | |
| `expires_at` | string (date-time) | Yes | |
| `payment_method_id` | string (uuid) or null | No | The card saved, once the customer saved one. |
| `metadata` | object | No | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "setup_session",
"customer_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"status": "open",
"url": "string",
"return_url": "string",
"expires_at": "2026-01-01T00:00:00.000Z",
"payment_method_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"metadata": {},
"created_at": "2026-01-01T00:00:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | The page created earlier with this `Idempotency-Key`. |
| `201` | Page created. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `saved_cards_unavailable`: card payments are not set up on this store. |
### Remove a saved card {#removesavedcard}
```http
DELETE /api/v1/customers/{customer_id}/payment-methods/{payment_method_id}
```
Removes a saved card for good: it is detached at the processor and can never be charged again.
Removing a card that is already removed answers the same. If it cannot be removed right now
(`502 try_again`) nothing changed.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `customer_id` | path | string (uuid) | Yes | An OnCharge customer ID of your store. |
| `payment_method_id` | path | string (uuid) | Yes | A saved card's ID. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"payment_method"` | Yes | |
| `deleted` | `true` | Yes | |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_method",
"deleted": true
}
```
| Status | Meaning |
|---|---|
| `200` | Removed. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `502` | `try_again`: the card could not be removed right now; nothing changed. |
### Charge a saved card {#createcustomercharge}
```http
POST /api/v1/customers/{customer_id}/charges
```
Charges a customer's saved card while they are away. Use it only for what the customer agreed
to when they saved the card. Always send an `Idempotency-Key`: a retry returns the same charge
and never charges twice.
It is a payment like any checkout payment: same fee, same delivery-gated payout (card payments
on these stores are USD; an order that ships by carrier needs `shipping` with `order_id`), same
`payment.*` webhooks, and it appears under Payments.
When the customer's bank asks them to confirm the payment, the status is
`requires_authentication` and OnCharge emails them a link to confirm it.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
| `customer_id` | path | string (uuid) | Yes | An OnCharge customer ID of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `amount` | integer (≥ 1) | Yes | Amount in the currency's minor unit (cents for USD). |
| `currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `payment_method_id` | string (uuid) | No | A saved card of this customer. The default card when omitted. |
| `reference` | string (max 255 chars) | No | |
| `order_id` | string (max 255 chars) | No | |
| `description` | string (max 500 chars) | No | |
| `shipping` | object | No | Where the order ships. OnCharge matches the carrier's delivery location against `postal_code` (US, first five digits) or `city` + `state`. Send at least `postal_code` or `city`. |
| `shipping.name` | string (max 200 chars) | No | |
| `shipping.line1` | string (max 300 chars) | No | |
| `shipping.line2` | string (max 300 chars) | No | |
| `shipping.city` | string (max 120 chars) | No | |
| `shipping.state` | string (max 120 chars) | No | |
| `shipping.postal_code` | string (max 20 chars) | No | |
| `shipping.country` | string (max 60 chars) | No | ISO 3166-1 alpha-2 code recommended (`US`). |
| `line_items` | array of object (≤ 500 items) | No | |
| `line_items[].description` | string | Yes | |
| `line_items[].quantity` | integer (≥ 1) | Yes | |
| `line_items[].amount_including_tax` | integer (≥ 0) | Yes | Line amount in minor units, tax included. |
| `line_items[].requires_shipping` | boolean | No | Whether this item is shipped. On a store that sells both shipped and unshipped things, an order with any shipped item is paid out after carrier-confirmed delivery; one whose items all say `false`, 7 days after payment. Without it, the order is decided by whether it has a shipping address. |
| `line_items[].tax_category` | one of `general_goods`, `nontaxable`, `services`, `electronic_services`, `clothing`, `software_download`, `saas`, `books`, `ebooks`, `music_download`, `dietary_supplements`, `otc_drugs`, `cosmetics`, `candy`, `groceries`, `prepared_food`, `pet_food`, `gift_cards` | No | An OnCharge product tax category. |
| `metadata` | object | No | |
| `tax` | object | No | Sales tax for this payment, when your store has it on (Settings → Sales tax). With `enabled`, `amount` is the order as you list it (before tax, unless your store lists prices with tax included); line items (`amount_including_tax` is then each line's total as listed) and `shipping_amount` must add up to it. Tax is calculated for the shipping address, or `billing_address` when nothing ships. See /docs/sales-tax. |
| `tax.enabled` | boolean | Yes | Calculate sales tax. Store plugins that already add their platform's tax should leave this off. |
| `tax.shipping_amount` | integer (≥ 0) | No | The shipping charge inside `amount`, minor units: taxed as shipping. |
| `tax.billing_address` | object | No | |
| `tax.billing_address.line1` | string (max 300 chars) | No | |
| `tax.billing_address.line2` | string (max 300 chars) | No | |
| `tax.billing_address.city` | string (max 120 chars) | No | |
| `tax.billing_address.state` | string (max 120 chars) | No | Two-letter US state (or its name). |
| `tax.billing_address.postal_code` | string (max 20 chars) | Yes | Five-digit US ZIP code (ZIP+4 accepted). |
| `tax.billing_address.country` | string (max 60 chars) | No | US only for now. Defaults to US. |
```json title="Request"
{
"amount": 2900,
"currency": "USD",
"reference": "subscription-2026-12"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"charge"` | Yes | |
| `session_id` | string (uuid) | Yes | The payment, as for a checkout session: refunds, shipments and webhooks use it. |
| `payment_reference` | string | Yes | |
| `status` | one of `succeeded`, `processing`, `requires_authentication`, `declined`, `failed` | Yes | `succeeded`: paid. `processing`: the bank has not answered yet; a payment webhook follows. `requires_authentication`: the customer's bank wants them to confirm it; OnCharge emailed them a link to confirm it (`authentication.emailed`). `declined`: see `decline`. |
| `amount` | integer | Yes | |
| `currency` | string | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `payment_method_id` | string (uuid) | Yes | |
| `order_id` | string or null | No | |
| `created_at` | string (date-time) | Yes | |
| `decline` | object or null | Yes | |
| `decline.reason` | one of `insufficient_funds`, `expired_card`, `incorrect_details`, `authentication_required`, `card_not_supported`, `try_again_later`, `suspected_fraud`, `card_declined`, `limit_exceeded` | Yes | |
| `decline.message` | string | Yes | What happened and what to do, in plain words. |
| `authentication` | object or null | Yes | |
| `authentication.emailed` | boolean | Yes | OnCharge emailed the customer a link to its page where they confirm the payment (valid 7 days). `false` when the customer has no email: ask them to pay through checkout instead. The link goes to the customer only, so the cardholder confirms it. |
| `shipping_required` | `true` | No | The order ships by carrier and has no address yet: attach it with POST /api/v1/checkout/sessions/{session_id}/order. |
| `idempotent` | `true` | No | A retry with the same Idempotency-Key returned the first charge. |
| `tax` | object or null | No | Sales tax on a payment; null when it is not taxed. |
| `tax.status` | one of `awaiting_address`, `calculated`, `pending`, `failed`, `collected`, `partly_refunded`, `refunded` | Yes | `awaiting_address`: no address yet, the payment waits. `calculated`: not paid yet. `pending`: tax included, charged while the calculation was unavailable; worked out shortly. `failed`: the calculation failed (`error`), the payment waits. `collected`, `partly_refunded`, `refunded`: paid, and how much of the tax was given back. |
| `tax.inclusive` | boolean | Yes | true when the listed prices include the tax. |
| `tax.currency` | string or null | Yes | |
| `tax.subtotal` | integer or null | Yes | Before tax, minor units. |
| `tax.amount` | integer or null | Yes | The tax, minor units. |
| `tax.total` | integer or null | Yes | What the customer pays, minor units. |
| `tax.shipping` | integer | Yes | The shipping charge inside the total, minor units. |
| `tax.jurisdictions` | array of object | Yes | |
| `tax.jurisdictions[].state` | string or null | No | |
| `tax.jurisdictions[].rate` | string | No | Combined percent, e.g. "8.25". |
| `tax.jurisdictions[].amount` | integer | No | |
| `tax.refunded` | integer | Yes | Tax given back so far with refunds and lost disputes, minor units. |
| `tax.error` | string or null | Yes | `tax_address_invalid` or `tax_unavailable` when `status` is `failed`. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "charge",
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"payment_reference": "string",
"status": "succeeded",
"amount": 0,
"currency": "string",
"customer_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"payment_method_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"order_id": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"decline": {
"reason": "insufficient_funds",
"message": "string"
},
"authentication": {
"emailed": true
},
"shipping_required": true,
"idempotent": true,
"tax": {
"status": "awaiting_address",
"inclusive": true,
"currency": "string",
"subtotal": 0,
"amount": 0,
"total": 0,
"shipping": 0,
"jurisdictions": [
{
"state": "string",
"rate": "string",
"amount": 0
}
],
"refunded": 0,
"error": "string"
}
}
```
| Status | Meaning |
|---|---|
| `200` | The charge made earlier with this `Idempotency-Key` (`idempotent: true`). |
| `201` | Charge made: `succeeded`, `processing` or `requires_authentication`. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `402` | Declined: `decline.reason` and `decline.message` say why in plain words. `limit_exceeded`: the charge would go over a limit OnCharge set for the store (for example a daily volume cap); nothing was sent to the bank. Charge again with a new `Idempotency-Key` once the limit allows it. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `no_saved_card`, `payment_method_unusable` (the card was removed, also when resuming a charge started with it), `charge_not_completed` (an interrupted charge more than 20 hours old), `idempotency_conflict` or `saved_cards_unavailable`. |
| `502` | `try_again`: the outcome is not known yet. Retry with the same `Idempotency-Key` (within 20 hours); the card is never charged twice. After that the charge answers `409 charge_not_completed`: start a new one with a new key. |
## Risk {#risk}
Read risk decisions and manage the store's risk policy.
### List risk decisions {#listriskdecisions}
```http
GET /api/v1/risk/decisions
```
Risk decisions made at checkout for the store, newest first.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `from` | query | string (date-time) | No | Earliest `created_at` (ISO 8601). |
| `to` | query | string (date-time) | No | Latest `created_at` (ISO 8601). |
| `decision` | query | one of `allow`, `deny`, `review`, `step_up` | No | |
| `limit` | query | integer | No | |
| `offset` | query | integer | No | |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `decisions` | array of object | Yes | |
| `decisions[].id` | string (uuid) | No | |
| `decisions[].session_id` | string (uuid) | No | |
| `decisions[].decision` | one of `allow`, `deny`, `review`, `step_up` | No | |
| `decisions[].score` | integer (≥ 0, ≤ 100) | No | |
| `decisions[].actions` | array of string | No | Step-up actions, e.g. `require_sms_otp`, `require_terms`, `require_signature`, `force_3ds`. |
| `decisions[].reasons` | array of object | No | |
| `decisions[].reasons[].code` | string | No | |
| `decisions[].reasons[].severity` | one of `info`, `warn`, `block` | No | |
| `decisions[].reasons[].explain` | string | No | |
| `decisions[].explain_short` | string or null | No | |
| `decisions[].model_version` | string | No | |
| `decisions[].created_at` | string (date-time) | No | |
| `total` | integer | Yes | |
| `limit` | integer | Yes | |
| `offset` | integer | Yes | |
```json title="Response"
{
"decisions": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"decision": "allow",
"score": 0,
"actions": [
"string"
],
"reasons": [
{
"code": null,
"severity": null,
"explain": null
}
],
"explain_short": "string",
"model_version": "string",
"created_at": "2026-01-01T00:00:00.000Z"
}
],
"total": 0,
"limit": 0,
"offset": 0
}
```
| Status | Meaning |
|---|---|
| `200` | A page of decisions. |
### Retrieve a risk decision {#getriskdecision}
```http
GET /api/v1/risk/decisions/{decision_id}
```
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `decision_id` | path | string (uuid) | Yes | |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | No | |
| `session_id` | string (uuid) | No | |
| `decision` | one of `allow`, `deny`, `review`, `step_up` | No | |
| `score` | integer (≥ 0, ≤ 100) | No | |
| `actions` | array of string | No | Step-up actions, e.g. `require_sms_otp`, `require_terms`, `require_signature`, `force_3ds`. |
| `reasons` | array of object | No | |
| `reasons[].code` | string | No | |
| `reasons[].severity` | one of `info`, `warn`, `block` | No | |
| `reasons[].explain` | string | No | |
| `explain_short` | string or null | No | |
| `model_version` | string | No | |
| `created_at` | string (date-time) | No | |
| `feature_snapshot` | object | No | |
| `policy_version` | string or null | No | |
| `label` | object or null | No | |
| `label.paid` | boolean or null | No | |
| `label.refunded` | boolean or null | No | |
| `label.chargeback` | boolean or null | No | |
| `label.dispute_opened` | boolean or null | No | |
| `label.label_source` | string or null | No | |
| `label.occurred_at` | string (date-time) or null | No | |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"decision": "allow",
"score": 0,
"actions": [
"string"
],
"reasons": [
{
"code": "string",
"severity": "info",
"explain": "string"
}
],
"explain_short": "string",
"model_version": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"feature_snapshot": {},
"policy_version": "string",
"label": {
"paid": true,
"refunded": true,
"chargeback": true,
"dispute_opened": true,
"label_source": "string",
"occurred_at": "2026-01-01T00:00:00.000Z"
}
}
```
| Status | Meaning |
|---|---|
| `200` | The decision with its feature snapshot and outcome label, if any. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Label the outcome of a risk decision {#sendriskfeedback}
```http
POST /api/v1/risk/feedback
```
Tells OnCharge how an order turned out, to improve future decisions.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `label` | one of `fraud_confirmed`, `false_positive`, `legitimate`, `chargeback` | Yes | |
| `notes` | string (max 1000 chars) | No | |
```json title="Request"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"label": "fraud_confirmed",
"notes": "string"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `status` | `"ok"` | Yes | |
| `label` | string | Yes | |
```json title="Response"
{
"status": "ok",
"label": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Recorded. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Get the store's risk policy {#getriskpolicy}
```http
GET /api/v1/risk/policies
```
The store's policy, or the defaults (`is_default: true`) if none was saved.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `mode` | one of `monitor`, `enforce` | No | |
| `thresholds` | object | No | |
| `thresholds.score_allow` | integer (≥ 0, ≤ 100) | Yes | |
| `thresholds.score_review` | integer (≥ 0, ≤ 100) | Yes | |
| `thresholds.score_deny` | integer (≥ 0, ≤ 100) | Yes | |
| `step_up_rules` | object | No | |
| `step_up_rules.require_otp_on_review` | boolean | Yes | |
| `step_up_rules.require_signature` | boolean | Yes | |
| `step_up_rules.require_terms` | boolean | Yes | |
| `step_up_rules.force_3ds_above` | integer (≥ 0, ≤ 100) | Yes | |
| `blocks` | object | No | |
| `blocks.vpn_tor` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.datacenter_asn` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.disposable_email` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.voip_phone` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.high_risk_countries` | array of string | Yes | ISO country codes. |
| `blocks.headless_browser` | one of `allow`, `step_up`, `deny` | Yes | |
| `velocity_limits` | object | No | |
| `velocity_limits.ip_5m` | integer (≥ 0) | Yes | |
| `velocity_limits.ip_1h` | integer (≥ 0) | Yes | |
| `velocity_limits.ip_24h` | integer (≥ 0) | Yes | |
| `velocity_limits.email_5m` | integer (≥ 0) | Yes | |
| `velocity_limits.email_1h` | integer (≥ 0) | Yes | |
| `velocity_limits.email_24h` | integer (≥ 0) | Yes | |
| `id` | string (uuid) | No | |
| `store_id` | string (uuid) | Yes | |
| `is_default` | boolean | Yes | true when no policy has been saved and these are the defaults. |
| `created_at` | string (date-time) | No | |
| `updated_at` | string (date-time) | No | |
```json title="Response"
{
"mode": "monitor",
"thresholds": {
"score_allow": 0,
"score_review": 0,
"score_deny": 0
},
"step_up_rules": {
"require_otp_on_review": true,
"require_signature": true,
"require_terms": true,
"force_3ds_above": 0
},
"blocks": {
"vpn_tor": "allow",
"datacenter_asn": "allow",
"disposable_email": "allow",
"voip_phone": "allow",
"high_risk_countries": [
"string"
],
"headless_browser": "allow"
},
"velocity_limits": {
"ip_5m": 0,
"ip_1h": 0,
"ip_24h": 0,
"email_5m": 0,
"email_1h": 0,
"email_24h": 0
},
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"is_default": true,
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | The policy. |
### Create or update the store's risk policy {#updateriskpolicy}
```http
PUT /api/v1/risk/policies
```
Each top-level section you send replaces that section; sections you omit are unchanged.
Thresholds must satisfy `score_allow < score_review < score_deny`. In `monitor` mode
decisions are recorded but never block a payment.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `mode` | one of `monitor`, `enforce` | No | |
| `thresholds` | object | No | |
| `thresholds.score_allow` | integer (≥ 0, ≤ 100) | Yes | |
| `thresholds.score_review` | integer (≥ 0, ≤ 100) | Yes | |
| `thresholds.score_deny` | integer (≥ 0, ≤ 100) | Yes | |
| `step_up_rules` | object | No | |
| `step_up_rules.require_otp_on_review` | boolean | Yes | |
| `step_up_rules.require_signature` | boolean | Yes | |
| `step_up_rules.require_terms` | boolean | Yes | |
| `step_up_rules.force_3ds_above` | integer (≥ 0, ≤ 100) | Yes | |
| `blocks` | object | No | |
| `blocks.vpn_tor` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.datacenter_asn` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.disposable_email` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.voip_phone` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.high_risk_countries` | array of string | Yes | ISO country codes. |
| `blocks.headless_browser` | one of `allow`, `step_up`, `deny` | Yes | |
| `velocity_limits` | object | No | |
| `velocity_limits.ip_5m` | integer (≥ 0) | Yes | |
| `velocity_limits.ip_1h` | integer (≥ 0) | Yes | |
| `velocity_limits.ip_24h` | integer (≥ 0) | Yes | |
| `velocity_limits.email_5m` | integer (≥ 0) | Yes | |
| `velocity_limits.email_1h` | integer (≥ 0) | Yes | |
| `velocity_limits.email_24h` | integer (≥ 0) | Yes | |
```json title="Request"
{
"mode": "monitor",
"thresholds": {
"score_allow": 0,
"score_review": 0,
"score_deny": 0
},
"step_up_rules": {
"require_otp_on_review": true,
"require_signature": true,
"require_terms": true,
"force_3ds_above": 0
},
"blocks": {
"vpn_tor": "allow",
"datacenter_asn": "allow",
"disposable_email": "allow",
"voip_phone": "allow",
"high_risk_countries": [
"string"
],
"headless_browser": "allow"
},
"velocity_limits": {
"ip_5m": 0,
"ip_1h": 0,
"ip_24h": 0,
"email_5m": 0,
"email_1h": 0,
"email_24h": 0
}
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `mode` | one of `monitor`, `enforce` | No | |
| `thresholds` | object | No | |
| `thresholds.score_allow` | integer (≥ 0, ≤ 100) | Yes | |
| `thresholds.score_review` | integer (≥ 0, ≤ 100) | Yes | |
| `thresholds.score_deny` | integer (≥ 0, ≤ 100) | Yes | |
| `step_up_rules` | object | No | |
| `step_up_rules.require_otp_on_review` | boolean | Yes | |
| `step_up_rules.require_signature` | boolean | Yes | |
| `step_up_rules.require_terms` | boolean | Yes | |
| `step_up_rules.force_3ds_above` | integer (≥ 0, ≤ 100) | Yes | |
| `blocks` | object | No | |
| `blocks.vpn_tor` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.datacenter_asn` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.disposable_email` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.voip_phone` | one of `allow`, `step_up`, `deny` | Yes | |
| `blocks.high_risk_countries` | array of string | Yes | ISO country codes. |
| `blocks.headless_browser` | one of `allow`, `step_up`, `deny` | Yes | |
| `velocity_limits` | object | No | |
| `velocity_limits.ip_5m` | integer (≥ 0) | Yes | |
| `velocity_limits.ip_1h` | integer (≥ 0) | Yes | |
| `velocity_limits.ip_24h` | integer (≥ 0) | Yes | |
| `velocity_limits.email_5m` | integer (≥ 0) | Yes | |
| `velocity_limits.email_1h` | integer (≥ 0) | Yes | |
| `velocity_limits.email_24h` | integer (≥ 0) | Yes | |
| `id` | string (uuid) | No | |
| `store_id` | string (uuid) | No | |
| `created_at` | string (date-time) | No | |
| `updated_at` | string (date-time) | No | |
```json title="Response"
{
"mode": "monitor",
"thresholds": {
"score_allow": 0,
"score_review": 0,
"score_deny": 0
},
"step_up_rules": {
"require_otp_on_review": true,
"require_signature": true,
"require_terms": true,
"force_3ds_above": 0
},
"blocks": {
"vpn_tor": "allow",
"datacenter_asn": "allow",
"disposable_email": "allow",
"voip_phone": "allow",
"high_risk_countries": [
"string"
],
"headless_browser": "allow"
},
"velocity_limits": {
"ip_5m": 0,
"ip_1h": 0,
"ip_24h": 0,
"email_5m": 0,
"email_1h": 0,
"email_24h": 0
},
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | Policy updated. |
| `201` | Policy created. |
| `400` | `validation_error`, `invalid_json` or `invalid_thresholds`. |
### Replay a decision under a different policy {#simulateriskpolicy}
```http
POST /api/v1/risk/simulate
```
Shows what a past decision would have been with the policy you send. Nothing is saved.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `decision_id` | string (uuid) | Yes | |
| `policy` | object | Yes | |
| `policy.mode` | one of `monitor`, `enforce` | No | |
| `policy.thresholds` | object | No | |
| `policy.thresholds.score_allow` | integer (≥ 0, ≤ 100) | Yes | |
| `policy.thresholds.score_review` | integer (≥ 0, ≤ 100) | Yes | |
| `policy.thresholds.score_deny` | integer (≥ 0, ≤ 100) | Yes | |
| `policy.step_up_rules` | object | No | |
| `policy.step_up_rules.require_otp_on_review` | boolean | Yes | |
| `policy.step_up_rules.require_signature` | boolean | Yes | |
| `policy.step_up_rules.require_terms` | boolean | Yes | |
| `policy.step_up_rules.force_3ds_above` | integer (≥ 0, ≤ 100) | Yes | |
| `policy.blocks` | object | No | |
| `policy.blocks.vpn_tor` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy.blocks.datacenter_asn` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy.blocks.disposable_email` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy.blocks.voip_phone` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy.blocks.high_risk_countries` | array of string | Yes | ISO country codes. |
| `policy.blocks.headless_browser` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy.velocity_limits` | object | No | |
| `policy.velocity_limits.ip_5m` | integer (≥ 0) | Yes | |
| `policy.velocity_limits.ip_1h` | integer (≥ 0) | Yes | |
| `policy.velocity_limits.ip_24h` | integer (≥ 0) | Yes | |
| `policy.velocity_limits.email_5m` | integer (≥ 0) | Yes | |
| `policy.velocity_limits.email_1h` | integer (≥ 0) | Yes | |
| `policy.velocity_limits.email_24h` | integer (≥ 0) | Yes | |
```json title="Request"
{
"decision_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"policy": {
"mode": "monitor",
"thresholds": {
"score_allow": 0,
"score_review": 0,
"score_deny": 0
},
"step_up_rules": {
"require_otp_on_review": true,
"require_signature": true,
"require_terms": true,
"force_3ds_above": 0
},
"blocks": {
"vpn_tor": "allow",
"datacenter_asn": "allow",
"disposable_email": "allow",
"voip_phone": "allow",
"high_risk_countries": [
"string"
],
"headless_browser": "allow"
},
"velocity_limits": {
"ip_5m": 0,
"ip_1h": 0,
"ip_24h": 0,
"email_5m": 0,
"email_1h": 0,
"email_24h": 0
}
}
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `simulation` | `true` | No | |
| `original` | object | No | |
| `original.decision` | one of `allow`, `deny`, `review`, `step_up` | No | |
| `original.score` | integer | No | |
| `original.explain_short` | string or null | No | |
| `simulated` | object | No | |
| `simulated.decision` | one of `allow`, `deny`, `review`, `step_up` | No | |
| `simulated.score` | integer | No | |
| `simulated.actions` | array of string | No | |
| `simulated.reasons` | array of object | No | |
| `simulated.reasons[].code` | string | No | |
| `simulated.reasons[].severity` | one of `info`, `warn`, `block` | No | |
| `simulated.reasons[].explain` | string | No | |
| `simulated.explain_short` | string or null | No | |
| `policy_tested` | object | No | |
| `policy_tested.mode` | one of `monitor`, `enforce` | No | |
| `policy_tested.thresholds` | object | No | |
| `policy_tested.thresholds.score_allow` | integer (≥ 0, ≤ 100) | Yes | |
| `policy_tested.thresholds.score_review` | integer (≥ 0, ≤ 100) | Yes | |
| `policy_tested.thresholds.score_deny` | integer (≥ 0, ≤ 100) | Yes | |
| `policy_tested.step_up_rules` | object | No | |
| `policy_tested.step_up_rules.require_otp_on_review` | boolean | Yes | |
| `policy_tested.step_up_rules.require_signature` | boolean | Yes | |
| `policy_tested.step_up_rules.require_terms` | boolean | Yes | |
| `policy_tested.step_up_rules.force_3ds_above` | integer (≥ 0, ≤ 100) | Yes | |
| `policy_tested.blocks` | object | No | |
| `policy_tested.blocks.vpn_tor` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy_tested.blocks.datacenter_asn` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy_tested.blocks.disposable_email` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy_tested.blocks.voip_phone` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy_tested.blocks.high_risk_countries` | array of string | Yes | ISO country codes. |
| `policy_tested.blocks.headless_browser` | one of `allow`, `step_up`, `deny` | Yes | |
| `policy_tested.velocity_limits` | object | No | |
| `policy_tested.velocity_limits.ip_5m` | integer (≥ 0) | Yes | |
| `policy_tested.velocity_limits.ip_1h` | integer (≥ 0) | Yes | |
| `policy_tested.velocity_limits.ip_24h` | integer (≥ 0) | Yes | |
| `policy_tested.velocity_limits.email_5m` | integer (≥ 0) | Yes | |
| `policy_tested.velocity_limits.email_1h` | integer (≥ 0) | Yes | |
| `policy_tested.velocity_limits.email_24h` | integer (≥ 0) | Yes | |
```json title="Response"
{
"simulation": true,
"original": {
"decision": "allow",
"score": 0,
"explain_short": "string"
},
"simulated": {
"decision": "allow",
"score": 0,
"actions": [
"string"
],
"reasons": [
{
"code": "string",
"severity": "info",
"explain": "string"
}
],
"explain_short": "string"
},
"policy_tested": {
"mode": "monitor",
"thresholds": {
"score_allow": 0,
"score_review": 0,
"score_deny": 0
},
"step_up_rules": {
"require_otp_on_review": true,
"require_signature": true,
"require_terms": true,
"force_3ds_above": 0
},
"blocks": {
"vpn_tor": "allow",
"datacenter_asn": "allow",
"disposable_email": "allow",
"voip_phone": "allow",
"high_risk_countries": [
"string"
],
"headless_browser": "allow"
},
"velocity_limits": {
"ip_5m": 0,
"ip_1h": 0,
"ip_24h": 0,
"email_5m": 0,
"email_1h": 0,
"email_24h": 0
}
}
}
```
| Status | Meaning |
|---|---|
| `200` | The original and simulated outcomes. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
## Recurring {#recurring}
Merchant-initiated charges on a saved card.
### Charge a saved card {#createrecurringcharge}
```http
POST /api/v1/recurring/charge
```
> **Limited availability.** Ask OnCharge support before relying on this endpoint.
A merchant-initiated charge on a card the shopper saved during an earlier OnCharge checkout
(subscriptions, installments). Availability depends on your account configuration; ask
OnCharge support before relying on it. Uses the shopper's most recent saved card unless
`stored_card_id` is given.
On a store with its own card account the shopper is your customer with that email and
`stored_card_id` one of their saved cards: it charges through
`POST /api/v1/customers/{customer_id}/charges`, which new integrations should use instead.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `shopper_email` | string (email) | Yes | |
| `amount` | integer (≥ 1) | Yes | Amount in the currency's minor unit (cents for USD). |
| `currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `reference` | string (min 1 chars, max 255 chars) | Yes | |
| `recurring_model` | one of `Subscription`, `UnscheduledCardOnFile` | No | Default `"Subscription"`. |
| `stored_card_id` | string (uuid) | No | |
```json title="Request"
{
"shopper_email": "string",
"amount": 4900,
"currency": "USD",
"reference": "string",
"recurring_model": "Subscription",
"stored_card_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `session_id` | string (uuid) | Yes | |
| `status` | one of `authorized`, `refused`, `pending` | Yes | |
| `result_code` | string | No | Raw authorization result. Use `status` instead. |
| `psp_reference` | string | No | Opaque payment reference. |
```json title="Response"
{
"session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"status": "authorized",
"result_code": "string",
"psp_reference": "string"
}
```
| Status | Meaning |
|---|---|
| `201` | Charge attempted. Check `status`. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `no_shopper`, `card_not_found` or `no_cards`. |
| `502` | `provider_error` or `provider_unavailable`: the payment network did not accept the request. Retry later. |
## Catalog {#catalog}
Send your products to OnCharge for shopping ads on Google Merchant Center and the Meta catalog. The whole catalog is sent and each ad platform reviews it against its own policies; only products that name a controlled substance, and products you exclude, are stored but not sent.
### Add, update and remove catalog products {#upsertcatalogproducts}
```http
POST /api/v1/catalog/products/batch
```
Sends up to 500 products and deletes to the store's advertising catalog, which OnCharge sends to Google Merchant Center and the Meta catalog. Products are matched by `id`; sending a product again updates it, and an identical product is not rewritten (`unchanged`). Deletes remove the product from ad platforms.
OnCharge sends the whole catalog to the ad platforms, which review each product against their own policies. `ruo: true` is a label only. Products that name a controlled substance, and products with no image, no price, an http link or `excluded: true`, are stored but not sent. Each result says whether the product is `advertisable` and why not. The WooCommerce plugin (1.5.0+) calls this for you.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `items` | array of object (≤ 500 items) | No | Products to add or update. |
| `items[].id` | string (min 1 chars, max 50 chars) | Yes | Your product ID (WooCommerce: the product or variation ID). Unique per store. |
| `items[].item_group_id` | string or null (max 50 chars) | No | Groups the variants of one product (WooCommerce: the parent product ID). |
| `items[].title` | string (min 1 chars, max 1000 chars) | Yes | Product name. Stored cut to 150 characters. |
| `items[].description` | string or null (max 20000 chars) | No | Plain text or HTML (tags and shortcodes are removed). Stored cut to 5,000 characters. |
| `items[].link` | string (uri) (max 2048 chars) | Yes | Product page. Must be https; a product with an http link is rejected (or, if already stored, excluded). |
| `items[].image_link` | string (uri) or null (max 2048 chars) | No | Main image. Products without one are stored but not advertised. |
| `items[].additional_image_links` | array of string (uri) (≤ 20 items) | No | More images; at most 10 are kept. |
| `items[].price_minor` | integer (≥ 0) | Yes | Regular price in minor units, as shown in your store. |
| `items[].sale_price_minor` | integer or null (≥ 0) | No | Current sale price in minor units. Ignored unless lower than `price_minor`. |
| `items[].currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `items[].availability` | one of `in_stock`, `out_of_stock`, `preorder`, `backorder` | No | Default `"in_stock"`. |
| `items[].condition` | one of `new`, `refurbished`, `used` | No | Default `"new"`. |
| `items[].brand` | string or null (max 200 chars) | No | |
| `items[].gtin` | string or null (max 50 chars) | No | UPC, EAN, ISBN or ITF-14. Kept only when it is 8–14 digits. |
| `items[].mpn` | string or null (max 100 chars) | No | |
| `items[].google_product_category` | string or null (max 500 chars) | No | Google's product category ID or path, if you know it. |
| `items[].product_type` | string or null (max 750 chars) | No | Your own category path, e.g. `Apparel > Shirts`. |
| `items[].attributes` | object | No | Variant attributes such as `{"Color": "Blue", "Size": "M"}`. At most 30. |
| `items[].ruo` | boolean | No | `true` for research-use-only (RUO) products. A label only: the product is sent to the ad platforms like any other, and each platform reviews it against its own policies. |
| `items[].excluded` | boolean | No | `true` to keep the product out of advertising. |
| `deletes` | array of string (≤ 500 items) | No | IDs of products to remove. |
```json title="Request"
{
"items": [
{
"id": "205",
"item_group_id": "200",
"title": "Linen shirt - Blue, M",
"description": "Soft linen shirt.",
"link": "https://shop.example.com/product/linen-shirt/?attribute_pa_color=blue&attribute_pa_size=m",
"image_link": "https://shop.example.com/wp-content/uploads/linen-shirt-blue.jpg",
"price_minor": 4900,
"sale_price_minor": 3900,
"currency": "USD",
"availability": "in_stock",
"brand": "Acme",
"gtin": "0012345678905",
"product_type": "Apparel > Shirts",
"attributes": {
"Color": "Blue",
"Size": "M"
}
}
],
"deletes": [
"198"
]
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `results` | array of object | Yes | One per product, then one per delete, in request order. |
| `results[].id` | string | Yes | |
| `results[].status` | one of `created`, `updated`, `unchanged`, `deleted`, `not_found`, `rejected` | Yes | `unchanged`: identical to what OnCharge already has (nothing written). `not_found`: a delete for an ID OnCharge never had. |
| `results[].advertisable` | boolean | No | For stored products: may be sent to ad platforms. |
| `results[].ruo` | boolean | No | |
| `results[].excluded_reason` | one of `merchant_excluded`, `controlled_substance`, `insecure_link`, `missing_image`, `zero_price`, or `null` | No | Why the product is not advertised, or `null`. `merchant_excluded`: you sent `excluded: true`. `controlled_substance`: the product names a controlled substance (U.S. DEA schedules I to V), which is never sent to an ad platform. `insecure_link`: the link is not https. `missing_image`: no `image_link`. `zero_price`: `price_minor` is 0. |
| `results[].warnings` | array of one of `title_truncated`, `gtin_invalid`, `sale_price_ignored`, `additional_images_truncated`, `link_not_stored` | No | |
| `results[].error` | string | No | For `rejected`: the error code, e.g. `insecure_link`. |
| `results[].message` | string | No | |
| `counts` | object | Yes | |
| `counts.created` | integer | Yes | |
| `counts.updated` | integer | Yes | |
| `counts.unchanged` | integer | Yes | |
| `counts.deleted` | integer | Yes | |
| `counts.not_found` | integer | Yes | |
| `counts.rejected` | integer | Yes | |
```json title="Response"
{
"results": [
{
"id": "205",
"status": "created",
"advertisable": true,
"ruo": false,
"excluded_reason": null
},
{
"id": "198",
"status": "deleted"
}
],
"counts": {
"created": 1,
"updated": 0,
"unchanged": 0,
"deleted": 1,
"not_found": 0,
"rejected": 0
}
}
```
| Status | Meaning |
|---|---|
| `200` | Per-product results and counts. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `413` | `payload_too_large`: more than 5 MB. Send smaller batches. |
### List catalog products {#listcatalogproducts}
```http
GET /api/v1/catalog/products
```
The store's catalog, oldest first. Use it to find products you no longer sell and remove them. Sign an empty body.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `limit` | query | integer | No | |
| `offset` | query | integer | No | |
| `include_deleted` | query | boolean | No | Also list removed products. |
| `updated_since` | query | string (date-time) | No | Only products changed at or after this time (ISO 8601). |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `products` | array of object | Yes | |
| `products[].id` | string | Yes | |
| `products[].item_group_id` | string or null | No | |
| `products[].title` | string | Yes | |
| `products[].link` | string (uri) | Yes | |
| `products[].image_link` | string (uri) or null | No | |
| `products[].price_minor` | integer | Yes | |
| `products[].sale_price_minor` | integer or null | No | |
| `products[].currency` | string (min 3 chars, max 3 chars) | Yes | ISO 4217 currency code. |
| `products[].availability` | one of `in_stock`, `out_of_stock`, `preorder`, `backorder` | Yes | |
| `products[].ruo` | boolean | Yes | |
| `products[].excluded_reason` | one of `merchant_excluded`, `controlled_substance`, `insecure_link`, `missing_image`, `zero_price`, or `null` | Yes | Why the product is not advertised, or `null`. `merchant_excluded`: you sent `excluded: true`. `controlled_substance`: the product names a controlled substance (U.S. DEA schedules I to V), which is never sent to an ad platform. `insecure_link`: the link is not https. `missing_image`: no `image_link`. `zero_price`: `price_minor` is 0. |
| `products[].advertisable` | boolean | Yes | Not removed and not excluded. |
| `products[].deleted` | boolean | Yes | Removed (only listed with `include_deleted=true`). |
| `products[].content_hash` | string | Yes | Changes whenever anything OnCharge stores for the product changes. |
| `products[].updated_at` | string (date-time) | Yes | |
| `total` | integer | Yes | |
| `limit` | integer | Yes | |
| `offset` | integer | Yes | |
```json title="Response"
{
"products": [
{
"id": "string",
"item_group_id": "string",
"title": "string",
"link": "string",
"image_link": "string",
"price_minor": 0,
"sale_price_minor": 0,
"currency": "USD",
"availability": "in_stock",
"ruo": true,
"excluded_reason": "merchant_excluded",
"advertisable": true,
"deleted": true,
"content_hash": "string",
"updated_at": "2026-01-01T00:00:00.000Z"
}
],
"total": 0,
"limit": 0,
"offset": 0
}
```
| Status | Meaning |
|---|---|
| `200` | A page of products. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
## Events {#events}
Every webhook event of the last 30 days, and sending one to an endpoint again.
### List events {#listevents}
```http
GET /api/v1/events
```
The store's events from the last 30 days, newest first, each exactly as its webhook endpoints received it (data.rail included). Use it to catch up on events your server missed. Paged by cursor.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `type` | query | string | No | An event type (`payment.captured`) or a group (`payout.*`). |
| `from` | query | string (date) | No | Created on or after this day (UTC). |
| `to` | query | string (date) | No | Created on or before this day (UTC). |
| `limit` | query | integer | No | |
| `cursor` | query | string | No | `next_cursor` of the previous page, sent with the same filters. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `events` | array of object | Yes | |
| `events[].id` | string | Yes | Event ID (`evt_…`), the same as the `OnCharge-Event-Id` header. |
| `events[].type` | one of `payment.pending`, `payment.authorized`, `payment.captured`, `payment.under_review`, `payment.refused`, `payment.cancelled`, `payment.expired`, `payment.capture_failed`, `refund.succeeded`, `refund.failed`, `chargeback.opened`, `dispute.evidence_due`, `chargeback.won`, `chargeback.lost`, `fraud_warning.received`, `delivery.confirmed`, `payout.paid`, `payout.failed`, `payout.returned`, `account.updated`, `account.requirements_due`, `account.restricted`, `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired`, `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.period.paid`, `subscription.period.payment_failed`, `support.conversation.created`, `support.message.received`, `support.conversation.closed` | Yes | Every event type. Payments on every rail use the same payment.* types (data.rail says which). Handle the types you need and acknowledge (2xx) any others; new types may be added. |
| `events[].created` | integer | Yes | Unix time (seconds) the event was created. |
| `events[].livemode` | boolean | Yes | false for events from test payments. |
| `events[].data` | object | Yes | For payment events from a checkout, the fields below. Crypto and Card to Crypto paid to your wallet carry `session_id: null` with `payment_id`, `source`, `method`, `coin`, `coin_amount`, `wallet` and transaction hashes; every other event its own fields. All of them carry `rail`. |
| `events[].data.session_id` | string or null | No | The checkout session; null for a payment paid straight to your wallet. |
| `events[].data.order_id` | string or null | No | Your order ID, if known. |
| `events[].data.reference` | string or null | No | The `reference` you sent when creating the session. |
| `events[].data.amount` | integer or null | No | Minor units. For `refund.succeeded`, the total refunded so far. |
| `events[].data.currency` | string or null | No | ISO 4217 code. |
| `events[].data.status` | string or null | No | The order's payment status after the event (for example `captured`, `refunded`). |
| `events[].data.rail` | one of `card`, `crypto`, `card_to_crypto` | Yes | The rail an event or payment is on: card checkout; crypto (crypto checkout, or a coin paid straight to your wallet through the plugin or the gateway API); or Card to Crypto (card, Cash App or Venmo paid out to your wallet in USDC). |
| `events[].data.payment_reference` | string or null | No | OnCharge's reference for the payment (`ocpay_…`). |
| `events[].data.payment_link_id` | string (uuid) or null | No | The payment link the checkout was made from (`/api/v1/payment-links`), or null. |
| `events[].data.invoice_id` | string (uuid) | No | Only on a payment for an OnCharge invoice: the invoice's id (see Invoices). |
| `events[].data.payment_method` | one of `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm`, `afterpay`, or `null` | No | How the shopper paid: `card`, or a way to pay beyond cards the store turned on (bank debit, Cash App Pay, Klarna, Affirm, Afterpay; see the Payment methods guide). Null for crypto. |
| `events[].data.tax` | object or null | No | Sales tax on the payment, on payment, refund and chargeback events of a taxed payment only. |
| `events[].data.reason` | one of `limit_exceeded` | No | Only on `payment.refused` when OnCharge refused the payment itself: `limit_exceeded` (the store reached a limit OnCharge set on its account, such as a daily volume cap). Absent when the bank declined it. |
| `events[].event` | one of `payment.pending`, `payment.authorized`, `payment.captured`, `payment.under_review`, `payment.refused`, `payment.cancelled`, `payment.expired`, `payment.capture_failed`, `refund.succeeded`, `refund.failed`, `chargeback.opened`, `dispute.evidence_due`, `chargeback.won`, `chargeback.lost`, `fraud_warning.received`, `delivery.confirmed`, `payout.paid`, `payout.failed`, `payout.returned`, `account.updated`, `account.requirements_due`, `account.restricted`, `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired`, `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.period.paid`, `subscription.period.payment_failed`, `support.conversation.created`, `support.message.received`, `support.conversation.closed` | No | Same as `type`. Kept for older plugins; only on payment events from a checkout. **Deprecated.** |
| `events[].status` | string or null | No | Same as `data.status`. Kept for older plugins; only on payment events from a checkout. **Deprecated.** |
| `events[].psp_reference` | string or null | No | Kept for older plugins, which store it as the order's transaction id: a payment made before 2026-12-01 keeps its original value here; from 2026-12-01 on it is the payment's OnCharge reference (`ocpay_…`, the same as `data.payment_reference`). Only on payment events from a checkout. **Deprecated.** |
| `next_cursor` | string or null | Yes | Pass as `cursor` for the next page; null on the last page. |
```json title="Response"
{
"events": [
{
"id": "string",
"type": "payment.pending",
"created": 0,
"livemode": true,
"data": {
"session_id": "string",
"order_id": "string",
"reference": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card",
"payment_reference": "string",
"payment_link_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"invoice_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"payment_method": "card",
"tax": {
"status": null,
"inclusive": null,
"currency": null,
"subtotal": null,
"amount": null,
"total": null,
"shipping": null,
"jurisdictions": null,
"refunded": null,
"error": null
},
"reason": "limit_exceeded"
},
"event": "payment.pending",
"status": "string",
"psp_reference": "string"
}
],
"next_cursor": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Events. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
### Retrieve an event {#getevent}
```http
GET /api/v1/events/{event_id}
```
One event from the last 30 days, exactly as your endpoints received it. An older event or another store's answers 404.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `event_id` | path | string | Yes | An event id (`evt_…`). |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string | Yes | Event ID (`evt_…`), the same as the `OnCharge-Event-Id` header. |
| `type` | one of `payment.pending`, `payment.authorized`, `payment.captured`, `payment.under_review`, `payment.refused`, `payment.cancelled`, `payment.expired`, `payment.capture_failed`, `refund.succeeded`, `refund.failed`, `chargeback.opened`, `dispute.evidence_due`, `chargeback.won`, `chargeback.lost`, `fraud_warning.received`, `delivery.confirmed`, `payout.paid`, `payout.failed`, `payout.returned`, `account.updated`, `account.requirements_due`, `account.restricted`, `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired`, `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.period.paid`, `subscription.period.payment_failed`, `support.conversation.created`, `support.message.received`, `support.conversation.closed` | Yes | Every event type. Payments on every rail use the same payment.* types (data.rail says which). Handle the types you need and acknowledge (2xx) any others; new types may be added. |
| `created` | integer | Yes | Unix time (seconds) the event was created. |
| `livemode` | boolean | Yes | false for events from test payments. |
| `data` | object | Yes | For payment events from a checkout, the fields below. Crypto and Card to Crypto paid to your wallet carry `session_id: null` with `payment_id`, `source`, `method`, `coin`, `coin_amount`, `wallet` and transaction hashes; every other event its own fields. All of them carry `rail`. |
| `data.session_id` | string or null | No | The checkout session; null for a payment paid straight to your wallet. |
| `data.order_id` | string or null | No | Your order ID, if known. |
| `data.reference` | string or null | No | The `reference` you sent when creating the session. |
| `data.amount` | integer or null | No | Minor units. For `refund.succeeded`, the total refunded so far. |
| `data.currency` | string or null | No | ISO 4217 code. |
| `data.status` | string or null | No | The order's payment status after the event (for example `captured`, `refunded`). |
| `data.rail` | one of `card`, `crypto`, `card_to_crypto` | Yes | The rail an event or payment is on: card checkout; crypto (crypto checkout, or a coin paid straight to your wallet through the plugin or the gateway API); or Card to Crypto (card, Cash App or Venmo paid out to your wallet in USDC). |
| `data.payment_reference` | string or null | No | OnCharge's reference for the payment (`ocpay_…`). |
| `data.payment_link_id` | string (uuid) or null | No | The payment link the checkout was made from (`/api/v1/payment-links`), or null. |
| `data.invoice_id` | string (uuid) | No | Only on a payment for an OnCharge invoice: the invoice's id (see Invoices). |
| `data.payment_method` | one of `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm`, `afterpay`, or `null` | No | How the shopper paid: `card`, or a way to pay beyond cards the store turned on (bank debit, Cash App Pay, Klarna, Affirm, Afterpay; see the Payment methods guide). Null for crypto. |
| `data.tax` | object or null | No | Sales tax on the payment, on payment, refund and chargeback events of a taxed payment only. |
| `data.tax.status` | one of `awaiting_address`, `calculated`, `pending`, `failed`, `collected`, `partly_refunded`, `refunded` | Yes | `awaiting_address`: no address yet, the payment waits. `calculated`: not paid yet. `pending`: tax included, charged while the calculation was unavailable; worked out shortly. `failed`: the calculation failed (`error`), the payment waits. `collected`, `partly_refunded`, `refunded`: paid, and how much of the tax was given back. |
| `data.tax.inclusive` | boolean | Yes | true when the listed prices include the tax. |
| `data.tax.currency` | string or null | Yes | |
| `data.tax.subtotal` | integer or null | Yes | Before tax, minor units. |
| `data.tax.amount` | integer or null | Yes | The tax, minor units. |
| `data.tax.total` | integer or null | Yes | What the customer pays, minor units. |
| `data.tax.shipping` | integer | Yes | The shipping charge inside the total, minor units. |
| `data.tax.jurisdictions` | array of object | Yes | |
| `data.tax.refunded` | integer | Yes | Tax given back so far with refunds and lost disputes, minor units. |
| `data.tax.error` | string or null | Yes | `tax_address_invalid` or `tax_unavailable` when `status` is `failed`. |
| `data.reason` | one of `limit_exceeded` | No | Only on `payment.refused` when OnCharge refused the payment itself: `limit_exceeded` (the store reached a limit OnCharge set on its account, such as a daily volume cap). Absent when the bank declined it. |
| `event` | one of `payment.pending`, `payment.authorized`, `payment.captured`, `payment.under_review`, `payment.refused`, `payment.cancelled`, `payment.expired`, `payment.capture_failed`, `refund.succeeded`, `refund.failed`, `chargeback.opened`, `dispute.evidence_due`, `chargeback.won`, `chargeback.lost`, `fraud_warning.received`, `delivery.confirmed`, `payout.paid`, `payout.failed`, `payout.returned`, `account.updated`, `account.requirements_due`, `account.restricted`, `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired`, `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.period.paid`, `subscription.period.payment_failed`, `support.conversation.created`, `support.message.received`, `support.conversation.closed` | No | Same as `type`. Kept for older plugins; only on payment events from a checkout. **Deprecated.** |
| `status` | string or null | No | Same as `data.status`. Kept for older plugins; only on payment events from a checkout. **Deprecated.** |
| `psp_reference` | string or null | No | Kept for older plugins, which store it as the order's transaction id: a payment made before 2026-12-01 keeps its original value here; from 2026-12-01 on it is the payment's OnCharge reference (`ocpay_…`, the same as `data.payment_reference`). Only on payment events from a checkout. **Deprecated.** |
```json title="Response"
{
"id": "string",
"type": "payment.pending",
"created": 0,
"livemode": true,
"data": {
"session_id": "string",
"order_id": "string",
"reference": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card",
"payment_reference": "string",
"payment_link_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"invoice_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"payment_method": "card",
"tax": {
"status": "awaiting_address",
"inclusive": true,
"currency": "string",
"subtotal": 0,
"amount": 0,
"total": 0,
"shipping": 0,
"jurisdictions": [
{
"state": null,
"rate": null,
"amount": null
}
],
"refunded": 0,
"error": "string"
},
"reason": "limit_exceeded"
},
"event": "payment.pending",
"status": "string",
"psp_reference": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The event. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Send an event to an endpoint again {#replayevent}
```http
POST /api/v1/events/{event_id}/replay
```
Sends an event from the last 30 days to one of your webhook endpoints again, with the same id and body, signed with that endpoint's secret. It goes even to an endpoint that has not chosen the event's type; a disabled endpoint answers 409. The delivery is retried like any other.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `event_id` | path | string | Yes | An event id (`evt_…`). |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `endpoint_id` | string (uuid) | Yes | One of your webhook endpoints (the Webhooks page shows their ids). |
```json title="Request"
{
"endpoint_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `event_id` | string | Yes | |
| `delivery_id` | string (uuid) | Yes | |
| `status` | one of `pending` | Yes | |
```json title="Response"
{
"event_id": "string",
"delivery_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"status": "pending"
}
```
| Status | Meaning |
|---|---|
| `200` | Queued. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | The endpoint is disabled. |
## Payments and balance {#payments-and-balance}
Payments on every rail, payouts to your bank and your balance, as the portal shows them.
### List payments {#listpayments}
```http
GET /api/v1/payments
```
The store's payments on every rail, newest first, from the activity ledger the portal reads: card checkout, crypto checkout, and crypto and Card to Crypto paid straight to your wallet through the plugin and the gateway API. `kind` lists refunds, disputes or crypto conversions instead, or all of them.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `kind` | query | one of `payment`, `refund`, `dispute`, `swap`, `all` | No | payment (default), refund, dispute, swap or all. |
| `rail` | query | one of `card`, `crypto`, `card_to_crypto` | No | |
| `status` | query | one of `paid`, `pending`, `refunded`, `failed`, `disputed`, `review`, `waiting`, `uncaptured` | No | |
| `source` | query | one of `wallet`, `plugin`, `gateway` | No | Paid straight to your wallet (plugin or gateway API), or one of them. |
| `q` | query | string | No | An OnCharge reference or id, a transaction hash, an email or an order number. |
| `from` | query | string (date) | No | |
| `to` | query | string (date) | No | |
| `min` | query | string | No | Smallest amount, in major units. |
| `max` | query | string | No | Largest amount, in major units. |
| `method` | query | one of `card`, `crypto`, `cashapp`, `venmo`, `bank` | No | |
| `signals` | query | string | No | Comma-separated: review, fraud_warning, disputed (every one listed must hold). |
| `limit` | query | integer | No | |
| `cursor` | query | string | No | `next_cursor` of the previous page, sent with the same filters. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `payments` | array of object | Yes | |
| `payments[].id` | string (uuid) | Yes | OnCharge's id of the payment, refund, dispute or conversion. |
| `payments[].reference` | string | Yes | OnCharge's reference: `ocpay_…`, `ocrfd_…`, `ocdsp_…`, `ocswp_…`. |
| `payments[].kind` | one of `payment`, `refund`, `dispute`, `swap` | Yes | |
| `payments[].rail` | one of `card`, `crypto`, `card_to_crypto` | Yes | The rail an event or payment is on: card checkout; crypto (crypto checkout, or a coin paid straight to your wallet through the plugin or the gateway API); or Card to Crypto (card, Cash App or Venmo paid out to your wallet in USDC). |
| `payments[].status` | string | Yes | paid, pending, authorized, review, refunded, partly_refunded, declined, failed, cancelled, expired, disputed, won, lost, completed… |
| `payments[].status_label` | string | No | |
| `payments[].amount` | integer or null | No | Null when only coin amounts are known. |
| `payments[].currency` | string or null | No | |
| `payments[].amount_text` | string or null | No | The coin amount as text when the amount in money is not known. |
| `payments[].fee` | integer or null | No | |
| `payments[].net` | integer or null | No | |
| `payments[].coin` | string or null | No | |
| `payments[].coin_amount` | string or null | No | |
| `payments[].coin_fee` | string or null | No | |
| `payments[].coin_net` | string or null | No | |
| `payments[].order_id` | string or null | No | |
| `payments[].method` | string or null | No | Visa •••• 4242, Cash App, USDT (TRC20)… |
| `payments[].customer_email` | string or null | No | |
| `payments[].created_at` | string (date-time) | Yes | |
| `payments[].payment_reference` | string or null | No | The payment a refund or dispute belongs to. |
| `payments[].payout_reference` | string or null | No | |
| `payments[].payment_tx` | string or null | No | The paying transaction on a public chain. |
| `payments[].payout_tx` | string or null | No | The transaction that paid your wallet. |
| `payments[].refundable` | integer | No | Minor units that can still be refunded (0 when this entry cannot be). |
| `payments[].signals` | array of one of `review`, `fraud_warning`, `disputed` | No | |
| `payments[].tax` | integer or null | No | Sales tax inside `amount`, minor units, signed like it (a refund's share given back is negative); null when untaxed. |
| `next_cursor` | string or null | Yes | Pass as `cursor` for the next page; null on the last page. |
```json title="Response"
{
"payments": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"reference": "string",
"kind": "payment",
"rail": "card",
"status": "string",
"status_label": "string",
"amount": 0,
"currency": "string",
"amount_text": "string",
"fee": 0,
"net": 0,
"coin": "string",
"coin_amount": "string",
"coin_fee": "string",
"coin_net": "string",
"order_id": "string",
"method": "string",
"customer_email": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"payment_reference": "string",
"payout_reference": "string",
"payment_tx": "string",
"payout_tx": "string",
"refundable": 0,
"signals": [
"review"
],
"tax": 0
}
],
"next_cursor": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Payments. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
### List payouts {#listpayouts}
```http
GET /api/v1/payouts
```
The store's payouts to its bank, newest first: on their way, paid, not delivered, returned or canceled, and bank debits. Payouts pay orders whose delivery was confirmed; crypto paid to your own wallet is never in a payout.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `status` | query | one of `paid`, `on_its_way`, `failed`, `returned`, `canceled` | No | |
| `from` | query | string (date) | No | |
| `to` | query | string (date) | No | |
| `min` | query | string | No | |
| `max` | query | string | No | |
| `q` | query | string | No | An order number, payment id or payout id. |
| `limit` | query | integer | No | |
| `cursor` | query | string | No | `next_cursor` of the previous page, sent with the same filters. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `payouts` | array of object | Yes | |
| `payouts[].id` | string (uuid) | Yes | The payout id the payout.paid, payout.failed and payout.returned events carry. |
| `payouts[].type` | one of `payout`, `bank_debit` | Yes | |
| `payouts[].status` | one of `paid`, `on_its_way`, `failed`, `returned`, `canceled` | Yes | |
| `payouts[].status_label` | string | No | |
| `payouts[].amount` | integer | Yes | Minor units; negative for a bank debit. |
| `payouts[].currency` | string | Yes | |
| `payouts[].created_at` | string (date-time) | Yes | |
| `payouts[].arrival_date` | string or null | No | |
| `payouts[].orders` | integer or null | No | Orders it paid, once its statement exists. |
| `payouts[].items` | integer | No | |
| `payouts[].problem` | string or null | No | Why it did not reach your bank (or, a debit card payout, your card), in plain words. |
| `payouts[].method` | one of `standard`, `instant` | No | `instant`: a debit card payout you asked for; `amount` is what reached the card. |
| `payouts[].fee` | integer | No | OnCharge's fee taken out of a debit card payout, in minor units (0 for a standard payout, and for one that did not arrive). |
| `next_cursor` | string or null | Yes | Pass as `cursor` for the next page; null on the last page. |
```json title="Response"
{
"payouts": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"type": "payout",
"status": "paid",
"status_label": "string",
"amount": 0,
"currency": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"arrival_date": "string",
"orders": 0,
"items": 0,
"problem": "string",
"method": "standard",
"fee": 0
}
],
"next_cursor": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Payouts. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
### Card totals for a period {#getpayoutsummary}
```http
GET /api/v1/payouts/summary
```
Gross volume, refunds, OnCharge's fees and what you keep, per currency, for a period (default the last 30 days, at most a year).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `from` | query | string (date) | No | First day (UTC). |
| `to` | query | string (date) | No | Last day (UTC). |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `period` | object | Yes | |
| `period.from` | string (date) | No | |
| `period.to` | string (date) | No | |
| `totals` | array of object | Yes | |
| `pricing` | object or null | No | |
| `fees` | array of object | No | |
```json title="Response"
{
"period": {
"from": "string",
"to": "string"
},
"totals": [
{}
],
"pricing": {},
"fees": [
{}
]
}
```
| Status | Meaning |
|---|---|
| `200` | Totals. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
### Quote a debit card payout {#getinstantpayout}
```http
GET /api/v1/payouts/instant
```
Whether the store can take a debit card payout now: what would reach the card, OnCharge's fee (1.5%, at least 0.50, taken out of the payout), what would leave the balance and when it should arrive; or why it cannot. Only money already released for delivered orders, and only what the next standard payout would pay, is ever payable. Claims nothing. The debit card is added in the dashboard (it needs a one-time code). 404 `not_available` where debit card payouts are not switched on.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `instant_payout` | object | Yes | What could reach your debit card now (money already released for delivered orders only), or why nothing can. |
| `instant_payout.store_id` | string (uuid) | Yes | |
| `instant_payout.available` | boolean | Yes | |
| `instant_payout.block` | object or null | Yes | |
| `instant_payout.amount` | integer | Yes | What would reach the card, in minor units. |
| `instant_payout.fee` | integer | Yes | OnCharge's fee, in minor units: 1.5% of the total, at least 0.50. |
| `instant_payout.total` | integer | Yes | What would leave your balance: amount + fee. |
| `instant_payout.currency` | one of `USD` | Yes | |
| `instant_payout.arrival` | object | Yes | |
| `instant_payout.arrival.text` | string | No | |
| `instant_payout.arrival.minutes` | integer | No | |
| `instant_payout.arrival.estimate` | string (date-time) or null | No | |
| `instant_payout.card` | object or null | Yes | The debit card on file, masked. Added in the dashboard only. |
| `instant_payout.card.brand` | string or null | No | |
| `instant_payout.card.last4` | string or null | No | |
| `instant_payout.card.exp_month` | integer or null | No | |
| `instant_payout.card.exp_year` | integer or null | No | |
| `instant_payout.card.status` | one of `cooling_off`, `ready` | No | |
| `instant_payout.card.usable_from` | string (date-time) | No | |
| `instant_payout.card.added_at` | string (date-time) | No | |
| `instant_payout.fee_rule` | object | Yes | |
| `instant_payout.fee_rule.percent` | number | No | |
| `instant_payout.fee_rule.minimum` | integer | No | |
| `instant_payout.limits` | object | Yes | |
| `instant_payout.limits.min` | integer | No | |
| `instant_payout.limits.per_payout_max` | integer | No | |
| `instant_payout.limits.daily_remaining_amount` | integer | No | |
| `instant_payout.limits.daily_remaining_count` | integer | No | |
```json title="Response"
{
"instant_payout": {
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"available": true,
"block": {
"code": "not_available",
"message": "string",
"until": "2026-01-01T00:00:00.000Z",
"action": {
"label": null,
"href": null
}
},
"amount": 0,
"fee": 0,
"total": 0,
"currency": "USD",
"arrival": {
"text": "Usually within 30 minutes",
"minutes": 0,
"estimate": "2026-01-01T00:00:00.000Z"
},
"card": {
"brand": "string",
"last4": "string",
"exp_month": 0,
"exp_year": 0,
"status": "cooling_off",
"usable_from": "2026-01-01T00:00:00.000Z",
"added_at": "2026-01-01T00:00:00.000Z"
},
"fee_rule": {
"percent": 0,
"minimum": 0
},
"limits": {
"min": 0,
"per_payout_max": 0,
"daily_remaining_amount": 0,
"daily_remaining_count": 0
}
}
}
```
| Status | Meaning |
|---|---|
| `200` | The quote. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Make a debit card payout {#createinstantpayout}
```http
POST /api/v1/payouts/instant
```
Sends what the quote showed to the store's debit card. An `Idempotency-Key` is required: the same key always answers with the same payout (200, `replay: true`) and never pays twice. Send `expected_amount` (the quote's `amount`): when what is payable changed, nothing is paid and the answer is 409 `quote_changed` with a fresh quote. Refused (409) while payouts are paused (a bank change's cooling-off included), during a new card's cooling-off, over the daily limits, or when nothing released is payable. The result arrives as `payout.paid` or `payout.failed` with `method: "instant"`; a failed debit card payout goes to your bank with your next payout, its fee refunded.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `expected_amount` | integer (≥ 1) | No | What you expect to reach the card, in minor units. |
```json title="Request"
{
"expected_amount": 1
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `payout` | object | Yes | |
| `payout.id` | string (uuid) | Yes | The id the payouts list and the payout.paid / payout.failed events carry. |
| `payout.method` | one of `instant` | Yes | |
| `payout.status` | one of `paid`, `on_its_way`, `failed`, `returned`, `canceled` | Yes | |
| `payout.amount` | integer | Yes | What reaches the card. |
| `payout.fee` | integer | Yes | |
| `payout.total` | integer | Yes | What left your balance. |
| `payout.currency` | string | Yes | |
| `payout.created_at` | string (date-time) | Yes | |
| `payout.arrival` | object | Yes | |
| `payout.arrival.text` | string | No | |
| `payout.arrival.estimate` | string (date-time) or null | No | |
| `replay` | boolean | Yes | True when this Idempotency-Key was used before: the same payout, not a new one. |
```json title="Response"
{
"payout": {
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"method": "instant",
"status": "paid",
"amount": 0,
"fee": 0,
"total": 0,
"currency": "string",
"created_at": "2026-01-01T00:00:00.000Z",
"arrival": {
"text": "string",
"estimate": "2026-01-01T00:00:00.000Z"
}
},
"replay": true
}
```
| Status | Meaning |
|---|---|
| `200` | This key was used before: the same payout. |
| `201` | Made. |
| `400` | Refused: `error` is the block's code (or `quote_changed`, `invalid_request_key`, `invalid_amount`), `message` says why in plain words, `until` when it lifts by itself. With `quote_changed`, `instant_payout` is a fresh quote. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | Refused: `error` is the block's code (or `quote_changed`, `invalid_request_key`, `invalid_amount`), `message` says why in plain words, `until` when it lifts by itself. With `quote_changed`, `instant_payout` is a fresh quote. |
| `502` | Refused: `error` is the block's code (or `quote_changed`, `invalid_request_key`, `invalid_amount`), `message` says why in plain words, `until` when it lifts by itself. With `quote_changed`, `instant_payout` is a fresh quote. |
| `503` | Refused: `error` is the block's code (or `quote_changed`, `invalid_request_key`, `invalid_amount`), `message` says why in plain words, `until` when it lifts by itself. With `quote_changed`, `instant_payout` is a fresh quote. |
### Retrieve the balance {#getbalance}
```http
GET /api/v1/balance
```
Where your money is, as the Balances page shows it.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `as_of` | string (date-time) | Yes | |
| `card` | object | Yes | |
| `next_payouts` | array of object | No | |
| `on_its_way` | array of object | No | |
| `delivery` | object | No | |
| `wallet` | object or null | No | |
```json title="Response"
{
"as_of": "2026-01-01T00:00:00.000Z",
"card": {},
"next_payouts": [
{}
],
"on_its_way": [
{}
],
"delivery": {},
"wallet": {}
}
```
| Status | Meaning |
|---|---|
| `200` | The balance. |
### List payment methods {#listpaymentmethods}
```http
GET /api/v1/payment-methods
```
The store's ways to pay beyond cards (bank debit, Cash App Pay, Klarna, Affirm, Afterpay), whether each is turned on, and its status in plain words. Read-only: owners and admins turn methods on in the portal.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `store_id` | string (uuid) | Yes | |
| `methods` | array of object | Yes | Only the methods OnCharge offers today. |
| `methods[].method` | one of `bank_debit`, `cash_app_pay`, `klarna`, `affirm`, `afterpay` | Yes | |
| `methods[].label` | string | Yes | |
| `methods[].summary` | string | Yes | What the method does for your store, in one or two sentences. |
| `methods[].enabled` | boolean | Yes | Whether the store turned it on (owners and admins, in the portal under Settings → Payment setup). |
| `methods[].state` | one of `off`, `not_available`, `requesting`, `reviewing`, `needs_information`, `inactive`, `active` | Yes | `active`: shoppers see it at checkout. `not_available`: not offered to this store's business. |
| `methods[].status_text` | string | Yes | The state in plain words. |
| `methods[].needs` | array of string | Yes | What is still needed before it can be approved, in words. |
```json title="Response"
{
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"methods": [
{
"method": "bank_debit",
"label": "Bank debit (ACH)",
"summary": "string",
"enabled": true,
"state": "off",
"status_text": "string",
"needs": [
"string"
]
}
]
}
```
| Status | Meaning |
|---|---|
| `200` | The store's payment methods. |
## Payment links {#payment-links}
Shareable OnCharge pages (/l/) that take a payment without a website. Each payment is an ordinary checkout session.
### List payment links {#listpaymentlinks}
```http
GET /api/v1/payment-links
```
The store's payment links, newest first, each with its views, checkouts, payments and revenue. Sign an empty body.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `active` | query | boolean | No | Only links that are on (`true`) or off (`false`). |
| `limit` | query | integer | No | |
| `before` | query | string (date-time) | No | `next_before` from the previous page. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `object` | `"list"` | Yes | |
| `data` | array of object | Yes | |
| `data[].id` | string (uuid) | Yes | |
| `data[].object` | `"payment_link"` | Yes | |
| `data[].store_id` | string (uuid) | Yes | |
| `data[].code` | string | Yes | |
| `data[].url` | string (uri) | Yes | The link to share: `https://app.oncharge.io/l/`. |
| `data[].title` | string | Yes | |
| `data[].description` | string or null | No | |
| `data[].amount_type` | one of `fixed`, `customer_chosen` | Yes | |
| `data[].amount` | integer or null | No | |
| `data[].min_amount` | integer or null | No | |
| `data[].max_amount` | integer or null | No | |
| `data[].preset_amount` | integer or null | No | |
| `data[].currency` | string | Yes | |
| `data[].adjustable_quantity` | boolean | No | |
| `data[].max_quantity` | integer | No | |
| `data[].collect_shipping` | boolean | No | |
| `data[].collect_phone` | boolean | No | |
| `data[].success_url` | string or null | No | |
| `data[].rails` | array of one of `card`, `crypto` | No | |
| `data[].active` | boolean | Yes | |
| `data[].status` | one of `active`, `inactive`, `expired` | Yes | `active`: takes payments; `inactive`: turned off; `expired`: past `expires_at`. |
| `data[].expires_at` | string (date-time) or null | No | |
| `data[].deactivated_at` | string (date-time) or null | No | |
| `data[].created_via` | one of `dashboard`, `api` | No | |
| `data[].created_at` | string (date-time) | Yes | |
| `data[].updated_at` | string (date-time) or null | No | |
| `data[].stats` | object | Yes | |
| `data[].stats.views` | integer | Yes | Visits of the link page while it was active. |
| `data[].stats.checkouts` | integer | Yes | Checkouts started from the link. |
| `data[].stats.payments` | integer | Yes | Paid checkouts (captured, or refunded afterwards). |
| `data[].stats.revenue` | integer | Yes | What the paid checkouts came to before refunds, minor units of the link's currency. |
| `data[].stats.refunded` | integer | Yes | What was refunded of them. |
| `data[].qr_code` | string or null | No | An SVG QR code of `url` as a data URI (single-link responses). |
| `has_more` | boolean | Yes | |
| `next_before` | string or null | Yes | Pass as `before` for the next page. |
```json title="Response"
{
"object": "list",
"data": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_link",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"code": "string",
"url": "string",
"title": "string",
"description": "string",
"amount_type": "fixed",
"amount": 0,
"min_amount": 0,
"max_amount": 0,
"preset_amount": 0,
"currency": "string",
"adjustable_quantity": true,
"max_quantity": 0,
"collect_shipping": true,
"collect_phone": true,
"success_url": "string",
"rails": [
"card"
],
"active": true,
"status": "active",
"expires_at": "2026-01-01T00:00:00.000Z",
"deactivated_at": "2026-01-01T00:00:00.000Z",
"created_via": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z",
"stats": {
"views": 0,
"checkouts": 0,
"payments": 0,
"revenue": 0,
"refunded": 0
},
"qr_code": "string"
}
],
"has_more": true,
"next_before": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | A page of payment links. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
### Create a payment link {#createpaymentlink}
```http
POST /api/v1/payment-links
```
Makes a link at `https://app.oncharge.io/l/`. Each visit that pays creates an ordinary checkout session (card or crypto, whichever the store has on), so the `payment.*` webhooks fire for it with `data.reference` = `link_`, and shipped goods are paid out after delivery like any other order.
Limits: a fixed amount of at least 50 cents; `amount` × `max_quantity` (or `max_amount`) at most $10,000; quantity up to 99; expiry at most two years ahead. A store that ships what it sells must set `collect_shipping`. `success_url` must be https on one of the store's registered domains.
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `title` | string (min 1 chars, max 120 chars) | Yes | |
| `description` | string or null (max 500 chars) | No | |
| `amount_type` | one of `fixed`, `customer_chosen` | No | `fixed`: the customer pays `amount` per item. `customer_chosen`: they choose between `min_amount` and `max_amount`. Default `"fixed"`. |
| `amount` | integer or null (≥ 1) | No | Per item, for a fixed amount. Minor units (cents), at least 50. |
| `min_amount` | integer or null (≥ 1) | No | Customer-chosen amounts: the least they may pay (default 50). |
| `max_amount` | integer or null (≥ 1) | No | Customer-chosen amounts: the most they may pay (default 1000000, $10,000). |
| `preset_amount` | integer or null (≥ 1) | No | Customer-chosen amounts: where the amount field starts. |
| `currency` | string | No | Card payments are USD only on stores paid out per delivered order. Default `"USD"`. |
| `adjustable_quantity` | boolean | No | Default `false`. |
| `max_quantity` | integer or null (≥ 1, ≤ 99) | No | Default 10 when `adjustable_quantity` is on. |
| `collect_shipping` | boolean | No | Ask for a shipping address (required on stores that ship what they sell). Default `false`. |
| `collect_phone` | boolean | No | Default `false`. |
| `success_url` | string (uri) or null | No | https, on one of the store's registered domains. Default: OnCharge's thank-you page. |
| `rails` | array of one of `card`, `crypto` or null (≥ 1 items) | No | Ways to pay allowed on the link (default both); the store must have them on. |
| `expires_at` | string (date-time) or null | No | |
```json title="Request"
{
"title": "Consultation deposit",
"amount": 5000,
"currency": "USD",
"collect_phone": true,
"success_url": "https://shop.example.com/thank-you"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"payment_link"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `code` | string | Yes | |
| `url` | string (uri) | Yes | The link to share: `https://app.oncharge.io/l/`. |
| `title` | string | Yes | |
| `description` | string or null | No | |
| `amount_type` | one of `fixed`, `customer_chosen` | Yes | |
| `amount` | integer or null | No | |
| `min_amount` | integer or null | No | |
| `max_amount` | integer or null | No | |
| `preset_amount` | integer or null | No | |
| `currency` | string | Yes | |
| `adjustable_quantity` | boolean | No | |
| `max_quantity` | integer | No | |
| `collect_shipping` | boolean | No | |
| `collect_phone` | boolean | No | |
| `success_url` | string or null | No | |
| `rails` | array of one of `card`, `crypto` | No | |
| `active` | boolean | Yes | |
| `status` | one of `active`, `inactive`, `expired` | Yes | `active`: takes payments; `inactive`: turned off; `expired`: past `expires_at`. |
| `expires_at` | string (date-time) or null | No | |
| `deactivated_at` | string (date-time) or null | No | |
| `created_via` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | Yes | |
| `updated_at` | string (date-time) or null | No | |
| `stats` | object | Yes | |
| `stats.views` | integer | Yes | Visits of the link page while it was active. |
| `stats.checkouts` | integer | Yes | Checkouts started from the link. |
| `stats.payments` | integer | Yes | Paid checkouts (captured, or refunded afterwards). |
| `stats.revenue` | integer | Yes | What the paid checkouts came to before refunds, minor units of the link's currency. |
| `stats.refunded` | integer | Yes | What was refunded of them. |
| `qr_code` | string or null | No | An SVG QR code of `url` as a data URI (single-link responses). |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_link",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"code": "string",
"url": "string",
"title": "string",
"description": "string",
"amount_type": "fixed",
"amount": 0,
"min_amount": 0,
"max_amount": 0,
"preset_amount": 0,
"currency": "string",
"adjustable_quantity": true,
"max_quantity": 0,
"collect_shipping": true,
"collect_phone": true,
"success_url": "string",
"rails": [
"card"
],
"active": true,
"status": "active",
"expires_at": "2026-01-01T00:00:00.000Z",
"deactivated_at": "2026-01-01T00:00:00.000Z",
"created_via": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z",
"stats": {
"views": 0,
"checkouts": 0,
"payments": 0,
"revenue": 0,
"refunded": 0
},
"qr_code": "string"
}
```
| Status | Meaning |
|---|---|
| `201` | The new link, with its QR code. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `409` | `payment_method_unavailable`: none of the link's ways to pay (`rails`) is on for the store yet. |
### Retrieve a payment link {#getpaymentlink}
```http
GET /api/v1/payment-links/{link_id}
```
One link with its stats and QR code. Another store's link answers `404`. Sign an empty body.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `link_id` | path | string (uuid) | Yes | The payment link's `id`. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"payment_link"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `code` | string | Yes | |
| `url` | string (uri) | Yes | The link to share: `https://app.oncharge.io/l/`. |
| `title` | string | Yes | |
| `description` | string or null | No | |
| `amount_type` | one of `fixed`, `customer_chosen` | Yes | |
| `amount` | integer or null | No | |
| `min_amount` | integer or null | No | |
| `max_amount` | integer or null | No | |
| `preset_amount` | integer or null | No | |
| `currency` | string | Yes | |
| `adjustable_quantity` | boolean | No | |
| `max_quantity` | integer | No | |
| `collect_shipping` | boolean | No | |
| `collect_phone` | boolean | No | |
| `success_url` | string or null | No | |
| `rails` | array of one of `card`, `crypto` | No | |
| `active` | boolean | Yes | |
| `status` | one of `active`, `inactive`, `expired` | Yes | `active`: takes payments; `inactive`: turned off; `expired`: past `expires_at`. |
| `expires_at` | string (date-time) or null | No | |
| `deactivated_at` | string (date-time) or null | No | |
| `created_via` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | Yes | |
| `updated_at` | string (date-time) or null | No | |
| `stats` | object | Yes | |
| `stats.views` | integer | Yes | Visits of the link page while it was active. |
| `stats.checkouts` | integer | Yes | Checkouts started from the link. |
| `stats.payments` | integer | Yes | Paid checkouts (captured, or refunded afterwards). |
| `stats.revenue` | integer | Yes | What the paid checkouts came to before refunds, minor units of the link's currency. |
| `stats.refunded` | integer | Yes | What was refunded of them. |
| `qr_code` | string or null | No | An SVG QR code of `url` as a data URI (single-link responses). |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_link",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"code": "string",
"url": "string",
"title": "string",
"description": "string",
"amount_type": "fixed",
"amount": 0,
"min_amount": 0,
"max_amount": 0,
"preset_amount": 0,
"currency": "string",
"adjustable_quantity": true,
"max_quantity": 0,
"collect_shipping": true,
"collect_phone": true,
"success_url": "string",
"rails": [
"card"
],
"active": true,
"status": "active",
"expires_at": "2026-01-01T00:00:00.000Z",
"deactivated_at": "2026-01-01T00:00:00.000Z",
"created_via": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z",
"stats": {
"views": 0,
"checkouts": 0,
"payments": 0,
"revenue": 0,
"refunded": 0
},
"qr_code": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The link. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Update a payment link {#updatepaymentlink}
```http
POST /api/v1/payment-links/{link_id}
```
Changes any field of the link, checked as a whole link again, or turns it off (`active: false`) or back on (`active: true`). Switching `amount_type` drops the other kind's amounts.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `link_id` | path | string (uuid) | Yes | The payment link's `id`. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `title` | string (min 1 chars, max 120 chars) | No | |
| `description` | string or null (max 500 chars) | No | |
| `amount_type` | one of `fixed`, `customer_chosen` | No | `fixed`: the customer pays `amount` per item. `customer_chosen`: they choose between `min_amount` and `max_amount`. Default `"fixed"`. |
| `amount` | integer or null (≥ 1) | No | Per item, for a fixed amount. Minor units (cents), at least 50. |
| `min_amount` | integer or null (≥ 1) | No | Customer-chosen amounts: the least they may pay (default 50). |
| `max_amount` | integer or null (≥ 1) | No | Customer-chosen amounts: the most they may pay (default 1000000, $10,000). |
| `preset_amount` | integer or null (≥ 1) | No | Customer-chosen amounts: where the amount field starts. |
| `currency` | string | No | Card payments are USD only on stores paid out per delivered order. Default `"USD"`. |
| `adjustable_quantity` | boolean | No | Default `false`. |
| `max_quantity` | integer or null (≥ 1, ≤ 99) | No | Default 10 when `adjustable_quantity` is on. |
| `collect_shipping` | boolean | No | Ask for a shipping address (required on stores that ship what they sell). Default `false`. |
| `collect_phone` | boolean | No | Default `false`. |
| `success_url` | string (uri) or null | No | https, on one of the store's registered domains. Default: OnCharge's thank-you page. |
| `rails` | array of one of `card`, `crypto` or null (≥ 1 items) | No | Ways to pay allowed on the link (default both); the store must have them on. |
| `expires_at` | string (date-time) or null | No | |
| `active` | boolean | No | Turn the link off (`false`) or back on (`true`). |
```json title="Request"
{
"title": "Consultation deposit (December)",
"expires_at": "2026-12-31T23:59:59Z"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"payment_link"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `code` | string | Yes | |
| `url` | string (uri) | Yes | The link to share: `https://app.oncharge.io/l/`. |
| `title` | string | Yes | |
| `description` | string or null | No | |
| `amount_type` | one of `fixed`, `customer_chosen` | Yes | |
| `amount` | integer or null | No | |
| `min_amount` | integer or null | No | |
| `max_amount` | integer or null | No | |
| `preset_amount` | integer or null | No | |
| `currency` | string | Yes | |
| `adjustable_quantity` | boolean | No | |
| `max_quantity` | integer | No | |
| `collect_shipping` | boolean | No | |
| `collect_phone` | boolean | No | |
| `success_url` | string or null | No | |
| `rails` | array of one of `card`, `crypto` | No | |
| `active` | boolean | Yes | |
| `status` | one of `active`, `inactive`, `expired` | Yes | `active`: takes payments; `inactive`: turned off; `expired`: past `expires_at`. |
| `expires_at` | string (date-time) or null | No | |
| `deactivated_at` | string (date-time) or null | No | |
| `created_via` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | Yes | |
| `updated_at` | string (date-time) or null | No | |
| `stats` | object | Yes | |
| `stats.views` | integer | Yes | Visits of the link page while it was active. |
| `stats.checkouts` | integer | Yes | Checkouts started from the link. |
| `stats.payments` | integer | Yes | Paid checkouts (captured, or refunded afterwards). |
| `stats.revenue` | integer | Yes | What the paid checkouts came to before refunds, minor units of the link's currency. |
| `stats.refunded` | integer | Yes | What was refunded of them. |
| `qr_code` | string or null | No | An SVG QR code of `url` as a data URI (single-link responses). |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_link",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"code": "string",
"url": "string",
"title": "string",
"description": "string",
"amount_type": "fixed",
"amount": 0,
"min_amount": 0,
"max_amount": 0,
"preset_amount": 0,
"currency": "string",
"adjustable_quantity": true,
"max_quantity": 0,
"collect_shipping": true,
"collect_phone": true,
"success_url": "string",
"rails": [
"card"
],
"active": true,
"status": "active",
"expires_at": "2026-01-01T00:00:00.000Z",
"deactivated_at": "2026-01-01T00:00:00.000Z",
"created_via": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z",
"stats": {
"views": 0,
"checkouts": 0,
"payments": 0,
"revenue": 0,
"refunded": 0
},
"qr_code": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The changed link. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `payment_method_unavailable`: none of the link's ways to pay (`rails`) is on for the store yet. |
### Deactivate a payment link {#deactivatepaymentlink}
```http
POST /api/v1/payment-links/{link_id}/deactivate
```
Turns the link off: visits say it is no longer active and no new checkout starts. Its payments stay. Idempotent. Sign an empty body or `{}`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `link_id` | path | string (uuid) | Yes | The payment link's `id`. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"payment_link"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `code` | string | Yes | |
| `url` | string (uri) | Yes | The link to share: `https://app.oncharge.io/l/`. |
| `title` | string | Yes | |
| `description` | string or null | No | |
| `amount_type` | one of `fixed`, `customer_chosen` | Yes | |
| `amount` | integer or null | No | |
| `min_amount` | integer or null | No | |
| `max_amount` | integer or null | No | |
| `preset_amount` | integer or null | No | |
| `currency` | string | Yes | |
| `adjustable_quantity` | boolean | No | |
| `max_quantity` | integer | No | |
| `collect_shipping` | boolean | No | |
| `collect_phone` | boolean | No | |
| `success_url` | string or null | No | |
| `rails` | array of one of `card`, `crypto` | No | |
| `active` | boolean | Yes | |
| `status` | one of `active`, `inactive`, `expired` | Yes | `active`: takes payments; `inactive`: turned off; `expired`: past `expires_at`. |
| `expires_at` | string (date-time) or null | No | |
| `deactivated_at` | string (date-time) or null | No | |
| `created_via` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | Yes | |
| `updated_at` | string (date-time) or null | No | |
| `stats` | object | Yes | |
| `stats.views` | integer | Yes | Visits of the link page while it was active. |
| `stats.checkouts` | integer | Yes | Checkouts started from the link. |
| `stats.payments` | integer | Yes | Paid checkouts (captured, or refunded afterwards). |
| `stats.revenue` | integer | Yes | What the paid checkouts came to before refunds, minor units of the link's currency. |
| `stats.refunded` | integer | Yes | What was refunded of them. |
| `qr_code` | string or null | No | An SVG QR code of `url` as a data URI (single-link responses). |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "payment_link",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"code": "string",
"url": "string",
"title": "string",
"description": "string",
"amount_type": "fixed",
"amount": 0,
"min_amount": 0,
"max_amount": 0,
"preset_amount": 0,
"currency": "string",
"adjustable_quantity": true,
"max_quantity": 0,
"collect_shipping": true,
"collect_phone": true,
"success_url": "string",
"rails": [
"card"
],
"active": true,
"status": "active",
"expires_at": "2026-01-01T00:00:00.000Z",
"deactivated_at": "2026-01-01T00:00:00.000Z",
"created_via": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"updated_at": "2026-01-01T00:00:00.000Z",
"stats": {
"views": 0,
"checkouts": 0,
"payments": 0,
"revenue": 0,
"refunded": 0
},
"qr_code": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The link, now off. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
## Invoices {#invoices}
Bill a customer: draft, finalize, send and get paid on OnCharge's hosted invoice page through OnCharge checkout, by card or crypto. Reminders, mark paid, void and credit notes.
### List invoices {#listinvoices}
```http
GET /api/v1/invoices
```
The store's invoices, newest first. `kind=credit_note` lists credit notes.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `status` | query | one of `draft`, `open`, `overdue`, `paid`, `void`, `all` | No | |
| `search` | query | string | No | An invoice number, a customer email, or part of a customer name. |
| `cursor` | query | string | No | `next_cursor` from the previous page. |
| `limit` | query | integer | No | |
| `kind` | query | one of `invoice`, `credit_note` | No | |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `invoices` | array of object | Yes | |
| `invoices[].id` | string (uuid) | Yes | |
| `invoices[].object` | one of `invoice`, `credit_note` | Yes | |
| `invoices[].store_id` | string (uuid) | No | |
| `invoices[].number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `invoices[].status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `invoices[].display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `invoices[].status_label` | string | No | |
| `invoices[].currency` | string | Yes | |
| `invoices[].currency_digits` | integer | No | |
| `invoices[].customer` | object | No | |
| `invoices[].customer.name` | string or null | No | |
| `invoices[].customer.email` | string or null | No | |
| `invoices[].customer.address` | object or null | No | |
| `invoices[].shipping_address` | object or null | No | |
| `invoices[].lines` | array of object | Yes | |
| `invoices[].lines[].description` | string | No | |
| `invoices[].lines[].quantity` | integer | No | |
| `invoices[].lines[].unit_amount` | integer | No | |
| `invoices[].lines[].tax_rate` | number | No | |
| `invoices[].lines[].amount` | integer | No | |
| `invoices[].lines[].tax_amount` | integer | No | |
| `invoices[].lines[].requires_shipping` | boolean | No | |
| `invoices[].subtotal` | integer | No | |
| `invoices[].tax` | integer | No | |
| `invoices[].total` | integer | Yes | |
| `invoices[].amount_paid` | integer | No | |
| `invoices[].amount_credited` | integer | No | |
| `invoices[].amount_remaining` | integer | Yes | |
| `invoices[].memo` | string or null | No | |
| `invoices[].footer` | string or null | No | |
| `invoices[].reply_to` | string or null | No | |
| `invoices[].days_until_due` | integer | No | |
| `invoices[].due_at` | string (date-time) or null | No | |
| `invoices[].send_reminders` | boolean | No | |
| `invoices[].metadata` | object | No | |
| `invoices[].hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `invoices[].paid_out_of_band` | boolean | No | |
| `invoices[].payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `invoices[].credit_note_for` | object or null | No | |
| `invoices[].credit_note_for.id` | string | No | |
| `invoices[].credit_note_for.number` | string or null | No | |
| `invoices[].credit_reason` | string or null | No | |
| `invoices[].source` | one of `dashboard`, `api` | No | |
| `invoices[].created_at` | string (date-time) | No | |
| `invoices[].finalized_at` | string or null | No | |
| `invoices[].sent_at` | string or null | No | |
| `invoices[].paid_at` | string or null | No | |
| `invoices[].voided_at` | string or null | No | |
| `invoices[].actions` | object | No | What can be done now. |
| `invoices[].events` | array of object | No | History (detail only). |
| `invoices[].payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `invoices[].payments[].payment_reference` | string | No | |
| `invoices[].payments[].session_id` | string | No | |
| `invoices[].payments[].amount` | integer | No | |
| `invoices[].payments[].currency` | string | No | |
| `invoices[].payments[].status` | string | No | |
| `invoices[].payments[].rail` | one of `card`, `crypto` | No | |
| `invoices[].credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `invoices[].payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `invoices[].payment_options[].rail` | string | No | |
| `invoices[].payment_options[].available` | boolean | No | |
| `invoices[].payment_options[].reason` | string or null | No | |
| `invoices[].idempotent` | boolean | No | |
| `invoices[].email_error` | string | No | Finalized, but the email could not be sent. |
| `next_cursor` | string or null | Yes | Pass back as `cursor`; null on the last page. |
```json title="Response"
{
"invoices": [
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": null
},
"shipping_address": {
"line1": null,
"line2": null,
"city": null,
"state": null,
"postal_code": null,
"country": null
},
"lines": [
{
"description": null,
"quantity": null,
"unit_amount": null,
"tax_rate": null,
"amount": null,
"tax_amount": null,
"requires_shipping": null
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": null,
"session_id": null,
"amount": null,
"currency": null,
"status": null,
"rail": null
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": null,
"available": null,
"reason": null
}
],
"idempotent": true,
"email_error": "string"
}
],
"next_cursor": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | A page of invoices. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Create an invoice {#createinvoice}
```http
POST /api/v1/invoices
```
A new draft. With `finalize` it is also numbered and opened for payment; with `send` it is also emailed to the customer (PDF attached). The bill-to details live on the invoice. A repeat with the same `Idempotency-Key` returns the first draft with `idempotent: true`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `currency` | one of `USD`, `EUR`, `GBP`, `CAD`, `AUD`, `NZD`, `CHF`, `JPY` | No | Amounts are in this currency's minor units (JPY has none). Card payments on stores paid out per delivered order are USD only. Default `"USD"`. |
| `customer` | object | No | |
| `customer.name` | string or null (max 200 chars) | No | Required to finalize. |
| `customer.email` | string (email) or null | No | Required to send. |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | Needed when a line ships and the store's card payments are paid out on delivery. |
| `lines` | array of object (≤ 100 items) | No | On update, replaces every line. |
| `lines[].description` | string (min 1 chars, max 500 chars) | Yes | |
| `lines[].quantity` | integer (≥ 1, ≤ 100000) | Yes | |
| `lines[].unit_amount` | integer (≥ -10000000000, ≤ 10000000000) | Yes | Minor units of the invoice currency; negative for a discount line. quantity x unit_amount may be at most 10000000000 either way. |
| `lines[].tax_rate` | number or string | No | A percent from 0 to 100 with up to three decimals, e.g. `8.875`. Tax is rounded half away from zero per line. |
| `lines[].requires_shipping` | boolean | No | A shipped item. Card payments for it are paid out after the carrier confirms delivery to `shipping_address`, as for any order. Default `false`. |
| `memo` | string or null (max 2000 chars) | No | |
| `footer` | string or null (max 1000 chars) | No | |
| `reply_to` | string (email) or null | No | Where the customer's replies to invoice emails go. |
| `days_until_due` | integer (≥ 0, ≤ 365) | No | Default `30`. |
| `due_at` | string or null | No | A date (`YYYY-MM-DD`, end of that day UTC) or an ISO 8601 time. Overrides `days_until_due`; must not be in the past when finalizing. |
| `send_reminders` | boolean | No | Email the customer 1, 7 and 14 days after the due date while it is unpaid. Default `true`. |
| `metadata` | object | No | |
| `finalize` | boolean | No | Finalize it straight away. |
| `send` | boolean | No | Finalize it and email it to the customer. |
```json title="Request"
{
"customer": {
"name": "Ada Lovelace",
"email": "ada@example.com"
},
"lines": [
{
"description": "Consulting, November",
"quantity": 10,
"unit_amount": 15000,
"tax_rate": 8.875
}
],
"days_until_due": 14,
"send": true
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay. |
| `201` | Created (and finalized or sent when asked). |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `store_inactive`: the store is not taking payments. |
| `422` | `invoice_incomplete`: finalizing needs a line, a total above zero and the customer's name; `invoice_too_large`: the lines would total more than 100000000000 minor units. |
### Retrieve an invoice {#getinvoice}
```http
GET /api/v1/invoices/{invoice_id}
```
The invoice or credit note with its lines, history, payments (OnCharge references), credit notes and how it can be paid now.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The invoice. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Update a draft {#updateinvoice}
```http
POST /api/v1/invoices/{invoice_id}
```
Any draft field; `lines` replaces every line. A finalized invoice cannot be edited: void it and create another, or issue a credit note.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `currency` | one of `USD`, `EUR`, `GBP`, `CAD`, `AUD`, `NZD`, `CHF`, `JPY` | No | Amounts are in this currency's minor units (JPY has none). Card payments on stores paid out per delivered order are USD only. Default `"USD"`. |
| `customer` | object | No | |
| `customer.name` | string or null (max 200 chars) | No | Required to finalize. |
| `customer.email` | string (email) or null | No | Required to send. |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | Needed when a line ships and the store's card payments are paid out on delivery. |
| `lines` | array of object (≤ 100 items) | No | On update, replaces every line. |
| `lines[].description` | string (min 1 chars, max 500 chars) | Yes | |
| `lines[].quantity` | integer (≥ 1, ≤ 100000) | Yes | |
| `lines[].unit_amount` | integer (≥ -10000000000, ≤ 10000000000) | Yes | Minor units of the invoice currency; negative for a discount line. quantity x unit_amount may be at most 10000000000 either way. |
| `lines[].tax_rate` | number or string | No | A percent from 0 to 100 with up to three decimals, e.g. `8.875`. Tax is rounded half away from zero per line. |
| `lines[].requires_shipping` | boolean | No | A shipped item. Card payments for it are paid out after the carrier confirms delivery to `shipping_address`, as for any order. Default `false`. |
| `memo` | string or null (max 2000 chars) | No | |
| `footer` | string or null (max 1000 chars) | No | |
| `reply_to` | string (email) or null | No | Where the customer's replies to invoice emails go. |
| `days_until_due` | integer (≥ 0, ≤ 365) | No | Default `30`. |
| `due_at` | string or null | No | A date (`YYYY-MM-DD`, end of that day UTC) or an ISO 8601 time. Overrides `days_until_due`; must not be in the past when finalizing. |
| `send_reminders` | boolean | No | Email the customer 1, 7 and 14 days after the due date while it is unpaid. Default `true`. |
| `metadata` | object | No | |
```json title="Request"
{
"memo": "Thanks for your business."
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The draft. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
### Delete a draft {#deleteinvoice}
```http
DELETE /api/v1/invoices/{invoice_id}
```
Only a draft can be deleted.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string | No | |
| `deleted` | boolean | No | |
```json title="Response"
{
"id": "string",
"deleted": true
}
```
| Status | Meaning |
|---|---|
| `200` | Deleted. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
### Finalize a draft {#finalizeinvoice}
```http
POST /api/v1/invoices/{invoice_id}/finalize
```
Gives the draft its store's next number (`INV-0001`), a due date and its hosted invoice page (`hosted_url`). Nothing on it can change afterwards. With `send`, also emails it.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `send` | boolean | No | |
```json title="Request"
{
"send": true
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The invoice. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
| `422` | `invoice_incomplete`. |
### Email an open invoice {#sendinvoice}
```http
POST /api/v1/invoices/{invoice_id}/send
```
Emails the invoice (again) to the customer with its PDF attached and the payment link. Needs the customer's email.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The invoice. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
| `422` | `invoice_incomplete`: no customer email. |
| `502` | `email_failed`: try again, or share `hosted_url`. |
### Void an open invoice {#voidinvoice}
```http
POST /api/v1/invoices/{invoice_id}/void
```
Cancels an open invoice nothing was paid on. Checkouts not yet started for it are closed; a payment already under way that completes is recorded on the invoice's history for you to refund.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `reason` | string or null (max 500 chars) | No | |
```json title="Request"
{
"reason": "string"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The invoice. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
### Mark an invoice paid outside OnCharge {#markinvoicepaid}
```http
POST /api/v1/invoices/{invoice_id}/mark-paid
```
Records what is left to pay as paid by bank transfer, cash or cheque. The payment link stops working.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `note` | string or null (max 500 chars) | No | |
```json title="Request"
{
"note": "string"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The invoice. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
### Issue a credit note {#createcreditnote}
```http
POST /api/v1/invoices/{invoice_id}/credit-notes
```
A numbered credit note (`CN-0001`) against an open or paid invoice. On an open invoice it lowers what is left to pay (a credit for all of it settles the invoice); on a paid one it records a credit, and with `refund` (only for an invoice paid through OnCharge) also refunds it to the customer's payment. The customer is emailed the note.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `amount` | integer (≥ 1) | No | One credit line of this many minor units. |
| `lines` | array of object (≥ 1 items, ≤ 100 items) | No | |
| `lines[].description` | string | Yes | |
| `lines[].quantity` | integer | No | Default `1`. |
| `lines[].unit_amount` | integer (≥ 1) | Yes | |
| `lines[].tax_rate` | number or string | No | |
| `reason` | one of `duplicate`, `fraudulent`, `order_change`, `product_unsatisfactory`, `other` | No | Default `"other"`. |
| `memo` | string or null (max 2000 chars) | No | |
| `refund` | boolean | No | On an invoice paid through OnCharge, also refund the credit to the customer's payment. Default `false`. |
```json title="Request"
{
"amount": 5000,
"reason": "order_change",
"memo": "Two hours fewer than quoted."
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
| `refund` | object | No | |
| `refund.ok` | boolean | No | |
| `refund.status` | string | No | |
| `refund.amount` | integer | No | |
| `refund.message` | string | No | |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string",
"refund": {
"ok": true,
"status": "string",
"amount": 0,
"message": "string"
}
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay. |
| `201` | The credit note (with `refund` when one was asked for). |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `invoice_locked`: a finalized invoice cannot be edited; `invoice_not_draft`, `invalid_transition` or `invoice_partly_paid`: not possible in its status; `payment_in_progress`: a payment for the invoice is under way (try again in a few minutes); `store_inactive`: the store is not taking payments. |
| `422` | `credit_too_large`: more than is left to pay (or, once paid, than the invoice). |
### Download an invoice PDF {#getinvoicepdf}
```http
GET /api/v1/invoices/{invoice_id}/pdf
```
The invoice or credit note as a PDF.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
| Status | Meaning |
|---|---|
| `200` | The PDF. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
### Refund an extra payment {#refundextrainvoicepayment}
```http
POST /api/v1/invoices/{invoice_id}/refund-extra
```
Refunds what a payment paid beyond what the invoice took: a payment for an invoice that was already settled, voided or credited, or the part of one over what was left to pay. Such payments show in the invoice's history as `payment_unapplied` and the merchant is told. Refunded at most once per payment.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `invoice_id` | path | string (uuid) | Yes | The invoice (or credit note) id. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `payment_reference` | string | Yes | The payment's OnCharge reference (`ocpay_…`). |
```json title="Request"
{
"payment_reference": "ocpay_3f2a9c1e0b7d4e6f8a1b2c3d4e5f6a7b"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `invoice`, `credit_note` | Yes | |
| `store_id` | string (uuid) | No | |
| `number` | string or null | No | `INV-0001` (credit notes `CN-0001`), per store, given at finalize; null on a draft. |
| `status` | one of `draft`, `open`, `paid`, `void`, `issued` | Yes | `issued` is a credit note's. |
| `display_status` | one of `draft`, `open`, `overdue`, `paid`, `void`, `issued` | No | |
| `status_label` | string | No | |
| `currency` | string | Yes | |
| `currency_digits` | integer | No | |
| `customer` | object | No | |
| `customer.name` | string or null | No | |
| `customer.email` | string or null | No | |
| `customer.address` | object or null | No | |
| `shipping_address` | object or null | No | |
| `lines` | array of object | Yes | |
| `lines[].description` | string | No | |
| `lines[].quantity` | integer | No | |
| `lines[].unit_amount` | integer | No | |
| `lines[].tax_rate` | number | No | |
| `lines[].amount` | integer | No | |
| `lines[].tax_amount` | integer | No | |
| `lines[].requires_shipping` | boolean | No | |
| `subtotal` | integer | No | |
| `tax` | integer | No | |
| `total` | integer | Yes | |
| `amount_paid` | integer | No | |
| `amount_credited` | integer | No | |
| `amount_remaining` | integer | Yes | |
| `memo` | string or null | No | |
| `footer` | string or null | No | |
| `reply_to` | string or null | No | |
| `days_until_due` | integer | No | |
| `due_at` | string (date-time) or null | No | |
| `send_reminders` | boolean | No | |
| `metadata` | object | No | |
| `hosted_url` | string or null | No | The hosted invoice page the customer pays on (once finalized). |
| `paid_out_of_band` | boolean | No | |
| `payment_reference` | string or null | No | The OnCharge reference (`ocpay_…`) of the payment that paid it. |
| `credit_note_for` | object or null | No | |
| `credit_note_for.id` | string | No | |
| `credit_note_for.number` | string or null | No | |
| `credit_reason` | string or null | No | |
| `source` | one of `dashboard`, `api` | No | |
| `created_at` | string (date-time) | No | |
| `finalized_at` | string or null | No | |
| `sent_at` | string or null | No | |
| `paid_at` | string or null | No | |
| `voided_at` | string or null | No | |
| `actions` | object | No | What can be done now. |
| `events` | array of object | No | History (detail only). |
| `payments` | array of object | No | Payments made for it, by OnCharge reference (detail only). |
| `payments[].payment_reference` | string | No | |
| `payments[].session_id` | string | No | |
| `payments[].amount` | integer | No | |
| `payments[].currency` | string | No | |
| `payments[].status` | string | No | |
| `payments[].rail` | one of `card`, `crypto` | No | |
| `credit_notes` | array of object | No | Credit notes issued against it (detail only). |
| `payment_options` | array of object | No | How the customer can pay it now, and why a rail is off (detail only). |
| `payment_options[].rail` | string | No | |
| `payment_options[].available` | boolean | No | |
| `payment_options[].reason` | string or null | No | |
| `idempotent` | boolean | No | |
| `email_error` | string | No | Finalized, but the email could not be sent. |
```json title="Response"
{
"id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"object": "invoice",
"store_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
"number": "string",
"status": "draft",
"display_status": "draft",
"status_label": "string",
"currency": "string",
"currency_digits": 0,
"customer": {
"name": "string",
"email": "string",
"address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
}
},
"shipping_address": {
"line1": "string",
"line2": "string",
"city": "string",
"state": "string",
"postal_code": "string",
"country": "string"
},
"lines": [
{
"description": "string",
"quantity": 0,
"unit_amount": 0,
"tax_rate": 0,
"amount": 0,
"tax_amount": 0,
"requires_shipping": true
}
],
"subtotal": 0,
"tax": 0,
"total": 0,
"amount_paid": 0,
"amount_credited": 0,
"amount_remaining": 0,
"memo": "string",
"footer": "string",
"reply_to": "string",
"days_until_due": 0,
"due_at": "2026-01-01T00:00:00.000Z",
"send_reminders": true,
"metadata": {},
"hosted_url": "string",
"paid_out_of_band": true,
"payment_reference": "string",
"credit_note_for": {
"id": "string",
"number": "string"
},
"credit_reason": "string",
"source": "dashboard",
"created_at": "2026-01-01T00:00:00.000Z",
"finalized_at": "string",
"sent_at": "string",
"paid_at": "string",
"voided_at": "string",
"actions": {},
"events": [
{}
],
"payments": [
{
"payment_reference": "string",
"session_id": "string",
"amount": 0,
"currency": "string",
"status": "string",
"rail": "card"
}
],
"credit_notes": [
{}
],
"payment_options": [
{
"rail": "string",
"available": true,
"reason": "string"
}
],
"idempotent": true,
"email_error": "string"
}
```
| Status | Meaning |
|---|---|
| `200` | The invoice, with `refund`. |
| `400` | `validation_error` (the message lists each invalid field) or `invalid_json`. |
| `404` | `not_found`: the object does not exist or belongs to another store. |
| `409` | `refund_failed`: the refund could not be made. |
## Subscriptions {#subscriptions}
Recurring billing: plans and add-ons, and subscriptions on them. Each period is an OnCharge invoice charged to the customer's card saved at your store; customers sign up and agree to the recurring charges on OnCharge's own pages. Subscriptions are not available yet: until they are turned on, every endpoint here answers 404 `not_found`.
### List plans {#listplans}
```http
GET /api/v1/plans
```
Your store's plans and add-ons, newest first (at most 200). Archived ones only with `include_archived=true`.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `include_archived` | query | boolean | No | Also list archived plans. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `data` | array of object | Yes | Newest first, at most 200. |
| `data[].id` | string (uuid) | Yes | |
| `data[].object` | one of `plan`, `addon` | Yes | |
| `data[].store_id` | string (uuid) | Yes | |
| `data[].name` | string | Yes | |
| `data[].description` | string or null | Yes | |
| `data[].amount` | integer | Yes | Per period (per unit), minor units. |
| `data[].currency` | string | Yes | |
| `data[].interval` | one of `day`, `week`, `month`, `year` or null | Yes | Null for an add-on. |
| `data[].interval_count` | integer or null | Yes | |
| `data[].interval_text` | string or null | Yes | The period in words: `month`, `3 months`. Null for an add-on. |
| `data[].trial_days` | integer | Yes | |
| `data[].intro` | object or null | Yes | The intro price per period (`amount`) for the first `periods` periods. |
| `data[].requires_shipping` | boolean | Yes | |
| `data[].active` | boolean | Yes | False once archived. |
| `data[].metadata` | object | Yes | |
| `data[].created_at` | string (date-time) | Yes | |
```json title="Response"
{
"data": [
{
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"object": "plan",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"name": "Monthly box",
"description": "A box of our best sellers, every month.",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"interval_text": "month",
"trial_days": 14,
"intro": {
"amount": 1500,
"periods": 2
},
"requires_shipping": true,
"active": true,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z"
}
]
}
```
| Status | Meaning |
|---|---|
| `200` | The plans. |
| `404` | `not_found`: subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
### Create a plan or add-on {#createplan}
```http
POST /api/v1/plans
```
A plan: a price every `interval_count` `interval`s (a period is at most a year), with an optional free trial and intro price. Or an add-on (`kind: "addon"`): billed with the plan it is added to, in the same periods. A plan's price and terms never change once created: create another plan and move subscriptions to it with `change`. A repeat with the same `Idempotency-Key` returns the first plan (200).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `kind` | one of `plan`, `addon` | No | `addon`: no interval, trial or intro of its own; it is billed with the plan it is added to. Default `"plan"`. |
| `name` | string (min 1 chars, max 120 chars) | Yes | |
| `description` | string or null (max 1000 chars) | No | |
| `amount` | integer (≥ 1, ≤ 99999999) | Yes | Per period (per unit), minor units. |
| `currency` | string | No | ISO 4217. Add-ons must be in their plan's currency. Default `"USD"`. |
| `interval` | one of `day`, `week`, `month`, `year` | No | Required for a plan. |
| `interval_count` | integer (≥ 1, ≤ 365) | No | Intervals per period, up to one year: at most 365 days, 52 weeks, 12 months or 1 year. Default `1`. |
| `trial_days` | integer (≥ 0, ≤ 365) | No | A free trial before the first charge: 0 (none) or at least 7 days, so the customer can be reminded 7 days before it ends. Plans only. Default `0`. |
| `intro` | object or null | No | A lower price for the first periods: `{ "amount": 1500, "periods": 2 }`. Plans only. |
| `requires_shipping` | boolean | No | Each period ships, needs a shipping address and is paid out after carrier-confirmed delivery. On a store that ships physical goods every period ships anyway. Default `false`. |
| `metadata` | object | No | Your own key-value pairs: at most 20 keys of letters, digits, `_`, `.` and `-` (up to 40 characters), each value up to 500 characters. |
```json title="Request"
{
"name": "Monthly box",
"description": "A box of our best sellers, every month.",
"amount": 3000,
"currency": "USD",
"interval": "month",
"trial_days": 14,
"intro": {
"amount": 1500,
"periods": 2
},
"requires_shipping": true
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `plan`, `addon` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `name` | string | Yes | |
| `description` | string or null | Yes | |
| `amount` | integer | Yes | Per period (per unit), minor units. |
| `currency` | string | Yes | |
| `interval` | one of `day`, `week`, `month`, `year` or null | Yes | Null for an add-on. |
| `interval_count` | integer or null | Yes | |
| `interval_text` | string or null | Yes | The period in words: `month`, `3 months`. Null for an add-on. |
| `trial_days` | integer | Yes | |
| `intro` | object or null | Yes | The intro price per period (`amount`) for the first `periods` periods. |
| `requires_shipping` | boolean | Yes | |
| `active` | boolean | Yes | False once archived. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"object": "plan",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"name": "Monthly box",
"description": "A box of our best sellers, every month.",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"interval_text": "month",
"trial_days": 14,
"intro": {
"amount": 1500,
"periods": 2
},
"requires_shipping": true,
"active": true,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay. |
| `201` | Created. |
| `400` | `invalid_request`: the message names the first invalid field (an intro price must be lower than the plan's price); `invalid_json`: the body is not JSON; `invalid_idempotency_key`: the `Idempotency-Key` is longer than 255 characters or has control characters. |
| `404` | `store_not_found`; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
### Retrieve a plan {#getplan}
```http
GET /api/v1/plans/{plan_id}
```
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `plan_id` | path | string (uuid) | Yes | A plan or add-on of your store. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `plan`, `addon` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `name` | string | Yes | |
| `description` | string or null | Yes | |
| `amount` | integer | Yes | Per period (per unit), minor units. |
| `currency` | string | Yes | |
| `interval` | one of `day`, `week`, `month`, `year` or null | Yes | Null for an add-on. |
| `interval_count` | integer or null | Yes | |
| `interval_text` | string or null | Yes | The period in words: `month`, `3 months`. Null for an add-on. |
| `trial_days` | integer | Yes | |
| `intro` | object or null | Yes | The intro price per period (`amount`) for the first `periods` periods. |
| `requires_shipping` | boolean | Yes | |
| `active` | boolean | Yes | False once archived. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"object": "plan",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"name": "Monthly box",
"description": "A box of our best sellers, every month.",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"interval_text": "month",
"trial_days": 14,
"intro": {
"amount": 1500,
"periods": 2
},
"requires_shipping": true,
"active": true,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | The plan or add-on. |
| `404` | `plan_not_found`: no such plan in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
### Update or archive a plan {#updateplan}
```http
PATCH /api/v1/plans/{plan_id}
```
Its name, description or metadata, or archive it with `active: false` (subscriptions already on it go on; it takes no new ones). The price and terms cannot change. Signed like any request, with `PATCH` as the method.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `plan_id` | path | string (uuid) | Yes | A plan or add-on of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string (min 1 chars, max 120 chars) | No | |
| `description` | string or null (max 1000 chars) | No | |
| `active` | boolean | No | `false` archives the plan: it takes no new subscriptions, and those already on it go on. `true` brings it back. |
| `metadata` | object | No | Your own key-value pairs: at most 20 keys of letters, digits, `_`, `.` and `-` (up to 40 characters), each value up to 500 characters. |
```json title="Request"
{
"active": false
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | one of `plan`, `addon` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `name` | string | Yes | |
| `description` | string or null | Yes | |
| `amount` | integer | Yes | Per period (per unit), minor units. |
| `currency` | string | Yes | |
| `interval` | one of `day`, `week`, `month`, `year` or null | Yes | Null for an add-on. |
| `interval_count` | integer or null | Yes | |
| `interval_text` | string or null | Yes | The period in words: `month`, `3 months`. Null for an add-on. |
| `trial_days` | integer | Yes | |
| `intro` | object or null | Yes | The intro price per period (`amount`) for the first `periods` periods. |
| `requires_shipping` | boolean | Yes | |
| `active` | boolean | Yes | False once archived. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"object": "plan",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"name": "Monthly box",
"description": "A box of our best sellers, every month.",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1,
"interval_text": "month",
"trial_days": 14,
"intro": {
"amount": 1500,
"periods": 2
},
"requires_shipping": true,
"active": true,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z"
}
```
| Status | Meaning |
|---|---|
| `200` | The plan. |
| `400` | `invalid_request`: the message names the first invalid field; `invalid_json`: the body is not JSON. |
| `404` | `plan_not_found`: no such plan in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
### Create a sign-up link for a plan {#createplanpaymentlink}
```http
POST /api/v1/plans/{plan_id}/payment-link
```
A payment link (https://app.oncharge.io/l/) that signs shoppers up to the plan: they enter their email (and their shipping address if the plan ships), then agree to the recurring terms and enter a card on OnCharge's sign-up page. It is one of your payment links: it appears with them, and you turn it off the same way (`POST /api/v1/payment-links/{link_id}/deactivate`).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `plan_id` | path | string (uuid) | Yes | A plan or add-on of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `title` | string (min 1 chars, max 120 chars) | No | What the link page shows. Default: the plan's name. |
```json title="Request"
{
"title": "Join the Monthly box"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `code` | string | Yes | |
| `url` | string | Yes | The link to share: https://app.oncharge.io/l/. |
| `plan_id` | string (uuid) | Yes | |
```json title="Response"
{
"id": "5f0c9d4e-2a1b-4c3d-9e8f-7a6b5c4d3e2f",
"code": "k7Hq2mNpR4sT",
"url": "https://app.oncharge.io/l/k7Hq2mNpR4sT",
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f"
}
```
| Status | Meaning |
|---|---|
| `201` | The link. |
| `400` | `invalid_request`: the message names the first invalid field; `invalid_json`: the body is not JSON. |
| `404` | `plan_not_found`: no such plan (add-ons have no links); `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `plan_inactive`: the plan is archived. |
### List subscriptions {#listsubscriptions}
```http
GET /api/v1/subscriptions
```
Your store's subscriptions, newest first.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `status` | query | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | No | Only this status. |
| `customer_id` | query | string (uuid) | No | Only this customer's. |
| `limit` | query | integer | No | |
| `starting_after` | query | string (uuid) | No | The last `id` of the previous page. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `data` | array of object | Yes | |
| `data[].id` | string (uuid) | Yes | |
| `data[].object` | `"subscription"` | Yes | |
| `data[].store_id` | string (uuid) | Yes | |
| `data[].customer_id` | string (uuid) | Yes | |
| `data[].customer` | object or null | Yes | |
| `data[].customer.email` | string or null | No | |
| `data[].customer.name` | string or null | No | |
| `data[].status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `data[].status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `data[].plan` | object | Yes | |
| `data[].plan.id` | string (uuid) | Yes | |
| `data[].plan.name` | string | No | |
| `data[].plan.amount` | integer | No | |
| `data[].plan.currency` | string | No | |
| `data[].plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `data[].plan.interval_count` | integer or null | No | |
| `data[].quantity` | integer | Yes | |
| `data[].addons` | array of object | Yes | |
| `data[].addons[].plan_id` | string (uuid) | No | |
| `data[].addons[].name` | string or null | No | |
| `data[].addons[].amount` | integer or null | No | |
| `data[].addons[].quantity` | integer | No | |
| `data[].intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `data[].payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `data[].trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `data[].current_period` | object or null | Yes | |
| `data[].current_period.index` | integer | No | 0 for the first period. |
| `data[].current_period.start` | string (date-time) or null | No | |
| `data[].current_period.end` | string (date-time) or null | No | |
| `data[].current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `data[].next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `data[].credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `data[].pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `data[].pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `data[].pending_change.plan_id` | string (uuid) | No | |
| `data[].pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `data[].pending_change.quantity` | integer | No | |
| `data[].pending_change.addons` | array of object | No | |
| `data[].cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `data[].canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `data[].ended_at` | string (date-time) or null | Yes | |
| `data[].cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `data[].pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `data[].pause.at_period_end` | boolean | No | |
| `data[].pause.paused_at` | string (date-time) or null | No | |
| `data[].pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `data[].pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `data[].shipping` | object or null | Yes | |
| `data[].shipping.name` | string or null | No | |
| `data[].shipping.address` | object | No | |
| `data[].source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `data[].payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `data[].sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `data[].metadata` | object | Yes | |
| `data[].created_at` | string (date-time) | Yes | |
| `has_more` | boolean | Yes | More follow: pass the last `id` as `starting_after`. |
```json title="Response"
{
"data": [
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null
}
],
"has_more": true
}
```
| Status | Meaning |
|---|---|
| `200` | A page of subscriptions. |
| `404` | `not_found`: subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
### Start a subscription for a customer {#createsubscription}
```http
POST /api/v1/subscriptions
```
For an existing customer of your store. It starts as `incomplete`: OnCharge emails the customer a link to its sign-up page, where they read the terms, agree to the recurring charges and choose one of their saved cards or add one. It starts when they agree (the trial starts, or the first period is charged). The link is never returned to you, and it works for 7 days; after that the subscription is `incomplete_expired`. A repeat with the same `Idempotency-Key` returns the first subscription (200).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `customer_id` | string (uuid) | Yes | An existing customer of your store. They need an email address: OnCharge emails them the link to confirm. |
| `plan_id` | string (uuid) | Yes | An active plan of your store. |
| `quantity` | integer (≥ 1, ≤ 1000) | No | Default `1`. |
| `addons` | array of object (≤ 20 items) | No | Each add-on listed once. |
| `addons[].plan_id` | string (uuid) | Yes | An add-on of your store (`kind: "addon"`), in the plan's currency. |
| `addons[].quantity` | integer (≥ 1, ≤ 1000) | No | Default `1`. |
| `shipping` | object | No | Required when the subscription ships. |
| `shipping.name` | string (min 1 chars, max 200 chars) | Yes | |
| `shipping.line1` | string (min 1 chars, max 300 chars) | Yes | |
| `shipping.line2` | string or null (max 300 chars) | No | |
| `shipping.city` | string (min 1 chars, max 120 chars) | Yes | |
| `shipping.state` | string or null (max 120 chars) | No | |
| `shipping.postal_code` | string (min 1 chars, max 20 chars) | Yes | |
| `shipping.country` | string | Yes | Two-letter code (`US`). |
| `metadata` | object | No | Your own key-value pairs: at most 20 keys of letters, digits, `_`, `.` and `-` (up to 40 characters), each value up to 500 characters. |
```json title="Request"
{
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"quantity": 1,
"addons": [
{
"plan_id": "d2e3f4a5-b6c7-4d8e-9f0a-1b2c3d4e5f6a",
"quantity": 1
}
],
"shipping": {
"name": "Ada Lovelace",
"line1": "1 Main St",
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay. |
| `201` | Created, waiting for the customer (`incomplete`). |
| `400` | `invalid_request`: the message names the first invalid field (also an add-on listed twice, or in another currency); `invalid_json`: the body is not JSON; `invalid_idempotency_key`: the `Idempotency-Key` is longer than 255 characters or has control characters. |
| `404` | `customer_not_found`, `plan_not_found` or `addon_not_found`; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `customer_email_required`: the customer has no email address; `plan_inactive`: the plan (or an add-on) is archived; `store_inactive`: the store is not taking payments; `subscriptions_unavailable`: the store has no card payments set up for saved cards; `idempotency_conflict`: the `Idempotency-Key` was used for another customer or plan. |
| `422` | `shipping_address_required`: the subscription ships each period: send `shipping`. |
### Create a hosted sign-up page {#createsubscriptioncheckout}
```http
POST /api/v1/subscriptions/checkout
```
A sign-up page on OnCharge for one customer: the answer is the subscription (`incomplete`) with its `url`. Send the customer there; they read the terms, agree to the recurring charges and enter a card, and the subscription starts (the trial starts, or the first period is charged). The page works for 24 hours and never offers the customer's saved cards. A repeat with the same `Idempotency-Key` returns the first subscription and its page (200).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | No | A unique key (up to 255 characters is safe) that makes retries of this request safe. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `plan_id` | string (uuid) | Yes | An active plan of your store. |
| `quantity` | integer (≥ 1, ≤ 1000) | No | Default `1`. |
| `addons` | array of object (≤ 20 items) | No | Each add-on listed once. |
| `addons[].plan_id` | string (uuid) | Yes | An add-on of your store (`kind: "addon"`), in the plan's currency. |
| `addons[].quantity` | integer (≥ 1, ≤ 1000) | No | Default `1`. |
| `customer_id` | string (uuid) | No | An existing customer of your store. |
| `customer_email` | string (email) (max 254 chars) | No | The customer is found by email, or added to your store. |
| `customer_name` | string (min 1 chars, max 200 chars) | No | Saved on the customer if they have no name yet. |
| `shipping` | object | No | Required when the subscription ships. |
| `shipping.name` | string (min 1 chars, max 200 chars) | Yes | |
| `shipping.line1` | string (min 1 chars, max 300 chars) | Yes | |
| `shipping.line2` | string or null (max 300 chars) | No | |
| `shipping.city` | string (min 1 chars, max 120 chars) | Yes | |
| `shipping.state` | string or null (max 120 chars) | No | |
| `shipping.postal_code` | string (min 1 chars, max 20 chars) | Yes | |
| `shipping.country` | string | Yes | Two-letter code (`US`). |
| `success_url` | string (uri) (max 2048 chars) | No | An `https` page the customer goes to after signing up. Kept in the subscription's `metadata` as `success_url`. |
| `metadata` | object | No | Your own key-value pairs: at most 20 keys of letters, digits, `_`, `.` and `-` (up to 40 characters), each value up to 500 characters. |
```json title="Request"
{
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"customer_email": "ada@example.com",
"customer_name": "Ada Lovelace",
"shipping": {
"name": "Ada Lovelace",
"line1": "1 Main St",
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
},
"success_url": "https://shop.example.com/welcome"
}
```
**Response** `201`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
| `url` | string | Yes | The customer's sign-up page on OnCharge. It works until `sign_up_expires_at` (24 hours). It never offers the customer's saved cards. |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "incomplete",
"status_text": "Waiting for customer",
"payment_method": null,
"trial_end": null,
"current_period": null,
"next_billing_at": null,
"source": "checkout",
"sign_up_expires_at": "2026-12-02T00:00:00.000Z",
"url": "https://app.oncharge.io/s/subscribe/7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b?token=ocs_…"
}
```
| Status | Meaning |
|---|---|
| `200` | Idempotent replay. |
| `201` | Created: send the customer to `url`. |
| `400` | `invalid_request`: the message names the first invalid field (also neither `customer_id` nor `customer_email`, or an add-on listed twice or in another currency); `invalid_json`: the body is not JSON; `invalid_idempotency_key`: the `Idempotency-Key` is longer than 255 characters or has control characters. |
| `404` | `customer_not_found`, `plan_not_found` or `addon_not_found`; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `plan_inactive`: the plan (or an add-on) is archived; `store_inactive`: the store is not taking payments; `subscriptions_unavailable`: the store has no card payments set up for saved cards; `idempotency_conflict`: the `Idempotency-Key` was used for another customer or plan. |
| `422` | `shipping_address_required`: the subscription ships each period: send `shipping`. |
### Retrieve a subscription {#getsubscription}
```http
GET /api/v1/subscriptions/{subscription_id}
```
The subscription with every bill (each period and prorated plan change, its invoice, attempts, failure and payment reference) and its history.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
| `billings` | array of object | Yes | Every bill, newest first. |
| `billings[].id` | string (uuid) | Yes | |
| `billings[].object` | `"subscription_billing"` | Yes | |
| `billings[].subscription_id` | string (uuid) | Yes | |
| `billings[].reason` | one of `period`, `proration` | Yes | `proration`: the prorated charge of a plan change applied now. |
| `billings[].period_index` | integer | Yes | 0 for the first period. |
| `billings[].period_start` | string (date-time) | Yes | |
| `billings[].period_end` | string (date-time) | Yes | |
| `billings[].lines` | array of object | Yes | |
| `billings[].lines[].description` | string | No | |
| `billings[].lines[].quantity` | integer | No | |
| `billings[].lines[].unit_amount` | integer | No | |
| `billings[].lines[].requires_shipping` | boolean | No | |
| `billings[].subtotal` | integer | Yes | |
| `billings[].credit_applied` | integer | Yes | Credit from earlier downgrades taken off this bill. |
| `billings[].amount_due` | integer | Yes | |
| `billings[].ships` | boolean | Yes | This period's order ships: it is paid out after carrier-confirmed delivery. |
| `billings[].status` | one of `open`, `paid`, `uncollectible`, `void` | Yes | |
| `billings[].invoice` | object or null | Yes | |
| `billings[].invoice.id` | string (uuid) | No | |
| `billings[].invoice.number` | string or null | No | `INV-0042`. |
| `billings[].attempts` | integer | Yes | Charge attempts so far. |
| `billings[].next_attempt_at` | string (date-time) or null | Yes | While open: when it is charged again; null when it waits for the customer. |
| `billings[].failure` | object or null | Yes | Why the last charge failed, while unpaid. |
| `billings[].failure.reason` | one of `declined`, `authentication_required`, `unusable_card`, `error`, `store_unavailable`, `store_limit` | No | |
| `billings[].failure.message` | string | No | What happened and what OnCharge does next, in plain words. |
| `billings[].failure.waits_for_customer` | boolean | No | No automatic retry: the customer has to confirm the payment with their bank or add another card. |
| `billings[].paid_at` | string (date-time) or null | Yes | |
| `billings[].payment_reference` | string or null | Yes | OnCharge's reference for the payment that paid it (`ocpay_…`). |
| `billings[].created_at` | string (date-time) | Yes | |
| `history` | array of object | Yes | What happened, newest first (at most 100). |
| `history[].kind` | string | No | |
| `history[].actor` | one of `merchant`, `api`, `customer`, `system` | No | |
| `history[].data` | object | No | |
| `history[].created_at` | string (date-time) | No | |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null,
"billings": [
{
"id": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"object": "subscription_billing",
"subscription_id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"reason": "period",
"period_index": 0,
"period_start": "2026-12-15T00:00:00.000Z",
"period_end": "2027-01-15T00:00:00.000Z",
"lines": [
{
"description": "Monthly box (introductory price)",
"quantity": 1,
"unit_amount": 1500,
"requires_shipping": true
}
],
"subtotal": 1500,
"credit_applied": 0,
"amount_due": 1500,
"ships": true,
"status": "paid",
"invoice": {
"id": "4d5e6f7a-8b9c-4d0e-8f1a-2b3c4d5e6f7a",
"number": "INV-0042"
},
"attempts": 1,
"next_attempt_at": null,
"failure": null,
"paid_at": "2026-12-15T00:05:00.000Z",
"payment_reference": "ocpay_8f14e45fceea467a95752c3b8e1f0b6d",
"created_at": "2026-12-15T00:00:00.000Z"
}
],
"history": [
{
"kind": "billing_paid",
"actor": "system",
"data": {
"amount": 1500,
"period_index": 0,
"reason": "period"
},
"created_at": "2026-12-15T00:05:00.000Z"
},
{
"kind": "consent_granted",
"actor": "customer",
"data": {
"version": "2026-12-01-draft"
},
"created_at": "2026-12-01T00:10:00.000Z"
},
{
"kind": "created",
"actor": "system",
"data": {
"source": "api",
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"quantity": 1
},
"created_at": "2026-12-01T00:00:00.000Z"
}
]
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription. |
| `404` | `not_found`: no such subscription in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
### Update a subscription {#updatesubscription}
```http
PATCH /api/v1/subscriptions/{subscription_id}
```
Change where it ships, replace its metadata, or ask the customer to switch to another of their saved cards at your store. Only the customer changes the card: with `payment_method_id` they are emailed a link to switch to that card on their subscription page (once an hour at most), and the answer is `202` with `card_change`. If that email cannot be sent, nothing in the request is saved. Nothing changes, and nothing is charged to that card, until the customer switches and agrees to the charges on it. Signed like any request, with `PATCH` as the method.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `payment_method_id` | string (uuid) | No | Another active saved card of the same customer at your store. The customer is emailed a link to switch to it themselves (`202`); the subscription keeps its card, and nothing is charged to this one, until they do. Not on an `incomplete` subscription: the customer chooses the card when they sign up. |
| `shipping` | object | No | Where the next periods ship. |
| `shipping.name` | string (min 1 chars, max 200 chars) | Yes | |
| `shipping.line1` | string (min 1 chars, max 300 chars) | Yes | |
| `shipping.line2` | string or null (max 300 chars) | No | |
| `shipping.city` | string (min 1 chars, max 120 chars) | Yes | |
| `shipping.state` | string or null (max 120 chars) | No | |
| `shipping.postal_code` | string (min 1 chars, max 20 chars) | Yes | |
| `shipping.country` | string | Yes | Two-letter code (`US`). |
| `metadata` | object | No | Replaces the metadata. |
```json title="Request"
{
"payment_method_id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription. |
| `202` | With `payment_method_id`: the customer was emailed a link to switch to that card (`card_change.status: "customer_asked"`, with the card's brand and last four digits). The subscription keeps its card until they do; any shipping or metadata change in the same request is saved. |
| `400` | `invalid_request`: the message names the first invalid field; `invalid_json`: the body is not JSON. |
| `404` | `not_found`: no such subscription; `payment_method_not_found`: not an active saved card of this customer; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `subscription_ended`: it has ended; `not_started`: the customer chooses the card when they sign up; `customer_email_required`: the customer has no email address to ask them to switch cards; `conflict`: the subscription changed meanwhile (try again). A `429 too_many_requests` means you asked this customer to switch cards less than an hour ago; a `502 customer_not_emailed` means the email could not be sent and nothing in the request was saved: try again. |
### Cancel a subscription {#cancelsubscription}
```http
POST /api/v1/subscriptions/{subscription_id}/cancel
```
By default an active or trialing subscription ends when its current period (or trial) ends: nothing more is charged, and `subscription.canceled` follows then. With `at_period_end: false`, or for any other status, it ends now: anything unpaid is voided. The customer is emailed. To keep a subscription whose cancellation is waiting, `resume` it (not when the customer cancelled it).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `at_period_end` | boolean | No | `true`: an active or trialing subscription ends when its current period (or trial) ends; any other status ends now. `false`: it ends now and anything unpaid is voided. Default `true`. |
```json title="Request"
{
"at_period_end": true
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription: `cancel_at_period_end: true`, or `canceled`. |
| `400` | `invalid_request`: the message names the first invalid field; `invalid_json`: the body is not JSON. |
| `404` | `not_found`: no such subscription in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `subscription_ended`: it has already ended; `payment_in_progress`: a payment for it is being collected (try again in a minute); `conflict`: the subscription changed meanwhile (try again). |
### Pause a subscription {#pausesubscription}
```http
POST /api/v1/subscriptions/{subscription_id}/pause
```
From the end of the current period (nothing already paid is lost), for `periods` periods, until `resume_at`, or until resumed. While paused nothing is charged or shipped. Only an active or trialing subscription can be paused; a past-due one must be paid first.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `periods` | integer (≥ 1, ≤ 12) | No | Pause for this many periods. |
| `resume_at` | string (date-time) | No | Resume then: after the end of the current period. |
```json title="Request"
{
"periods": 2
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription, with `pause.at_period_end: true`. |
| `400` | `invalid_request`: the message names the first invalid field (also both `periods` and `resume_at`, or a `resume_at` not after the end of the current period); `invalid_json`: the body is not JSON. |
| `404` | `not_found`: no such subscription in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `payment_required`: it is past due; `not_pausable`: it is not active or trialing; `cancel_scheduled`: it ends at the period's end; `conflict`: the subscription changed meanwhile (try again). |
### Resume a subscription {#resumesubscription}
```http
POST /api/v1/subscriptions/{subscription_id}/resume
```
A paused subscription starts again now: a new period begins and is charged at once. On a subscription with a pause or cancellation waiting for the period's end, the pause or cancellation is called off. A cancellation the customer asked for is theirs to undo, by subscribing again.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription. |
| `404` | `not_found`: no such subscription in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `not_paused`: nothing to resume; `canceled_by_customer`: the customer cancelled it; `conflict`: the subscription changed meanwhile (try again). |
### Change the plan, quantity or add-ons {#changesubscription}
```http
POST /api/v1/subscriptions/{subscription_id}/change
```
A change that **raises the price** the customer pays is never applied at once: it waits in `pending_change` (with `increase`) for the first period that starts at least 7 days after the customer is emailed a notice, which goes 7 to 30 days before the new price is first charged. Asking for `proration: "now"` on an increase is refused (`409 price_increase_needs_notice`); leave `proration` out (or send `"next_period"`) to schedule it. Any other change applies at once by default: the rest of the current period is prorated and the difference for the time left (to the second, rounded half up) is credited to the next bills. With `"next_period"` it applies at the renewal (`pending_change`). A shipped subscription (each period is one order) and a plan with another interval change at the next period only; a paused subscription always does. The customer is emailed the new price.
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
**Request body** (`application/json`)
| Field | Type | Required | Description |
|---|---|---|---|
| `plan_id` | string (uuid) | No | Another plan of your store, in the same currency. A new plan drops any intro price left. |
| `quantity` | integer (≥ 1, ≤ 1000) | No | |
| `addons` | array of object (≤ 20 items) | No | Replaces every add-on (`[]` removes them). |
| `addons[].plan_id` | string (uuid) | Yes | An add-on of your store (`kind: "addon"`), in the plan's currency. |
| `addons[].quantity` | integer (≥ 1, ≤ 1000) | No | Default `1`. |
| `proration` | one of `now`, `next_period` | No | `now`: applied at once; the rest of the period is prorated (a lower price is a credit on the next bills). A change that raises the price is never applied now (`409 price_increase_needs_notice`). `next_period`: applied at the renewal, or for a price increase from the first period at least 7 days after the customer's emailed notice. Left out: `now`, unless the change raises the price (then scheduled with the notice). A shipped subscription, or a plan with another interval, changes at the next period only (`409 change_at_next_period` otherwise); a paused one always does. |
```json title="Request"
{
"plan_id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"quantity": 2,
"proration": "next_period"
}
```
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
| `proration` | object | No | Only for a change applied now. |
| `proration.charge` | integer | No | Charged now for the rest of the period, minor units. Always 0 since a price increase never applies at once (kept for compatibility). |
| `proration.credit` | integer | No | Credited to the next bills (a downgrade), minor units. |
| `proration.outcome` | one of `paid`, `processing`, `failed`, `resume_later`, `not_charged`, or `null` | No | How the charge went; null when nothing was charged. |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 2,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 4500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null,
"proration": {
"charge": 1452,
"credit": 0,
"outcome": "paid"
}
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription; for a change applied now, with `proration`. |
| `400` | `invalid_request`: the message names the first invalid field (also nothing to change, or an add-on listed twice or in another currency); `currency_mismatch`: the new plan is in another currency; `invalid_json`: the body is not JSON. |
| `404` | `not_found`, `plan_not_found` or `addon_not_found`; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `not_changeable`: it is not active, trialing or paused (a past-due subscription must be paid first); `price_increase_needs_notice`: the change raises the price, so it cannot apply now: leave `proration` out or use `"next_period"`; `change_at_next_period`: it ships, or the new plan has another interval: use `proration: "next_period"`; `plan_inactive`: the new plan or an add-on is archived; `store_inactive`; `conflict`: the subscription changed meanwhile (try again). |
| `422` | `shipping_address_required`: the new plan ships and the subscription has no shipping address: set one with PATCH first. |
### Retry a past-due payment now {#retrysubscription}
```http
POST /api/v1/subscriptions/{subscription_id}/retry
```
Charges a past-due subscription's unpaid bills to its card now, instead of waiting for the next scheduled retry (for example after the customer told you they fixed their card).
| Parameter | In | Type | Required | Description |
|---|---|---|---|---|
| `subscription_id` | path | string (uuid) | Yes | A subscription of your store. |
No request body. Sign it as an empty body.
**Response** `200`
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string (uuid) | Yes | |
| `object` | `"subscription"` | Yes | |
| `store_id` | string (uuid) | Yes | |
| `customer_id` | string (uuid) | Yes | |
| `customer` | object or null | Yes | |
| `customer.email` | string or null | No | |
| `customer.name` | string or null | No | |
| `status` | one of `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `paused`, `canceled` | Yes | `incomplete`: waiting for the customer to sign up. `incomplete_expired`: they did not in time. `trialing`: in its free trial. `active`: paid up. `past_due`: a payment failed and is being retried. `paused`: nothing is charged or shipped. `canceled`: ended. |
| `status_text` | string | Yes | The status in plain words (`Waiting for customer`, `Past due`, …). |
| `plan` | object | Yes | |
| `plan.id` | string (uuid) | Yes | |
| `plan.name` | string | No | |
| `plan.amount` | integer | No | |
| `plan.currency` | string | No | |
| `plan.interval` | one of `day`, `week`, `month`, `year` or null | No | |
| `plan.interval_count` | integer or null | No | |
| `quantity` | integer | Yes | |
| `addons` | array of object | Yes | |
| `addons[].plan_id` | string (uuid) | No | |
| `addons[].name` | string or null | No | |
| `addons[].amount` | integer or null | No | |
| `addons[].quantity` | integer | No | |
| `intro` | object or null | Yes | The intro price this subscription has, taken from its plan when it was created. |
| `payment_method` | object or null | Yes | The saved card it is charged to. Null until the customer signs up. |
| `trial_end` | string (date-time) or null | Yes | When the free trial ends (the first charge). |
| `current_period` | object or null | Yes | |
| `current_period.index` | integer | No | 0 for the first period. |
| `current_period.start` | string (date-time) or null | No | |
| `current_period.end` | string (date-time) or null | No | |
| `current_period.amount` | integer or null | No | What this period was billed, minor units. |
| `next_billing_at` | string (date-time) or null | Yes | When it is charged next, or resumes; null once ended. |
| `credit_balance` | integer | Yes | Credit from downgrades, taken off the next bills (minor units). |
| `pending_change` | object or null | Yes | A change that applies at the next period (a price increase: from `increase.effective_at`). |
| `pending_change.change_id` | string (uuid) | No | This change: its notice is for it alone; a newer change is always told again. |
| `pending_change.plan_id` | string (uuid) | No | |
| `pending_change.increase` | object or null | No | Set when the change raises the price: a bigger charge, or a higher price per day when the interval changes. It applies only to the period starting `effective_at`, with the customer's notice confirmed sent 7 to 30 days before that date. Its date follows the subscription's real schedule (after a pause, from the day it resumes); when that schedule moves, the date moves (`version` goes up) and the customer is told again. |
| `pending_change.increase.from` | integer | No | The price per period before, minor units (per `from_every`). |
| `pending_change.increase.to` | integer | No | The price per period after, minor units (per `to_every`). |
| `pending_change.increase.from_every` | string | No | The period before, in words: `every month`. |
| `pending_change.increase.to_every` | string | No | The period after, in words: `every week`. |
| `pending_change.increase.currency` | string | No | |
| `pending_change.increase.effective_index` | integer or null | No | The period it applies from (0 is the first); null while unknown (paused with no end date). |
| `pending_change.increase.effective_at` | string (date-time) or null | No | When that period starts: the first charge at the new price; null while unknown. |
| `pending_change.increase.notice_sent_at` | string (date-time) or null | No | When the email service accepted the notice; null until then (it goes 30 days before `effective_at`, and is tried again if it did not go). |
| `pending_change.increase.version` | integer | No | Which notice: goes up each time the date moves, so a notice for an earlier date never counts again. |
| `pending_change.quantity` | integer | No | |
| `pending_change.addons` | array of object | No | |
| `pending_change.addons[].plan_id` | string (uuid) | No | |
| `pending_change.addons[].quantity` | integer | No | |
| `cancel_at_period_end` | boolean | Yes | It ends when the current period ends. |
| `canceled_at` | string (date-time) or null | Yes | When it was cancelled (for a cancellation at the period's end, when it was asked for). |
| `ended_at` | string (date-time) or null | Yes | |
| `cancel_reason` | one of `merchant`, `customer`, `api`, `dunning`, `store_closed`, `reminder_undeliverable`, or `null` | Yes | `dunning`: its payment failed on every retry. `reminder_undeliverable`: the reminder required 7 days before the first charge after a trial could not be emailed for 72 hours, so it ended without being charged. |
| `pause` | object or null | Yes | A pause waiting for the period's end (`at_period_end: true`), or under way. |
| `pause.at_period_end` | boolean | No | |
| `pause.paused_at` | string (date-time) or null | No | |
| `pause.resume_at` | string (date-time) or null | No | When it starts again by itself; null: when you (or the customer) resume it. |
| `pause.reason` | one of `merchant`, `customer`, `api`, `dunning`, or `null` | No | |
| `shipping` | object or null | Yes | |
| `shipping.name` | string or null | No | |
| `shipping.address` | object | No | |
| `shipping.address.line1` | string | No | |
| `shipping.address.line2` | string or null | No | |
| `shipping.address.city` | string | No | |
| `shipping.address.state` | string or null | No | |
| `shipping.address.postal_code` | string | No | |
| `shipping.address.country` | string | No | |
| `source` | one of `dashboard`, `api`, `payment_link`, `checkout` | Yes | How it was started. |
| `payment_link_id` | string (uuid) or null | Yes | The plan payment link the customer signed up through. |
| `sign_up_expires_at` | string (date-time) or null | Yes | While `incomplete`: when the sign-up link stops working. |
| `metadata` | object | Yes | |
| `created_at` | string (date-time) | Yes | |
| `retry` | array of one of `paid`, `processing`, `failed`, `resume_later`, `not_charged` | Yes | How each unpaid bill's charge went, oldest first. |
```json title="Response"
{
"id": "7e2f9a1c-3b4d-4e5f-8a6b-9c0d1e2f3a4b",
"object": "subscription",
"store_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
"customer_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
"customer": {
"email": "ada@example.com",
"name": "Ada Lovelace"
},
"plan": {
"id": "c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f",
"name": "Monthly box",
"amount": 3000,
"currency": "USD",
"interval": "month",
"interval_count": 1
},
"quantity": 1,
"addons": [],
"intro": {
"amount": 1500,
"periods": 2
},
"credit_balance": 0,
"pending_change": null,
"cancel_at_period_end": false,
"canceled_at": null,
"ended_at": null,
"cancel_reason": null,
"pause": null,
"shipping": {
"name": "Ada Lovelace",
"address": {
"line1": "1 Main St",
"line2": null,
"city": "Austin",
"state": "TX",
"postal_code": "78701",
"country": "US"
}
},
"payment_link_id": null,
"metadata": {},
"created_at": "2026-12-01T00:00:00.000Z",
"status": "active",
"status_text": "Active",
"payment_method": {
"id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"object": "payment_method",
"type": "card",
"brand": "Visa",
"last4": "4242",
"exp_month": 12,
"exp_year": 2029,
"funding": "credit",
"country": "US",
"wallet": null,
"is_default": true,
"status": "active",
"expired": false,
"saved_via": "save_card_page",
"created_at": "2026-12-01T00:00:00.000Z",
"last_used_at": "2026-12-15T00:00:00.000Z",
"updated_by_card_network_at": null,
"removed_at": null
},
"trial_end": "2026-12-15T00:00:00.000Z",
"current_period": {
"index": 0,
"start": "2026-12-15T00:00:00.000Z",
"end": "2027-01-15T00:00:00.000Z",
"amount": 1500
},
"next_billing_at": "2027-01-15T00:00:00.000Z",
"source": "api",
"sign_up_expires_at": null,
"retry": [
"paid"
]
}
```
| Status | Meaning |
|---|---|
| `200` | The subscription, with how each charge went. |
| `404` | `not_found`: no such subscription in your store; `not_found` while subscriptions are not available yet (every subscription endpoint answers 404 until they are turned on). |
| `409` | `not_past_due`: only a past-due subscription is retried. |
## Webhooks {#webhooks}
OnCharge sends these events to your webhook endpoint. Verification and handling: [Webhooks](https://oncharge.io/docs/webhooks).
| Event | When |
|---|---|
| `payment.pending` | The shopper started paying but the money has not arrived yet. Do not ship yet. On a gateway wallet, a payment seen on the chain and not confirmed yet. |
| `payment.authorized` | The card was approved and the money is held for you. It is collected next. |
| `payment.captured` | The shopper paid. Mark the order as paid and ship it. For crypto and Card to Crypto paid to your own wallet, the payout is already on its way to it. |
| `payment.under_review` | A payment to your wallet arrived but does not match the order (for example a different amount), so check it before you ship. |
| `payment.refused` | The payment was declined. The order is not paid; the shopper can try again. When OnCharge refused it because the store reached a limit set on its account, `data.reason` is `limit_exceeded` and nothing was sent to the bank. |
| `payment.cancelled` | The payment was cancelled before it was collected. Nothing was charged. |
| `payment.expired` | The shopper did not finish paying in time. Nothing was charged. |
| `payment.capture_failed` | An approved payment could not be collected. The order is not paid. |
| `refund.succeeded` | A refund went through. The amount is the total refunded on this order so far. |
| `refund.failed` | A refund could not be sent. Nothing was taken from your balance. |
| `chargeback.opened` | The shopper asked their bank to reverse this payment. OnCharge helps you answer it. |
| `dispute.evidence_due` | A dispute needs its evidence by the date given. OnCharge answers for you where it can; the dispute page says what is still missing. Sent once per dispute and deadline. |
| `chargeback.won` | The bank decided in your favour. You keep the money. |
| `chargeback.lost` | The bank decided for the shopper. The payment is reversed. |
| `fraud_warning.received` | The cardholder's bank reported this payment as fraud. Do not ship it yet: the payout is on hold, and OnCharge may refund it to stop a dispute. |
| `delivery.confirmed` | Every package of the order was confirmed delivered by the carrier. Sent once per order. |
| `payout.paid` | A payout reached your bank, or (a debit card payout, `method` "instant") your debit card, with `fee` taken out. Payouts pay orders whose delivery was confirmed. |
| `payout.failed` | A payout could not be delivered to your bank. The money is safe and is sent again; the problem says whether your bank details need fixing. A debit card payout that fails goes to your bank instead, its fee refunded. |
| `payout.returned` | Your bank sent a payout back after it arrived. The money is sent again once working bank details are on file. |
| `account.updated` | What your account can do changed: taking payments, receiving payouts, or what it needs from you. |
| `account.requirements_due` | Your account needs more information by the deadline, or it stops taking payments. Provide it under Settings. Sent once per change. |
| `account.restricted` | Your account stopped taking payments or receiving payouts. The reason says what to do. |
| `swap.created` | A conversion was created and waits for the coins to arrive. |
| `swap.completed` | A crypto payment was converted to the coin you are paid in and sent to your wallet. |
| `swap.failed` | A crypto payment could not be converted. The coins go back to the sender, or OnCharge contacts you. |
| `swap.refunded` | A conversion could not finish, and the coins were sent back to the sender. |
| `swap.expired` | No coins arrived before the conversion's quote ran out. Nothing was converted. |
| `support.conversation.created` | A customer started a conversation by email, chat or phone. Not sent yet: the sample shows what will arrive. |
| `support.message.received` | A customer wrote in an open conversation. Not sent yet: the sample shows what will arrive. |
| `support.conversation.closed` | A conversation was marked as done by your team, an OnCharge rep or the AI assistant. Not sent yet: the sample shows what will arrive. |
| `subscription.created` | A customer agreed to a subscription and it started: its trial began, or its first period was paid. |
| `subscription.updated` | The plan, quantity, card, or a waiting cancellation or pause changed. `data.change` says what: `plan_changed` (with `prorated_charge` and `prorated_credit`), `change_scheduled` (with `pending_change`), `price_increase_notice` (the customer was emailed the notice of a price increase, with `price_increase`), `change_applied`, `payment_method`, `cancel_scheduled`, `pause_scheduled`, `kept` (a waiting cancellation or pause was called off), `trial_ended` or `payment_recovered`. |
| `subscription.trial_will_end` | A trial ends soon and the customer was reminded: 7 days ahead for a trial of 14 days or more, 3 days for 7 to 13 days, 1 day for 3 to 6 days. Sent once per trial. |
| `subscription.past_due` | A period's payment failed. OnCharge retries it 1, 3, 7 and 14 days after the first failure (unless it waits for the customer) and asked the customer to check their card. |
| `subscription.paused` | The subscription paused: nothing is charged or shipped until it resumes (`data.resume_at`, or when you resume it). |
| `subscription.resumed` | A paused subscription started again; a new period began and was charged. |
| `subscription.canceled` | The subscription ended: cancelled by you or the customer, or after its payment failed on every retry (`data.cancel_reason`). |
| `subscription.period.paid` | A period (or a plan change) was paid. If it ships, ship it and report its tracking number with `data.session_id`: its payout is released on carrier-confirmed delivery, like any order. |
| `subscription.period.payment_failed` | A charge for a period failed. `data.failure` says why and `data.next_attempt_at` when it is tried again (null: it waits for the customer). |
**Headers**
| Header | Description |
|---|---|
| `OnCharge-Event-Id` | Unique event ID (`evt_…`). Deduplicate on it; the same event may be delivered more than once. |
| `OnCharge-Signature` | `t=,v1=` where `v1` = lower-case hex HMAC-SHA256(webhook signing secret, `"."`). The key is your webhook signing secret (`oc_cbsec_…`) as given. Compare in constant time and reject events where `\|now - t\| > 300`. |
| `X-Oncharge-Signature` | **Deprecated.** Legacy body-only signature kept for older plugins. Verify `OnCharge-Signature` instead. |
**Event body**
| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | string | Yes | Event ID (`evt_…`), the same as the `OnCharge-Event-Id` header. |
| `type` | one of `payment.pending`, `payment.authorized`, `payment.captured`, `payment.under_review`, `payment.refused`, `payment.cancelled`, `payment.expired`, `payment.capture_failed`, `refund.succeeded`, `refund.failed`, `chargeback.opened`, `dispute.evidence_due`, `chargeback.won`, `chargeback.lost`, `fraud_warning.received`, `delivery.confirmed`, `payout.paid`, `payout.failed`, `payout.returned`, `account.updated`, `account.requirements_due`, `account.restricted`, `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired`, `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.period.paid`, `subscription.period.payment_failed`, `support.conversation.created`, `support.message.received`, `support.conversation.closed` | Yes | Every event type. Payments on every rail use the same payment.* types (data.rail says which). Handle the types you need and acknowledge (2xx) any others; new types may be added. |
| `created` | integer | Yes | Unix time (seconds) the event was created. |
| `livemode` | boolean | Yes | false for events from test payments. |
| `data` | object | Yes | For payment events from a checkout, the fields below. Crypto and Card to Crypto paid to your wallet carry `session_id: null` with `payment_id`, `source`, `method`, `coin`, `coin_amount`, `wallet` and transaction hashes; every other event its own fields. All of them carry `rail`. |
| `data.session_id` | string or null | No | The checkout session; null for a payment paid straight to your wallet. |
| `data.order_id` | string or null | No | Your order ID, if known. |
| `data.reference` | string or null | No | The `reference` you sent when creating the session. |
| `data.amount` | integer or null | No | Minor units. For `refund.succeeded`, the total refunded so far. |
| `data.currency` | string or null | No | ISO 4217 code. |
| `data.status` | string or null | No | The order's payment status after the event (for example `captured`, `refunded`). |
| `data.rail` | one of `card`, `crypto`, `card_to_crypto` | Yes | The rail an event or payment is on: card checkout; crypto (crypto checkout, or a coin paid straight to your wallet through the plugin or the gateway API); or Card to Crypto (card, Cash App or Venmo paid out to your wallet in USDC). |
| `data.payment_reference` | string or null | No | OnCharge's reference for the payment (`ocpay_…`). |
| `data.payment_link_id` | string (uuid) or null | No | The payment link the checkout was made from (`/api/v1/payment-links`), or null. |
| `data.invoice_id` | string (uuid) | No | Only on a payment for an OnCharge invoice: the invoice's id (see Invoices). |
| `data.payment_method` | one of `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm`, `afterpay`, or `null` | No | How the shopper paid: `card`, or a way to pay beyond cards the store turned on (bank debit, Cash App Pay, Klarna, Affirm, Afterpay; see the Payment methods guide). Null for crypto. |
| `data.tax` | object or null | No | Sales tax on the payment, on payment, refund and chargeback events of a taxed payment only. |
| `data.tax.status` | one of `awaiting_address`, `calculated`, `pending`, `failed`, `collected`, `partly_refunded`, `refunded` | Yes | `awaiting_address`: no address yet, the payment waits. `calculated`: not paid yet. `pending`: tax included, charged while the calculation was unavailable; worked out shortly. `failed`: the calculation failed (`error`), the payment waits. `collected`, `partly_refunded`, `refunded`: paid, and how much of the tax was given back. |
| `data.tax.inclusive` | boolean | Yes | true when the listed prices include the tax. |
| `data.tax.currency` | string or null | Yes | |
| `data.tax.subtotal` | integer or null | Yes | Before tax, minor units. |
| `data.tax.amount` | integer or null | Yes | The tax, minor units. |
| `data.tax.total` | integer or null | Yes | What the customer pays, minor units. |
| `data.tax.shipping` | integer | Yes | The shipping charge inside the total, minor units. |
| `data.tax.jurisdictions` | array of object | Yes | |
| `data.tax.refunded` | integer | Yes | Tax given back so far with refunds and lost disputes, minor units. |
| `data.tax.error` | string or null | Yes | `tax_address_invalid` or `tax_unavailable` when `status` is `failed`. |
| `data.reason` | one of `limit_exceeded` | No | Only on `payment.refused` when OnCharge refused the payment itself: `limit_exceeded` (the store reached a limit OnCharge set on its account, such as a daily volume cap). Absent when the bank declined it. |
| `event` | one of `payment.pending`, `payment.authorized`, `payment.captured`, `payment.under_review`, `payment.refused`, `payment.cancelled`, `payment.expired`, `payment.capture_failed`, `refund.succeeded`, `refund.failed`, `chargeback.opened`, `dispute.evidence_due`, `chargeback.won`, `chargeback.lost`, `fraud_warning.received`, `delivery.confirmed`, `payout.paid`, `payout.failed`, `payout.returned`, `account.updated`, `account.requirements_due`, `account.restricted`, `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired`, `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.period.paid`, `subscription.period.payment_failed`, `support.conversation.created`, `support.message.received`, `support.conversation.closed` | No | Same as `type`. Kept for older plugins; only on payment events from a checkout. **Deprecated.** |
| `status` | string or null | No | Same as `data.status`. Kept for older plugins; only on payment events from a checkout. **Deprecated.** |
| `psp_reference` | string or null | No | Kept for older plugins, which store it as the order's transaction id: a payment made before 2026-12-01 keeps its original value here; from 2026-12-01 on it is the payment's OnCharge reference (`ocpay_…`, the same as `data.payment_reference`). Only on payment events from a checkout. **Deprecated.** |
```json title="payment.captured"
```
---
# SDKs
| Package | Runs on | Use it to |
|---|---|---|
| `@oncharge/node` | Your server (Node 18.17+, Next.js, serverless) | Sign API requests, create and read sessions, report shipments, refund, list payments, payouts and events, read your balance, verify webhooks, serve the RUO compliance feed. ESM and CommonJS, no dependencies. |
| `@oncharge/node/next` | Next.js App Router (or any Fetch API route handler) | Ready-made webhook and compliance-feed route handlers. |
| `@oncharge/js` | The browser | Embed the checkout iframe with resizing and events. |
| `@oncharge/js/react` | React 17+ | The `` component. |
| `oncharge.js` script | Any web page | `window.OnCharge.mountCheckout`, no bundler needed: `https://app.oncharge.io/js/v1/oncharge.js`. |
| `Gateway` in `@oncharge/node` | Your server | The [gateway API](https://oncharge.io/docs/gateway-api) (crypto and Card to Crypto): one wallet per order, hosted and single-provider links, Cash App and Venmo prepared in advance, signed-callback verification. |
| `@oncharge/react` | React 17+ | `` (Cash App, Venmo and card preloaded side by side), `` (live providers you switch on and off), ``, `useProviders()`, `useCryptoQuote()`, and ``. |
> **Coming soon to npm.** `@oncharge/node`, `@oncharge/js` and `@oncharge/react` are not yet published, so `npm install` will not find them yet. The hosted `oncharge.js` script is the same code as `@oncharge/js`. Until the packages are out, the [signing helper](https://oncharge.io/docs/authentication#examples), the [webhook verifier](https://oncharge.io/docs/webhooks#verify-the-signature), the [compliance feed reference implementation](https://oncharge.io/docs/compliance-feed#reference-implementation-any-javascript-runtime) and the [plain iframe code](https://oncharge.io/docs/checkout#embedded-iframe) do the same jobs without dependencies.
## @oncharge/node
```bash
npm install @oncharge/node
```
```ts
import { OnCharge } from '@oncharge/node';
const oncharge = new OnCharge({
apiKey: process.env.ONCHARGE_API_KEY!,
apiSecret: process.env.ONCHARGE_API_SECRET!,
// baseUrl: 'https://app.oncharge.io', (default)
// timeoutMs: 30_000, (default, per request)
// fetch: customFetch, (default: the global fetch)
});
```
Never import `@oncharge/node` into code that runs in the browser: it needs your API secret.
### Checkout sessions
```ts
const session = await oncharge.checkout.sessions.create(
{
amount: 4900,
currency: 'USD',
reference: 'order-1001',
return_url: 'https://shop.example.com/checkout/complete',
order_id: '1001',
customer_email: 'shopper@example.com',
shipping: { name: 'Alex Rivera', line1: '500 Market St', city: 'San Francisco', state: 'CA', postal_code: '94105', country: 'US' },
},
{ idempotencyKey: 'order-1001' },
);
// → { session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at }
```
`checkout_url` is the absolute checkout URL (`https://app.oncharge.io` + `iframe_url`). Pass it to the browser.
```ts
const current = await oncharge.checkout.sessions.retrieve(session.session_id);
// → { session_id, store_id, order_id, amount, currency, status, psp_reference, risk_decision, risk_score, created_at, updated_at, expires_at }
await oncharge.checkout.sessions.attachOrder(session.session_id, {
order_id: '1001',
shipping: { name: 'Alex Rivera', line1: '500 Market St', city: 'San Francisco', state: 'CA', postal_code: '94105', country: 'US' },
});
// → { session_id, order_id, shipping_recorded, shipping_on_file }
```
### Shipments
```ts
await oncharge.shipments.report({
session_id: session.session_id, // or order_id: '1001'
shipments: [{ carrier: 'UPS', tracking_number: '1Z999AA10123456784' }],
});
// → { session_id, shipments: [{ tracking_number, carrier, status, error?, message? }], delivery: { state, hold_reason } }
const { delivery } = await oncharge.shipments.get(session.session_id);
// delivery.state: not_tracked | awaiting_shipment | in_transit | delivered | on_hold | refunded
```
### Refunds
```ts
await oncharge.refunds.create(
{ session_id: session.session_id, amount: 1500, currency: 'USD', reference: 'refund-1001-1' },
{ idempotencyKey: 'refund-1001-1' },
);
// → { refund_id, session_id, status, amount, currency } (idempotent: true on a repeat with the same key)
```
### Payments, payouts and balance
```ts
// Payments on every rail (card, crypto, card_to_crypto), newest first; kind: refund | dispute | swap | all for the others
const { payments, next_cursor } = await oncharge.payments.list({ rail: 'card_to_crypto', status: 'paid', limit: 100 });
const more = next_cursor ? await oncharge.payments.list({ rail: 'card_to_crypto', status: 'paid', cursor: next_cursor }) : null;
// Payouts to your bank, and card totals for a period
const { payouts } = await oncharge.payouts.list({ status: 'failed' });
const totals = await oncharge.payouts.summary({ from: '2026-11-01', to: '2026-11-30' });
// A debit card payout (to the card added in the dashboard): quote, then send what the quote showed.
const { instant_payout: quote } = await oncharge.payouts.instant.retrieve();
if (quote.available) await oncharge.payouts.instant.create({ expectedAmount: quote.amount }, { idempotencyKey: `instant-${Date.now()}` });
// Where your money is
const balance = await oncharge.balance.retrieve();
// Ways to pay beyond cards (bank debit, Cash App Pay, Klarna, Affirm, Afterpay) and their status for your store
const { methods } = await oncharge.paymentMethods.list();
```
Every list is newest first and paged with `next_cursor` (pass it as `cursor`). Entries carry OnCharge references (`ocpay_…`, `ocrfd_…`, `ocdsp_…`, `ocswp_…`) and plain statuses. See the [API reference](https://oncharge.io/docs/api#listpayments).
### Events
```ts
// Every webhook event of the last 30 days, exactly as your endpoints received it, a page at a time
let cursor;
do {
const page = await oncharge.events.list({ type: 'payout.*', limit: 100, cursor }); // the same filter on every page
for (const event of page.events) await handle(event);
cursor = page.next_cursor ?? undefined;
} while (cursor);
const event = await oncharge.events.retrieve('evt_…');
await oncharge.events.replay(event.id, { endpointId: '…' }); // to one of your endpoints again, same id
```
### Invoices
```ts
const invoice = await oncharge.invoices.create(
{
customer: { name: 'Ada Lovelace', email: 'ada@example.com' },
lines: [{ description: 'Consulting', quantity: 10, unit_amount: 15000, tax_rate: 8.875 }],
days_until_due: 14,
send: true, // finalize and email it; `finalize: true` only numbers it
},
{ idempotencyKey: 'invoice-1001' },
);
// → { id, number: 'INV-0001', status: 'open', hosted_url, total, amount_remaining, … }
await oncharge.invoices.list({ status: 'overdue' }); // → { invoices, next_cursor }
await oncharge.invoices.retrieve(invoice.id);
await oncharge.invoices.update(draftId, { memo: 'Thanks' }); // drafts only
await oncharge.invoices.finalize(draftId, { send: true });
await oncharge.invoices.send(invoice.id);
await oncharge.invoices.markPaid(invoice.id, { note: 'Bank transfer' });
await oncharge.invoices.voidInvoice(invoice.id, { reason: 'Duplicate' });
await oncharge.invoices.createCreditNote(invoice.id, { amount: 5000, reason: 'order_change', refund: true }, { idempotencyKey: 'cn-1001' });
await oncharge.invoices.refundExtraPayment(invoice.id, { payment_reference: 'ocpay_…' }); // an extra payment, once
await oncharge.invoices.del(draftId); // drafts only
```
See [Invoices](https://oncharge.io/docs/invoices).
### Subscriptions
```ts
const plan = await oncharge.plans.create(
{ name: 'Monthly box', amount: 3000, currency: 'USD', interval: 'month', trial_days: 14, intro: { amount: 1500, periods: 2 } },
{ idempotencyKey: 'plan-monthly-box' },
);
// → { id, object: 'plan', interval_text: 'month', active: true, … }; an add-on is { kind: 'addon', name, amount }
await oncharge.plans.list({ include_archived: true }); // → { data }
await oncharge.plans.retrieve(plan.id);
await oncharge.plans.update(plan.id, { active: false }); // name, description, metadata or archive; never the price
await oncharge.plans.createPaymentLink(plan.id, { title: 'Join' }); // → { id, code, url, plan_id }
// A hosted sign-up page: the customer agrees to the recurring terms and enters a card on OnCharge's page
const signup = await oncharge.subscriptions.checkout({ plan_id: plan.id, customer_email: 'ada@example.com' }, { idempotencyKey: 'signup-ada' });
// → { id, status: 'incomplete', url, sign_up_expires_at, … }
// Or for an existing customer: OnCharge emails them the sign-up link (never returned)
await oncharge.subscriptions.create({ customer_id: customerId, plan_id: plan.id }, { idempotencyKey: 'sub-1001' });
await oncharge.subscriptions.list({ status: 'past_due', limit: 50 }); // → { data, has_more }; page with starting_after
await oncharge.subscriptions.retrieve(signup.id); // with billings and history
await oncharge.subscriptions.update(signup.id, { payment_method_id: cardId }); // another of the customer's saved cards
await oncharge.subscriptions.change(signup.id, { plan_id: yearlyPlanId, proration: 'next_period' });
await oncharge.subscriptions.pause(signup.id, { periods: 2 });
await oncharge.subscriptions.resume(signup.id);
await oncharge.subscriptions.cancel(signup.id); // at the end of the period; { at_period_end: false } for now
await oncharge.subscriptions.retry(signup.id); // a past-due subscription, now
```
`plans.update` and `subscriptions.update` are `PATCH` requests, signed like the others. Subscriptions are not available yet: until they are, these calls answer 404 `not_found`. See [Subscriptions](https://oncharge.io/docs/subscriptions).
### Errors
| Class | When | Useful fields |
|---|---|---|
| `OnChargeApiError` | OnCharge answered with an error. | `status`, `code` (OnCharge's `error`, e.g. `validation_error`, `invalid_signature`), `message`, `body` |
| `OnChargeConnectionError` | No answer: network failure or timeout. | `cause` |
| `OnChargeSignatureError` | A webhook signature is missing, malformed, too old or wrong. | `code` |
| `OnChargeError` | Base class of all of the above (also thrown for bad options). | |
Retry `429`, `5xx` and connection errors with backoff and the same idempotency key.
### Webhooks
```ts
const event = OnCharge.webhooks.constructEvent(rawBody, request.headers.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET!, {
toleranceSeconds: 300, // default
});
// Throws OnChargeSignatureError (code: missing_signature | invalid_signature_header | timestamp_outside_tolerance
// | signature_mismatch | invalid_payload). Returns the typed event.
```
`rawBody` is the request body exactly as received (a string or bytes). Also available:
- `OnCharge.webhooks.verifySignature(rawBody, header, secret, options?)` checks without parsing.
- `OnCharge.webhooks.generateTestHeader({ payload, secret, timestamp? })` returns a valid `OnCharge-Signature` for your tests.
- `OnCharge.webhooks.SIGNATURE_HEADER` (`OnCharge-Signature`) and `EVENT_ID_HEADER` (`OnCharge-Event-Id`).
The same functions are exported by name (`constructEvent`, `verifyWebhookSignature`, `generateTestHeader`), with the `OnChargeEvent` and `OnChargeEventType` types and `EVENT_TYPES` (every type, for an endpoint's event list). `OnChargeEvent` is typed per event: switch on `event.type` and `event.data` has that event's shape, `data.rail` included. See [Webhooks](https://oncharge.io/docs/webhooks) for the event types.
```ts
switch (event.type) {
case 'payment.captured':
if (event.data.session_id === null) {
// crypto or Card to Crypto paid to your wallet: event.data.rail, .method, .coin_amount, .payout_tx
}
break;
case 'payout.failed':
console.log(event.data.problem?.reason);
break;
}
```
### RUO compliance feed
```ts
import { createComplianceFeed } from '@oncharge/node';
const feed = createComplianceFeed({
connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE, // occs_.; unset → every endpoint answers 409 (not connected)
host: 'shop.example.com', // exactly as connected
site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
async listItems({ cursor, limit }) {
const items = await loadPublishedCatalog(cursor, limit); // products (gated ones too), pages, posts
return { items, nextCursor: items.length === limit ? cursor + limit : null };
},
reviewerAccess: async () => ({ accountExists: true, canViewCatalog: true, ownerConfirmed: true }), // optional
});
const response = await feed.handle(request); // Request → Response
```
| Option | Notes |
|---|---|
| `connectionCode` | The one-time `occs_…` code. Or pass `connectionId` and `signingKey` (hex SHA-256 of the secret) instead. |
| `host` | The bare host name as connected in the portal. |
| `site` | `{ name, tagline?, home_url, terms_page_url?, privacy_policy_url?, refund_page_url?, shipping_page_url?, contact_page_url? }`, or a function returning it. |
| `listItems({ cursor, limit })` | Returns `{ items, nextCursor, truncated? }`; `nextCursor` is `null` on the last page. |
| `reviewerAccess` | `{ accountExists, canViewCatalog, ownerConfirmed }`, or a function returning it. |
| `nonceStore` | `{ claim(nonce, ttlSeconds) }` returning `false` for a nonce already seen. Default: in memory, per process; use shared storage when you run several instances (`createMemoryNonceStore()` is exported). |
| `version` | Reported as `plugin_version`. |
The endpoint is chosen from the last path segment (`proof`, `content`, `reviewer-access`), so route every request under your base path to `feed.handle`. See [RUO compliance feed](https://oncharge.io/docs/compliance-feed).
### Low-level signing
`signedRequestHeaders({ apiKey, apiSecret, method, path, body, timestamp? })` returns the three `X-Oncharge-*` headers, for endpoints the client does not wrap (disputes, risk). `signRequest({ apiSecret, timestamp, method, path, body })` and `requestSigningString({ timestamp, method, path, body })` expose the steps. Pass `path` without the query string and `body` exactly as you will send it. See [Authentication](https://oncharge.io/docs/authentication).
## @oncharge/node/next
```ts title="app/api/webhooks/oncharge/route.ts"
import { createWebhookHandler } from '@oncharge/node/next';
export const { POST } = createWebhookHandler({
secret: process.env.ONCHARGE_WEBHOOK_SECRET,
async onEvent(event, { request }) {
// event.type, event.data.session_id, event.data.order_id, …
// throw to have OnCharge retry later
},
// toleranceSeconds: 300,
// eventIdStore: { has(id), add(id) } | false,
});
```
| Option | Notes |
|---|---|
| `secret` | Your webhook signing secret. If it is missing the handler answers `500 {"error":"not_configured"}`. |
| `onEvent(event, { request })` | Called once per verified event. Throw to make the handler answer `500`, so OnCharge retries. |
| `toleranceSeconds` | Default 300. |
| `eventIdStore` | Remembers handled event IDs so retries are acknowledged without calling `onEvent` again. Default: in memory (`createMemoryEventIdStore()`); pass a store backed by your database or Redis when you run several instances, or `false` to turn it off. |
Bad signatures get `400 {"error":""}`; handled and duplicate events get `200`.
```ts title="app/.well-known/oncharge-compliance/[route]/route.ts"
import { createComplianceFeedRoute } from '@oncharge/node/next';
export const { GET } = createComplianceFeedRoute({
connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
host: 'shop.example.com',
site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/' },
async listItems({ cursor, limit }) {
const items = await loadPublishedCatalog(cursor, limit);
return { items, nextCursor: items.length === limit ? cursor + limit : null };
},
});
```
`createComplianceFeedRoute` takes the same options as `createComplianceFeed`.
## @oncharge/js
```bash
npm install @oncharge/js
```
```ts
import { mountCheckout } from '@oncharge/js';
const checkout = mountCheckout('#oncharge-checkout', {
url: checkoutUrl, // session.checkout_url, or iframe_url with baseUrl
onReady: () => {},
onComplete: ({ sessionId, status }) => {}, // status: 'captured' | 'authorized'
onError: ({ message, status }) => {}, // status: 'refused' | 'error' (optional)
onRedirect: ({ url }) => window.location.assign(url), // default: navigate the top window
autoResize: true, // default
minHeight: 480, // default
});
checkout.iframe; // the HTMLIFrameElement
checkout.sessionId; // parsed from the URL
checkout.destroy();
```
`mountCheckout` adds `embed=1`, `parent_origin` and a fresh `embed_nonce` to the URL, and accepts a message only from that iframe, at the checkout's origin, with that nonce. It throws if the URL is not HTTPS (HTTP is allowed only for `localhost`). The same function is available without a bundler:
```html
```
## @oncharge/js/react
```tsx
import { OnChargeCheckout } from '@oncharge/js/react';
{}}
onError={({ message }) => {}}
onReady={() => {}}
onRedirect={({ url }) => window.location.assign(url)}
className="w-full"
minHeight={480}
/>;
```
Props: `url`, `baseUrl`, `onReady`, `onComplete`, `onError`, `onRedirect`, `className`, `style`, `minHeight`, `autoResize`, `title`. The iframe is remounted only when `url`, `baseUrl`, `minHeight`, `autoResize` or `title` change. It is a client component (`'use client'`).
See [Messages from the checkout](https://oncharge.io/docs/checkout#messages-from-the-checkout) for the protocol underneath.
## Other languages
There is no official PHP or Python SDK. The [Authentication examples](https://oncharge.io/docs/authentication#examples) are complete, dependency-free clients, and the [OpenAPI spec](https://oncharge.io/openapi.json) works with OpenAPI code generators (add the signing headers in a request hook).
## Gateway API {#gateway}
`Gateway` (in `@oncharge/node`) calls the [Gateway API](https://oncharge.io/docs/gateway-api). Give it your gateway key (Payments → Gateway API in the dashboard): wallets are then created with the callback relay, so OnCharge signs every callback it sends you.
```ts title="server"
import { Gateway, callbackToken, verifyCallbackToken, verifyRelayedCallback, parseGatewayCallback } from '@oncharge/node';
const gateway = new Gateway({ key: process.env.ONCHARGE_GATEWAY_KEY });
const callback = `https://shop.example.com/oncharge/callback?order=${order.id}&token=${callbackToken(process.env.ONCHARGE_CALLBACK_SECRET!, order.id)}`;
const wallet = await gateway.createWallet(process.env.ONCHARGE_PAYOUT_WALLET!, callback);
const hosted = gateway.checkoutUrl(wallet, { amount: '49.90', email }); // every available method, card included
const card = gateway.checkoutUrl(wallet, { amount: '49.90', email, provider: 'card' }); // the card page alone
const payApps = await gateway.preparePayApps(wallet, { amount: '49.90', email, providers: ['cashapp', 'venmo', 'card'] });
```
`preparePayApps` builds the Cash App, Venmo and card links for the same wallet and resolves Cash App to its own invoice (with the QR code) in parallel, so the payment page opens without a redirect; the card page opens in a new tab (`frame` is null). A payment through any of them, or through the hosted checkout, completes the order. The card page's id is `card`.
With a gateway key, each payment also reaches your [webhook endpoints](https://oncharge.io/docs/webhooks#payments-on-every-rail) as `payment.pending` and `payment.captured` with `data.rail` `crypto` or `card_to_crypto`, and appears in [`oncharge.payments.list()`](#payments-payouts-and-balance).
In the callback, verify OnCharge's signature over the full URL as it arrived, then your token:
```ts title="callback"
const rawQuery = req.originalUrl.split('?')[1] ?? '';
const url = `https://shop.example.com/oncharge/callback?${rawQuery}`; // your registered URL plus the raw query
if (!verifyRelayedCallback({ url, signature: req.get('X-OnCharge-Signature'), signingSecret: process.env.ONCHARGE_SIGNING_SECRET! })) return res.sendStatus(403);
const payment = parseGatewayCallback(rawQuery);
if (!verifyCallbackToken(process.env.ONCHARGE_CALLBACK_SECRET!, payment.get('order')!, payment.get('token'))) return res.sendStatus(403);
```
## @oncharge/react {#react}
```bash
npm install @oncharge/react
```
```tsx title="Cash App and Venmo, preloaded"
'use client';
import { PayAppSwitcher } from '@oncharge/react';
// payApps: from gateway.preparePayApps() on your server
saveChoice(provider)} />;
```
Every frame loads at once (preconnected, eager), the others behind their tabs, so switching is instant.
```tsx title="Providers you switch on and off"
import { ProviderPicker, checkoutUrl } from '@oncharge/react';
(location.href = checkoutUrl(addressIn, { amount: '49.90', email, provider: p.id }))}
/>;
```
` ` shows a QR code, the exact amount and a copyable address; `useCryptoQuote(coin, amount)` prices the order. ` ` embeds the Secure Checkout card form.
---
# Build with AI
You can ask an AI coding assistant (Claude, ChatGPT, Cursor, GitHub Copilot and others) to integrate OnCharge for you. Give it the right context and it can write the session endpoint, checkout page, webhook handler, shipment reporting and tests for your stack. Everything on this page is free to use.
> Whatever tool you use: keep your API secret and webhook secret out of the chat, out of the browser and out of your repository. Put them in your server's environment, and review generated code before you deploy it.
## 1. Point the assistant at the docs
| Resource | Use it for |
|---|---|
| [`https://oncharge.io/llms.txt`](https://oncharge.io/llms.txt) | An index of these docs in the [llms.txt](https://llmstxt.org) format. |
| [`https://oncharge.io/llms-full.txt`](https://oncharge.io/llms-full.txt) | All of these docs in one Markdown file. Paste or attach it when the assistant cannot browse. |
| [`https://oncharge.io/openapi.json`](https://oncharge.io/openapi.json) | The OpenAPI 3.1 spec of the merchant API and webhooks. |
| `https://oncharge.io/docs/.md` | Any single page as Markdown, e.g. [`/docs/webhooks.md`](https://oncharge.io/docs/webhooks.md) (the overview is `/docs/index.md`). |
In Cursor, add `https://oncharge.io/llms-full.txt` under **Docs** and mention `@OnCharge` in your prompt. In Claude or ChatGPT, attach `llms-full.txt` or paste its URL.
## 2. Use a prompt for your stack
The [AI prompt library](https://oncharge.io/docs/ai-prompts) has copy-paste prompts for Next.js, React with a backend, plain HTML with a Node or PHP backend, a custom WooCommerce theme, Magento, Wix, a headless Shopify (Hydrogen) storefront, and Webflow or Framer. Each one tells the assistant exactly what to build, which endpoints to call, how to sign requests and verify webhooks, how to report shipments, when to add the RUO compliance feed, and what never to do.
## 3. Claude: the OnCharge skill
The **oncharge-checkout** [Agent Skill](https://agentskills.io) teaches Claude the OnCharge integration: the workflow, the signing rules, and reference files it loads only when needed.
**Claude Code.** Download and unzip it into your personal skills folder:
```bash
mkdir -p ~/.claude/skills && cd ~/.claude/skills
curl -fsSLO https://oncharge.io/docs/ai-files/oncharge-checkout-skill.zip
unzip -o oncharge-checkout-skill.zip && rm oncharge-checkout-skill.zip
```
Unzip it into `.claude/skills/` inside a project instead to share it with your team through the repository.
**Claude apps.** Download [`oncharge-checkout-skill.zip`](https://oncharge.io/docs/ai-files/oncharge-checkout-skill.zip) and upload it under **Settings → Capabilities → Skills** (skills must be available on your plan).
The individual files are also published: [`SKILL.md`](https://oncharge.io/docs/ai-files/claude-skill/oncharge-checkout/SKILL.md).
Then ask, for example: "Add OnCharge checkout to this project."
## 4. ChatGPT: the OnCharge Integration Assistant GPT
You can create a custom GPT that knows these docs and can look pages up while it works:
1. In ChatGPT, open **Explore GPTs → Create → Configure**.
2. **Name:** OnCharge Integration Assistant. **Description:** Integrates OnCharge checkout into your store.
3. **Instructions:** paste [`gpt-instructions.md`](https://oncharge.io/docs/ai-files/chatgpt/gpt-instructions.md).
4. **Conversation starters:** add the four lines from [`conversation-starters.txt`](https://oncharge.io/docs/ai-files/chatgpt/conversation-starters.txt).
5. **Knowledge:** upload [`llms-full.txt`](https://oncharge.io/llms-full.txt) and [`openapi.json`](https://oncharge.io/openapi.json).
6. **Capabilities:** turn on Web Search and Code Interpreter.
7. **Actions → Create new action → Import from URL:** `https://oncharge.io/docs/ai-files/chatgpt/actions.openapi.json`. Authentication: **None**. Privacy policy: `https://oncharge.io/privacy`.
The actions only read the public docs (search and fetch pages). The GPT never calls the OnCharge merchant API: requests must be signed with your API secret, which should never be pasted into a chat. For live API calls from an assistant, use the MCP server below on your own machine.
## 5. MCP server: docs and live API tools
`@oncharge/mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server that runs locally over stdio. It gives any MCP client (Claude Code, Claude Desktop, Cursor, VS Code, Windsurf and others):
| Tool | What it does |
|---|---|
| `search_docs`, `read_doc`, `list_docs` | Search and read these docs offline (bundled with the server). |
| `create_checkout_session` | `POST /api/v1/checkout/sessions` |
| `get_checkout_session` | `GET /api/v1/checkout/sessions/{id}` |
| `attach_order` | `POST /api/v1/checkout/sessions/{id}/order` |
| `report_shipment` | `POST /api/v1/shipments` |
| `get_delivery_status` | `GET /api/v1/shipments?session_id=…` |
| `create_refund` | `POST /api/v1/refunds` (moves money; your client asks before running it) |
| `verify_webhook_signature` | Checks an `OnCharge-Signature` header against a raw body. |
| `explain_signature` | Shows the signing string and signature for a request, to debug your own code. |
The docs tools work without credentials. The API tools appear when `ONCHARGE_API_KEY` and `ONCHARGE_API_SECRET` are set; `ONCHARGE_BASE_URL` defaults to `https://app.oncharge.io`, and `ONCHARGE_WEBHOOK_SECRET` is used by `verify_webhook_signature` when no secret is passed.
> **Coming soon to npm.** Until `@oncharge/mcp` is published, OnCharge can provide the built package; replace `npx -y @oncharge/mcp` below with `node /path/to/oncharge-mcp/dist/index.js`.
**Claude Code**
```bash
claude mcp add oncharge \
--env ONCHARGE_API_KEY=oc_key_... \
--env ONCHARGE_API_SECRET=oc_sec_... \
-- npx -y @oncharge/mcp
```
**Claude Desktop** (`claude_desktop_config.json`), **Cursor** (`.cursor/mcp.json`) and most other clients:
```json title="MCP client configuration"
{
"mcpServers": {
"oncharge": {
"command": "npx",
"args": ["-y", "@oncharge/mcp"],
"env": {
"ONCHARGE_API_KEY": "oc_key_...",
"ONCHARGE_API_SECRET": "oc_sec_...",
"ONCHARGE_BASE_URL": "https://app.oncharge.io"
}
}
}
}
```
**VS Code** (`.vscode/mcp.json`):
```json title=".vscode/mcp.json"
{
"servers": {
"oncharge": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@oncharge/mcp"],
"env": { "ONCHARGE_API_KEY": "${input:onchargeKey}", "ONCHARGE_API_SECRET": "${input:onchargeSecret}" }
}
},
"inputs": [
{ "id": "onchargeKey", "type": "promptString", "description": "OnCharge API key" },
{ "id": "onchargeSecret", "type": "promptString", "description": "OnCharge API secret", "password": true }
]
}
```
Leave the `env` block out to use only the docs tools. MCP configuration files contain your secret: keep them out of version control.
## What a good AI-built integration has
Use this to review what the assistant produced:
- Sessions are created on the server, with the amount from your database and an `Idempotency-Key`.
- The API secret never reaches the browser or the repository.
- The checkout is shown by redirect or an iframe on a registered domain, and `postMessage` events are checked against `https://app.oncharge.io`.
- Orders are marked paid only from a verified webhook (or a server-side status check).
- The webhook handler verifies `OnCharge-Signature` on the raw body, deduplicates event IDs and replies within 10 seconds.
- Shipping addresses are sent for physical goods, and tracking numbers are reported when orders ship.
- Tests cover the [signing test vector](https://oncharge.io/docs/authentication#test-vector) and webhook verification.
---
# AI prompt library
Prompts that have Claude, ChatGPT or Cursor add OnCharge checkout to Next.js, React, HTML, WooCommerce, Magento, Wix, headless Shopify, Webflow or Framer. The prompts are at https://oncharge.io/docs/ai-prompts (plain text: https://oncharge.io/docs/ai-files/prompts/.txt).
---
# AI Connector
Connect Claude, ChatGPT, Claude Code or another AI assistant to your OnCharge store, then ask it about your ad spend, sales and return on ad spend in plain English. The connector is an [MCP](https://modelcontextprotocol.io) server. It is read-only: the assistant can look at your ads and payments, but it can't change anything.
> Only an owner or admin of a store can connect an assistant. Each connection covers one store.
## Connect your assistant
The connector's address is:
```text
https://app.oncharge.io/api/mcp
```
It is also in the merchant portal under **Settings → AI Connector**.
**Claude (claude.ai or the desktop app).**
1. Open **Settings → Connectors** and press **Add custom connector**.
2. Name it OnCharge and paste the address.
3. Press **Add**, then **Connect**.
4. In the OnCharge window, sign in, pick the store and press **Allow**.
**ChatGPT.**
1. Open **Settings → Apps & Connectors → Advanced settings** and turn on **Developer mode**.
2. Press **Create**, paste the address and set authentication to **OAuth**.
3. Sign in to OnCharge, pick the store and press **Allow**.
**Claude Code.**
```bash
claude mcp add --transport http oncharge https://app.oncharge.io/api/mcp
```
Then type `/mcp`, choose **oncharge** and **Authenticate**.
**Other assistants.** Any MCP client that supports Streamable HTTP and OAuth 2.1 with dynamic client registration can connect the same way.
## What the assistant can see
| Tool | Needs | What it returns |
|---|---|---|
| `get_store` | either | The store, what the connection may see, and its linked ad accounts, pixels and catalogs. |
| `get_revenue` | Payments | Paid orders, gross revenue, refunds and net revenue per currency, with disputes opened. It can break these down by day, by ad channel or by `utm_campaign`. |
| `list_recent_orders` | Payments | The latest paid orders: amount, refunds, status and ad channel. |
| `get_ad_spend` | Ads | Spend, impressions, clicks, CTR and CPC per ad platform, with the conversions and ROAS the platforms report. It can break these down by day or by ad account. |
| `list_campaign_plans` | Ads | Google and TikTok campaigns OnCharge runs for the store, with their status and budget. |
| `get_true_roas` | Ads and Payments | Each platform's spend against the revenue OnCharge actually took from shoppers who clicked its ads, next to the ROAS the platform reports. |
- No shopper names, emails, phone numbers or addresses are ever sent to the assistant.
- No API keys or ad platform credentials are sent either.
- Money is in major units (`49.5` is $49.50) next to its currency. Currencies are never converted.
## True ROAS
Ad platforms count conversions their own way. Their totals can include view-through and modelled conversions, and orders that were refunded later.
`get_true_roas` uses the payments OnCharge processed instead. Each order is credited to the ad platform of the shopper's last recorded click:
- The click ID from the landing URL, if there is one: `fbclid`, `gclid`/`gbraid`/`wbraid` or `ttclid`.
- Otherwise, Meta's `_fbc` cookie.
The OnCharge tag or plugin records that click at checkout (see [Advertising](https://oncharge.io/docs/advertising)). Refunds are subtracted, and spend comes from the ad accounts connected in the portal.
Two caveats:
- Facebook also adds `fbclid` to clicks on unpaid posts, so some organic Facebook sales can count as Meta.
- Orders from storefronts without the OnCharge tag can't be credited to any platform.
## Try asking
- "What was my true ROAS on Meta last month, and how does it compare with what Meta reports?"
- "Which `utm_campaign` brought in the most revenue over the last 30 days?"
- "How much did I spend on ads this week, and how much did refunds cost me?"
## Disconnect
Go to **Settings → AI Connector** and press **Disconnect**. You can also remove the connector in your assistant, which revokes its tokens.
Access ends immediately in both cases. It also ends straight away for any connections made by someone you remove from your OnCharge account.
## For developers
The connector follows the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). OnCharge is both the authorization server and the protected resource.
| | |
|---|---|
| MCP endpoint | `POST https://app.oncharge.io/api/mcp`. Streamable HTTP in stateless JSON mode; `GET` returns 405 because there is no server-sent event stream. |
| Protected resource metadata | `https://app.oncharge.io/.well-known/oauth-protected-resource/api/mcp` |
| Authorization server metadata | `https://app.oncharge.io/.well-known/oauth-authorization-server` |
| Client registration | `POST /api/oauth/register` ([RFC 7591](https://www.rfc-editor.org/rfc/rfc7591)). Public clients only (`token_endpoint_auth_method: none`). Redirect URIs must use `https`, loopback `http` or a private-use scheme. |
| Authorization | `/oauth/authorize`: authorization code with PKCE (`S256` only). `resource` must be the MCP endpoint. The response includes `iss` ([RFC 9207](https://www.rfc-editor.org/rfc/rfc9207)). |
| Token | `POST /api/oauth/token` with `authorization_code` or `refresh_token`. Access tokens last 1 hour. Refresh tokens last 60 days and rotate on every use; reusing one disconnects the app. |
| Revocation | `POST /api/oauth/revoke` ([RFC 7009](https://www.rfc-editor.org/rfc/rfc7009)). Revoking a refresh token disconnects the app. |
| Scopes | `ads:read` and `payments:read`. Both are granted when none are requested. |