# 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": "", "status": "captured" } ``` | `type` | Fields | When | |---|---|---| | `ready` | `height` | The payment form is shown (once per load). | | `resize` | `height` (CSS pixels) | The content height changed. | | `complete` | `status`: `captured` or `authorized` | The payment succeeded. | | `error` | `message`, `status`: `refused` or `error` | The payment failed or the form could not load. | | `redirect` | `url` | The checkout wants to leave the frame (embed mode); navigate the top window there. | Accept a message only when `event.origin` is the checkout's origin, `event.source` is the checkout iframe's window, `source` and `version` match, and `nonce` equals the `embed_nonce` you passed. `@oncharge/js` does all of this for you. ## Script tag The hosted script adds `window.OnCharge.mountCheckout`: it builds the iframe with the parameters above, checks every message, resizes the frame and turns the messages into callbacks. ```html title="checkout.html"
``` With a bundler, use the npm package instead (same options): ```js import { mountCheckout } from '@oncharge/js'; const checkout = mountCheckout('#oncharge-checkout', { url: checkoutUrl, onComplete: ({ sessionId }) => { /* … */ } }); ``` > **Coming soon to npm.** `@oncharge/js` is not yet published. The hosted script above is the same code; until the package is out, use the script tag or the [plain iframe](#embedded-iframe). | Option | Type | Default | Purpose | |---|---|---|---| | `url` | string | (required) | The session's `checkout_url`, or its `iframe_url` resolved against `baseUrl`. Must be HTTPS. | | `baseUrl` | string | `https://app.oncharge.io` | Used to resolve a relative `url`. | | `onReady` | `() => void` | | The payment form is shown. | | `onComplete` | `({ sessionId, status }) => void` | | The payment succeeded (`status` is `captured` or `authorized`). Confirm on your server before fulfilling. | | `onError` | `({ message, status? }) => void` | | The payment failed (`status: 'refused'`) or the form could not load. | | `onRedirect` | `({ url }) => void` | navigate the top window | The checkout wants to leave the frame. | | `autoResize` | boolean | `true` | Follow the checkout's content height. | | `minHeight` | number | `480` | Minimum iframe height in pixels. | | `title` | string | `Secure checkout` | Accessible title of the iframe. | `mountCheckout(target, options)` takes a CSS selector or an element and returns `{ iframe, sessionId, destroy() }`; `destroy()` removes the iframe and its listener and is safe to call twice. ## React ```tsx title="Checkout.tsx" import { OnChargeCheckout } from '@oncharge/js/react'; export function Checkout({ checkoutUrl }: { checkoutUrl: string }) { return ( { window.location.href = `/checkout/complete?session=${encodeURIComponent(sessionId)}`; }} onError={({ message }) => console.warn(message)} /> ); } ``` `` takes the same options as `mountCheckout` as props, plus `className` and `style` for its container. It remounts the iframe only when `url`, `baseUrl`, `minHeight`, `autoResize` or `title` change; callbacks can change on every render. Your React app gets `checkoutUrl` from your own backend endpoint, which creates the session. See the [React guide](https://oncharge.io/docs/react). ## Next.js Create the session in a server action or route handler and render the component in a client component. The [Next.js guide](https://oncharge.io/docs/nextjs) has the full code, including the webhook route. ## Create the session before the order exists Many checkouts show the payment form before the order is saved (WooCommerce does this). Create the session from the cart with `reference` set to your cart ID and the cart ID as the idempotency key. When the shopper places the order, attach it: ```http POST /api/v1/checkout/sessions/{session_id}/order { "order_id": "1001", "shipping": { "name": "Alex Rivera", "line1": "500 Market St", "city": "San Francisco", "state": "CA", "postal_code": "94105", "country": "US" } } ``` Each value is recorded once. The shipping address is accepted only while the session has none, no tracking has been reported, and the session is less than 24 hours old. The response tells you what is on file (`shipping_recorded`, `shipping_on_file`). ## Content Security Policy If your site sends a `Content-Security-Policy` header, allow the checkout: ```text frame-src https://app.oncharge.io; script-src https://app.oncharge.io; # only if you use the hosted script ``` The embedding page must be served over HTTPS from a registered domain (or a registered `localhost` during development). ## After the payment | Session status | What happened | Your action | |---|---|---| | `captured` | Paid. | Fulfil the order. | | `authorized` | Approved, not captured yet. | Wait for `payment.captured`, or [cancel](https://oncharge.io/docs/api#cancelcheckoutsession). | | `pending` | The shopper must complete a step. | Wait. | | `refused` | Declined. | Let the shopper try again. A declined payment is never retried automatically; the checkout lets the shopper try another card. | | `cancelled`, `expired`, `error` | Not paid. | Create a new session if the shopper wants to retry. | Refund captured payments with [`POST /api/v1/refunds`](https://oncharge.io/docs/api#createrefund). --- # Payment links A payment link is a page OnCharge hosts for you, `https://app.oncharge.io/l/`, 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