AI prompt library
Copy a prompt into Claude, ChatGPT, Cursor or any coding assistant, fill in the bracketed parts, and let it build the integration in your codebase. Each prompt includes the OnCharge facts the assistant needs (endpoints, signing, webhooks, shipments) and the rules it must follow, so it works even without web access. For more context, also attach llms-full.txt. See Build with AI for the Claude skill, the custom GPT and the MCP server.
Next.js (App Router)#
Server action or page that creates the session, embedded checkout component, webhook route, shipment action, optional compliance feed route.
I run a Next.js (App Router, TypeScript) store and want to accept card payments with OnCharge. Integrate it into this codebase.
Build:
1. `lib/oncharge.ts` (with `import 'server-only'`): a signed request helper for the OnCharge API (or the @oncharge/node client if it is installed), reading the credentials from `process.env`.
2. A server-side way to start checkout for an order (a server action or the checkout page's server component): load the order from my database, create the checkout session with the order id as Idempotency-Key, store the session_id on the order, and return the checkout URL.
3. A client component that embeds the checkout in an iframe (or `@oncharge/js/react` if installed): validate `event.origin === 'https://app.oncharge.io'` and the message shape, resize on `resize`, navigate on `redirect`, go to my order-complete page on `complete`.
4. `app/api/webhooks/oncharge/route.ts`: read `await request.text()`, verify OnCharge-Signature, deduplicate on the event id, and update the order for payment.captured, payment.refused, payment.cancelled, refund.succeeded, chargeback.opened and delivery.confirmed. Return 200 quickly.
5. An order-complete page that shows the status from my database (set by the webhook), optionally re-checking with GET /api/v1/checkout/sessions/{id}.
6. A server action for my admin/fulfilment flow that reports carrier + tracking numbers to POST /api/v1/shipments and surfaces rejected numbers.
7. A server action for refunds with an Idempotency-Key.
8. If my store sells research-use-only (RUO) products: `app/.well-known/oncharge-compliance/[route]/route.ts` serving the compliance feed from my published catalogue.
9. A CSP update (if I have one) allowing `frame-src https://app.oncharge.io`, and Vitest/Jest tests for the signer and webhook verifier.
Do not prefix any OnCharge variable with NEXT_PUBLIC_.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.React single-page app + backend#
Express (or your existing) backend endpoints plus a React checkout component.
I have a React single-page app (Vite) with a Node.js backend and want to accept card payments with OnCharge. My backend framework is: [Express / Fastify / Hono / NestJS: fill in]. Integrate OnCharge into both.
Build:
1. Backend: a signed OnCharge request helper (Node `crypto`, no extra dependencies), reading credentials from the server environment.
2. Backend: `POST /api/checkout` that takes only an order id (or cart id) from the browser, loads the order and amount from my database, creates the checkout session (Idempotency-Key = order id, shipping address for physical goods) and returns `{ checkoutUrl }` where checkoutUrl = "https://app.oncharge.io" + iframe_url.
3. Backend: `POST /api/webhooks/oncharge` registered BEFORE any JSON body parser, using the raw body to verify OnCharge-Signature, deduplicating event ids, and updating the order status.
4. Backend: functions/endpoints (admin-only) to report shipments and create refunds.
5. React: a `<Checkout orderId>` component that calls `/api/checkout` and embeds the checkout iframe with a `message` listener (origin check, resize, redirect, complete → navigate to my order page). Use `@oncharge/js/react` only if it is already installed.
6. React: the order page reads the order status from my backend; it never treats the iframe's `complete` message as payment proof.
7. Tests for the signer and the webhook verifier.
Nothing OnCharge-secret may appear in `VITE_*` variables or the frontend bundle.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.Plain HTML site + Node or PHP backend#
A checkout page with an iframe, a create-checkout endpoint, a webhook endpoint and shipment reporting, in Node or PHP.
My site is plain HTML/CSS/JS with a [Node.js / PHP: pick one] backend and I want to accept card payments with OnCharge.
Build:
1. Backend: a dependency-free OnCharge request helper that signs requests (Node `crypto` or PHP `hash`/`hash_hmac` + cURL).
2. Backend: `POST /create-checkout` that loads the order (amount, currency, email, shipping address) from my data by id, creates the checkout session with Idempotency-Key = order id, and returns JSON `{ checkoutUrl }`. Also support a no-JavaScript variant that responds with a 303 redirect to the checkout URL.
3. `checkout.html`: calls `/create-checkout`, embeds the checkout in an iframe, listens for messages from https://app.oncharge.io (resize, redirect, complete → order-complete page), and shows a friendly error if the call fails.
4. Backend: a webhook endpoint that reads the raw body (`express.raw` / `file_get_contents('php://input')`), verifies OnCharge-Signature, deduplicates, and updates my order store.
5. Backend: an admin-only endpoint to report carrier + tracking numbers, and one to refund with an Idempotency-Key.
6. A short README: env vars, webhook URL to register in the OnCharge portal, domains to register, and a CSP line (`frame-src https://app.oncharge.io`) if I use CSP.
7. Unit tests for the signer and webhook verifier.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.WooCommerce with a custom theme#
Keep the official plugin, make it work with a custom theme or checkout, and add tracking hooks.
My WooCommerce store uses a custom theme [and a custom/third-party checkout: describe]. I want OnCharge card payments.
Important: OnCharge has an official WooCommerce plugin ("OnCharge Secure Checkout", v1.5.0) that already creates sessions, embeds the checkout (classic and Blocks), handles v2 webhooks at `/?wc-api=oncharge_callback` (verified with its "Webhook Signing Secret" setting, deduplicated by event id), sends shipping addresses and reports tracking numbers. For OnCharge Advertising it also adds the tracking tag, shop events and the product sync (WooCommerce → Settings → Integration → OnCharge Marketing). Do NOT write a new payment gateway. Instead:
1. Check my theme's checkout templates and hooks for anything that breaks the plugin: the payment method area must render `#sc-pay-container`, and theme or plugin JavaScript must not remove or re-render it after the iframe mounts. Fix template overrides that drop WooCommerce payment hooks.
2. If I use a page builder or funnel checkout, make sure the checkout page loads WooCommerce's checkout scripts.
3. If my CSP blocks frames, add `frame-src https://app.oncharge.io`.
4. If my shipping workflow stores tracking numbers somewhere the plugin does not read (it reads WooCommerce Shipment Tracking / Advanced Shipment Tracking, WooCommerce Shipping labels, `_tracking_number` + `_tracking_provider`, and its own "OnCharge delivery" box), add an `oncharge_order_shipments` filter in my theme's functions.php or a small mu-plugin that returns `array( array( 'carrier' => 'UPS', 'tracking_number' => '…' ) )` for the order. Carriers must be USPS, UPS, FedEx or DHL Express.
5. If my store sells research-use-only (RUO) products, tell me to install the "OnCharge Compliance Scanner" plugin and to allow the `oncharge-compliance-scanner/v1` REST routes through my research/age gate.
6. List the plugin settings I must fill in (Store ID, API Key, API Secret, Webhook Signing Secret; leave the base URLs at https://app.oncharge.io), the webhook URL to register and the domains to register in the OnCharge portal.
Only if I explicitly ask for a fully custom flow, follow the API contract below with PHP (wp_remote_request for calls, a REST route for webhooks).
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.Magento 2#
Install and configure the OnCharge_Payments module (beta), or build a custom payment method against the API.
I run a Magento 2 store and want OnCharge card payments.
OnCharge provides a Magento 2 module, `OnCharge_Payments` (Composer package `oncharge/module-payments`, Magento 2.4.4+, PHP 8.1+), in beta (setup: https://oncharge.io/docs/magento, full README: https://oncharge.io/docs/files/magento/README.md). First help me install and configure it: composer require, bin/magento module:enable OnCharge_Payments, setup:upgrade, setup:di:compile, cache:flush, a running Magento cron; settings under Stores > Configuration > Sales > Payment Methods > OnCharge (API key/secret, Payment Action, Checkout Display redirect or embedded, Callback Signing Secret); register https://<store>/oncharge/webhook as the webhook URL and my domain in the OnCharge portal. Check that my theme's checkout renders the payment step correctly.
If I ask for a custom integration instead, build a Magento 2 payment method module that:
1. Creates the OnCharge checkout session server-side when the customer reaches the payment step or places the order (amount from the quote/order, Idempotency-Key = quote or order increment id, shipping address from the order).
2. Renders the checkout iframe in the payment method's checkout UI component (Knockout template), with a postMessage listener (origin https://app.oncharge.io).
3. Exposes a webhook controller (CSRF-exempt, raw body via `$this->getRequest()->getContent()`) that verifies OnCharge-Signature and updates the order/invoice state.
4. Attaches the order id with POST /api/v1/checkout/sessions/{id}/order if the session was created from the quote.
5. Reports tracking with an observer on `sales_order_shipment_track_save_after` (USPS, UPS, FedEx, DHL Express).
6. Implements online refunds from credit memos via POST /api/v1/refunds with an Idempotency-Key.
7. Stores the secret with Magento's encrypted config backend model, never in JS config.
8. For research-use-only (RUO) stores: serves the compliance feed at /oncharge/compliance/{proof,content,reviewer-access}.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.Wix (Velo)#
Set up the OnCharge Velo payment-provider integration (beta) and its HTTP functions.
My store runs on Wix (Wix eCommerce) and I want OnCharge card payments.
OnCharge provides a Wix Velo payment-provider integration in beta (setup: https://oncharge.io/docs/wix, full README: https://oncharge.io/docs/files/wix/README.md). Help me set it up, reusing the package's files rather than rewriting them:
1. Turn on Dev Mode, add the payment provider service plugin named `oncharge`, the backend files (`http-functions.js`, `events.js`, `jobs.config`, `oncharge/`) and the `OnChargeLog` CMS collection (admin-only).
2. Store `oncharge_api_key`, `oncharge_api_secret`, `oncharge_webhook_secret` (and `oncharge_compliance_code` for RUO stores) in the Wix Secrets Manager; they are read only in backend code, never in page code.
3. Make the backend create the checkout session (amount from the Wix order/transaction, Idempotency-Key = the Wix transaction or order id, shipping address for physical products) and return the checkout URL for redirect.
4. Webhooks arrive at `https://<my-site>/_functions/onchargeWebhook` (`post_onchargeWebhook` in `backend/http-functions.js`), which verifies OnCharge-Signature on the raw body and updates the Wix transaction status.
5. Report fulfilment tracking numbers (USPS, UPS, FedEx, DHL Express) to POST /api/v1/shipments.
6. If my store sells research-use-only (RUO) products, the compliance feed is served at https://<my-site>/_functions/onchargeCompliance/{proof,content,reviewer-access}; set that base path when connecting in the OnCharge portal.
7. Tell me which URLs and domains to register in the OnCharge portal.
Use only Velo APIs that exist; if the integration package already does a step, reuse it instead of rewriting it.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.Headless Shopify (Hydrogen)#
A custom checkout page in a Hydrogen/Remix storefront that pays with OnCharge and records the order in Shopify.
I have a headless Shopify storefront built with Hydrogen (React Router/Remix) and want to take card payments with OnCharge on my own checkout page.
Constraints: OnCharge is not a Shopify payments app and cannot appear inside Shopify's hosted checkout. So the payment happens on my storefront's own checkout route, and my server records the order in Shopify afterwards. Before building, remind me to confirm this fits my Shopify plan and terms.
Build:
1. A checkout route (loader/action) that reads the cart from the Storefront API, collects the shipping address, computes the amount server-side, and creates an OnCharge checkout session (Idempotency-Key = cart id + a version if the cart changes; reference = cart id). Keep OnCharge credentials in server-only environment variables (Oxygen/your host), never in client env.
2. A checkout component that embeds the OnCharge iframe with an origin-checked postMessage listener.
3. A resource route `/webhooks/oncharge` (action) that verifies OnCharge-Signature on `await request.text()`, deduplicates, and on payment.captured creates the order in Shopify through the Admin API (for example a draft order completed as paid, with the OnCharge session_id in a note attribute or metafield), then attaches that order id to the session with POST /api/v1/checkout/sessions/{id}/order.
4. A fulfilment hook (Shopify `fulfillments/create` webhook handled by my server) that reports tracking numbers to POST /api/v1/shipments with order_id or session_id.
5. Refund support from my admin tooling via POST /api/v1/refunds with an Idempotency-Key.
6. Tests for signing and webhook verification.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.Webflow, Framer or another site builder (embed)#
A serverless backend for sessions and webhooks plus an embed snippet for the site builder.
My site is built with [Webflow / Framer / Squarespace: pick one], which has no server code. I want to sell [describe products] and take card payments with OnCharge.
Because the API secret can never be in the page, build:
1. A small serverless backend (choose a platform I name, or default to a single Node 18+ project that deploys to any serverless host) with:
- `POST /create-checkout`: takes a product/price id from an allow-list defined on the server (never an amount from the browser), plus the shopper's email and shipping address from a form; creates the OnCharge checkout session (Idempotency-Key = a server-generated order id) and returns `{ checkoutUrl }`.
- `POST /webhooks/oncharge`: verifies OnCharge-Signature on the raw body, deduplicates, stores orders (in a simple database or KV store I choose) and emails me on payment.captured.
- An admin-protected `POST /shipments` to report tracking numbers, and `POST /refunds`.
- CORS limited to my site's domain.
2. An embed snippet (HTML + vanilla JS) for the site builder's custom code element: a form for email and shipping address, a call to `/create-checkout`, and the OnCharge iframe with an origin-checked postMessage listener (or a redirect to the checkout URL if the builder restricts iframes).
3. A README: deploy steps, env vars, the webhook URL and the domains to register in the OnCharge portal (the site's domain must be registered so the checkout can be framed and return_url accepted).
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.Any other stack#
A general prompt for Django, Rails, Laravel, Go, .NET, mobile backends or anything else.
I want to accept card payments with OnCharge in my application. My stack is: [language, framework, database, hosting: fill in]. Read my codebase first and fit the integration to its existing patterns.
Build:
1. A server-side OnCharge client that signs requests as described below, with unit tests using the test vector.
2. A server endpoint or action that creates a checkout session for an order from my database (Idempotency-Key = order id; shipping address for physical goods) and stores the session_id on the order.
3. The checkout UI: a redirect to the checkout URL, or an embedded iframe with an origin-checked postMessage listener.
4. A webhook endpoint that verifies OnCharge-Signature on the raw body, deduplicates event ids and updates order status.
5. Shipment reporting when orders ship, refunds with an Idempotency-Key, and a reconciliation job that re-reads sessions stuck in created/pending for more than an hour.
6. The RUO compliance feed only if I tell you my store sells research-use-only products.
## OnCharge facts (authoritative; full docs: https://oncharge.io/llms-full.txt)
- API base URL: https://app.oncharge.io. Every merchant API call is made from my SERVER. Read credentials from server environment variables: ONCHARGE_API_KEY (oc_key_…), ONCHARGE_API_SECRET (oc_sec_…), ONCHARGE_WEBHOOK_SECRET (oc_cbsec_…).
- Request signing (every call): headers X-Oncharge-Key = API key, X-Oncharge-Timestamp = current Unix time in seconds, X-Oncharge-Signature = lower-case hex HMAC-SHA256 where the KEY is the 64-char lower-case hex SHA-256 of the API secret (used as an ASCII string, not decoded) and the MESSAGE is "{timestamp}.{METHOD}.{path}.{hex sha256(raw body)}". {path} is the URL path WITHOUT the query string (e.g. /api/v1/shipments). For GET/empty bodies hash the empty string. Hash exactly the bytes you send (serialize JSON once). Requests more than 300 s off are rejected.
Test vector: secret oc_sec_example_secret_do_not_use, timestamp 1767225600, POST /api/v1/checkout/sessions, body {"amount":4900,"currency":"USD","reference":"order-1001","return_url":"https://shop.example.com/thanks"} → signature 7b0e1f9370475ae2a926804c0c9927c5f391c8a3c2e09a8071d98891aa01fdc7.
- Create a checkout session: POST /api/v1/checkout/sessions with header Idempotency-Key (my order or cart id). Body: amount (integer, minor units), currency (ISO 4217, e.g. "USD"), reference (my order/cart id), return_url (must be on a domain registered for my store), optional order_id, customer_email, customer_phone (E.164), shipping {name, line1, line2, city, state, postal_code, country} (required for physical goods: payout is released on carrier-confirmed delivery to this address and it cannot be changed later), line_items [{description, quantity, amount_including_tax}], metadata {}. Response 201: {session_id, status, iframe_url, pay_token, created_at, expires_at}. iframe_url is a PATH: checkout URL = "https://app.oncharge.io" + iframe_url. Sessions expire after 30 minutes. A repeat with the same Idempotency-Key within 50 minutes returns the same open session (200).
- Attach the order later (cart-first checkouts): POST /api/v1/checkout/sessions/{session_id}/order {order_id?, shipping?} → {session_id, order_id, shipping_recorded, shipping_on_file}. Values are set once; the address only within 24 h and before tracking is reported.
- Session status: GET /api/v1/checkout/sessions/{session_id} → {session_id, status, amount, currency, order_id, …}. Status: created | pending | authorized | captured (paid) | refused | cancelled | error | expired.
- Show the checkout: (a) redirect the shopper (303) to the checkout URL, or (b) embed it in an <iframe allow="payment"> on a page served over HTTPS from a registered store domain (only registered domains may frame it; a registered localhost works from any port). When embedding, add query parameters embed=1, parent_origin=<your page origin> and embed_nonce=<fresh random 16-128 chars [A-Za-z0-9_-] per load>. The iframe posts messages shaped {source:"oncharge-checkout", version:1, type, sessionId, nonce, height?, status?, message?, url?}: ready {height}, resize {height}, complete {status: captured|authorized}, error {message, status: refused|error}, redirect {url}. Accept a message only if event.origin is the checkout's origin, event.source is the iframe's contentWindow, source/version match and nonce equals your embed_nonce. On ready/resize set the iframe height; on redirect do window.location.assign(url); complete is a UI signal only, not proof of payment. The hosted script https://app.oncharge.io/js/v1/oncharge.js (window.OnCharge.mountCheckout) does all of this.
- SDKs: the npm packages @oncharge/node and @oncharge/js are NOT yet published (do not add them unless I say they are installed); the hosted script https://app.oncharge.io/js/v1/oncharge.js is available. APIs: @oncharge/node: new OnCharge({apiKey, apiSecret, baseUrl?, timeoutMs?}); checkout.sessions.create(params, {idempotencyKey}) → {session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at}; checkout.sessions.retrieve(id); checkout.sessions.attachOrder(id, {order_id, shipping}); shipments.report({session_id|order_id, shipments}); shipments.get(id); refunds.create({session_id, amount, currency, reference}, {idempotencyKey}); OnCharge.webhooks.constructEvent(rawBody, signatureHeader, secret, {toleranceSeconds}) (throws OnChargeSignatureError); OnCharge.webhooks.generateTestHeader({payload, secret}); errors OnChargeApiError {status, code}, OnChargeConnectionError; createComplianceFeed({connectionCode, host, site, listItems({cursor, limit}) → {items, nextCursor, truncated?}, reviewerAccess?: {accountExists, canViewCatalog, ownerConfirmed}, nonceStore?: {claim(nonce, ttlSeconds)}}).handle(Request) → Response. @oncharge/node/next: createWebhookHandler({secret, onEvent(event, {request}), toleranceSeconds?, eventIdStore?: {has, add} | false}) → {POST} (400 bad signature, 500 if onEvent throws, duplicates acknowledged); createComplianceFeedRoute(sameOptions) → {GET}. @oncharge/js: mountCheckout(selectorOrElement, {url, baseUrl?, onReady, onComplete({sessionId, status}), onError({message, status?}), onRedirect({url}) (default navigates the top window), autoResize = true, minHeight = 480, title}) → {iframe, sessionId, destroy()}. @oncharge/js/react: <OnChargeCheckout url onComplete onError onReady onRedirect className style minHeight autoResize title />. Without the npm packages, implement signing and the iframe listener directly as described here.
- Webhooks: OnCharge POSTs JSON to my HTTPS endpoint with headers OnCharge-Event-Id and OnCharge-Signature: "t=<unix seconds>,v1=<hex>". Verify on the RAW body before parsing: v1 must equal hex HMAC-SHA256(key = webhook secret as-is, message = "<t>.<raw body>") (constant-time compare; accept any of several v1 values) and |now − t| ≤ 300. Body: {id, type, created, livemode, data: {session_id, order_id, reference, amount, currency, status} (any data field except session_id may be null), event, status, psp_reference}. Types: payment.pending, payment.authorized (approved, not captured: do not fulfil yet), payment.captured (mark paid), payment.capture_failed, payment.refused, payment.cancelled, payment.expired, refund.succeeded (data.amount = total refunded), refund.failed, chargeback.opened, chargeback.won, chargeback.lost, delivery.confirmed. Respond 2xx within 10 s; non-2xx is retried for 24 h; deduplicate on the event id; acknowledge unknown types. X-Oncharge-Signature on webhooks is a legacy header: do not use it.
- Shipments (physical goods): after the payment is captured, POST /api/v1/shipments {session_id OR order_id, shipments: [{carrier?: "USPS"|"UPS"|"FedEx"|"DHL Express", tracking_number}]} (max 10 per order; repeats are harmless) → {session_id, shipments: [{tracking_number, carrier, status: "accepted"|"rejected", error?, message?}], delivery: {state, hold_reason}}. 409 order_not_paid if not yet captured. GET /api/v1/shipments?session_id=… → {session_id, delivery: {state: not_tracked|awaiting_shipment|in_transit|delivered|on_hold|refunded, hold_reason, delivered_at, shipments: [...]}}. Payout: 1 day after the carrier confirms delivery of every package to the checkout shipping address; orders with nothing to ship: 7 days after payment.
- Refunds: POST /api/v1/refunds {session_id, amount, currency, reference?} with Idempotency-Key = my refund id (captured payments only). Cancel an authorized, uncaptured payment: POST /api/v1/checkout/sessions/{id}/cancel (empty body).
- Errors: JSON {error, message}. 401 missing_auth | invalid_timestamp | timestamp_expired | invalid_key | invalid_signature; 403 store_inactive (store pending until its processing account is open, or suspended: retry later, keys stay valid) | store_checkout_closed (session creation only: store closed to new payments; shipments and refunds still work) | domain_mismatch | global_ban (show message to shopper); 400 validation_error | invalid_return_url; 404 not_found | session_not_found; 409 invalid_state | order_not_paid; 429 rate_limited (wait for X-RateLimit-Reset); 5xx: retry with backoff and the same Idempotency-Key.
- RUO compliance feed (ONLY if my store sells research-use-only products): serve GET <base>/proof, <base>/content, <base>/reviewer-access on my store's own host (default base /.well-known/oncharge-compliance; Magento uses /oncharge/compliance, Wix /_functions/onchargeCompliance, WordPress the scanner plugin), keyed by the one-time connection code occs_<uuid>.<secret> from the OnCharge portal (store it as ONCHARGE_COMPLIANCE_CODE). Follow https://oncharge.io/docs/compliance-feed exactly (signing strings, headers, nonce replay protection, response shapes, test vectors).
## Rules
- Never put the API secret, webhook secret or connection code in browser code, client-exposed env vars (NEXT_PUBLIC_, VITE_, REACT_APP_, PUBLIC_), mobile apps, logs or the repository. Never call the OnCharge API from the browser. Add the variables to .env.example with placeholder values only.
- Compute amounts on the server from my own data; never trust an amount sent by the browser.
- Mark orders paid only from a verified payment.captured webhook or a server-side GET of the session. Never from the return_url visit or a postMessage.
- Verify webhook signatures on the raw body before JSON parsing; respond 400 when invalid.
- Use Idempotency-Key for session creation (order/cart id) and refunds (refund id).
- Send the shipping address for physical goods and report tracking numbers when orders ship.
- Do not invent endpoints, fields, events or SDK methods beyond those above. If something I need is not covered, tell me instead of guessing.
- Write unit tests for the request signer (use the test vector above) and the webhook verifier (valid, tampered body, stale timestamp).
- When you finish, list the env vars to set, the webhook URL to register in the OnCharge merchant portal, and the domain(s) to register for my store.