Skip to content
OnCharge.io
View as Markdown
Developer docs

SDKs

PackageRuns onUse it to
@oncharge/nodeYour server (Node 18.17+, Next.js, serverless)Sign API requests, create and read sessions, report shipments, refund, list payments, payouts and events, read your balance, verify webhooks, serve the RUO compliance feed. ESM and CommonJS, no dependencies.
@oncharge/node/nextNext.js App Router (or any Fetch API route handler)Ready-made webhook and compliance-feed route handlers.
@oncharge/jsThe browserEmbed the checkout iframe with resizing and events.
@oncharge/js/reactReact 17+The <OnChargeCheckout> component.
oncharge.js scriptAny web pagewindow.OnCharge.mountCheckout, no bundler needed: https://app.oncharge.io/js/v1/oncharge.js.
Gateway in @oncharge/nodeYour serverThe gateway API (crypto and Card to Crypto): one wallet per order, hosted and single-provider links, Cash App and Venmo prepared in advance, signed-callback verification.
@oncharge/reactReact 17+<PayAppSwitcher> (Cash App, Venmo and card preloaded side by side), <ProviderPicker> (live providers you switch on and off), <CryptoPayment>, useProviders(), useCryptoQuote(), and <OnChargeCheckout>.

@oncharge/node#

Shell
npm install @oncharge/node
TypeScript
import { OnCharge } from '@oncharge/node';

const oncharge = new OnCharge({
  apiKey: process.env.ONCHARGE_API_KEY!,
  apiSecret: process.env.ONCHARGE_API_SECRET!,
  // baseUrl: 'https://app.oncharge.io',  (default)
  // timeoutMs: 30_000,                    (default, per request)
  // fetch: customFetch,                   (default: the global fetch)
});

Never import @oncharge/node into code that runs in the browser: it needs your API secret.

Checkout sessions#

TypeScript
const session = await oncharge.checkout.sessions.create(
  {
    amount: 4900,
    currency: 'USD',
    reference: 'order-1001',
    return_url: 'https://shop.example.com/checkout/complete',
    order_id: '1001',
    customer_email: 'shopper@example.com',
    shipping: { name: 'Alex Rivera', line1: '500 Market St', city: 'San Francisco', state: 'CA', postal_code: '94105', country: 'US' },
  },
  { idempotencyKey: 'order-1001' },
);
// → { session_id, status, iframe_url, checkout_url, pay_token, created_at, expires_at }

checkout_url is the absolute checkout URL (https://app.oncharge.io + iframe_url). Pass it to the browser.

TypeScript
const current = await oncharge.checkout.sessions.retrieve(session.session_id);
// → { session_id, store_id, order_id, amount, currency, status, psp_reference, risk_decision, risk_score, created_at, updated_at, expires_at }

await oncharge.checkout.sessions.attachOrder(session.session_id, {
  order_id: '1001',
  shipping: { name: 'Alex Rivera', line1: '500 Market St', city: 'San Francisco', state: 'CA', postal_code: '94105', country: 'US' },
});
// → { session_id, order_id, shipping_recorded, shipping_on_file }

Shipments#

TypeScript
await oncharge.shipments.report({
  session_id: session.session_id, // or order_id: '1001'
  shipments: [{ carrier: 'UPS', tracking_number: '1Z999AA10123456784' }],
});
// → { session_id, shipments: [{ tracking_number, carrier, status, error?, message? }], delivery: { state, hold_reason } }

const { delivery } = await oncharge.shipments.get(session.session_id);
// delivery.state: not_tracked | awaiting_shipment | in_transit | delivered | on_hold | refunded

Refunds#

TypeScript
await oncharge.refunds.create(
  { session_id: session.session_id, amount: 1500, currency: 'USD', reference: 'refund-1001-1' },
  { idempotencyKey: 'refund-1001-1' },
);
// → { refund_id, session_id, status, amount, currency }  (idempotent: true on a repeat with the same key)

Payments, payouts and balance#

TypeScript
// Payments on every rail (card, crypto, card_to_crypto), newest first; kind: refund | dispute | swap | all for the others
const { payments, next_cursor } = await oncharge.payments.list({ rail: 'card_to_crypto', status: 'paid', limit: 100 });
const more = next_cursor ? await oncharge.payments.list({ rail: 'card_to_crypto', status: 'paid', cursor: next_cursor }) : null;

// Payouts to your bank, and card totals for a period
const { payouts } = await oncharge.payouts.list({ status: 'failed' });
const totals = await oncharge.payouts.summary({ from: '2026-11-01', to: '2026-11-30' });
// A debit card payout (to the card added in the dashboard): quote, then send what the quote showed.
const { instant_payout: quote } = await oncharge.payouts.instant.retrieve();
if (quote.available) await oncharge.payouts.instant.create({ expectedAmount: quote.amount }, { idempotencyKey: `instant-${Date.now()}` });

// Where your money is
const balance = await oncharge.balance.retrieve();

// Ways to pay beyond cards (bank debit, Cash App Pay, Klarna, Affirm, Afterpay) and their status for your store
const { methods } = await oncharge.paymentMethods.list();

Every list is newest first and paged with next_cursor (pass it as cursor). Entries carry OnCharge references (ocpay_…, ocrfd_…, ocdsp_…, ocswp_…) and plain statuses. See the API reference.

Events#

TypeScript
// Every webhook event of the last 30 days, exactly as your endpoints received it, a page at a time
let cursor;
do {
  const page = await oncharge.events.list({ type: 'payout.*', limit: 100, cursor }); // the same filter on every page
  for (const event of page.events) await handle(event);
  cursor = page.next_cursor ?? undefined;
} while (cursor);
const event = await oncharge.events.retrieve('evt_…');
await oncharge.events.replay(event.id, { endpointId: '…' }); // to one of your endpoints again, same id

Invoices#

TypeScript
const invoice = await oncharge.invoices.create(
  {
    customer: { name: 'Ada Lovelace', email: 'ada@example.com' },
    lines: [{ description: 'Consulting', quantity: 10, unit_amount: 15000, tax_rate: 8.875 }],
    days_until_due: 14,
    send: true, // finalize and email it; `finalize: true` only numbers it
  },
  { idempotencyKey: 'invoice-1001' },
);
// → { id, number: 'INV-0001', status: 'open', hosted_url, total, amount_remaining, … }

await oncharge.invoices.list({ status: 'overdue' });             // → { invoices, next_cursor }
await oncharge.invoices.retrieve(invoice.id);
await oncharge.invoices.update(draftId, { memo: 'Thanks' });       // drafts only
await oncharge.invoices.finalize(draftId, { send: true });
await oncharge.invoices.send(invoice.id);
await oncharge.invoices.markPaid(invoice.id, { note: 'Bank transfer' });
await oncharge.invoices.voidInvoice(invoice.id, { reason: 'Duplicate' });
await oncharge.invoices.createCreditNote(invoice.id, { amount: 5000, reason: 'order_change', refund: true }, { idempotencyKey: 'cn-1001' });
await oncharge.invoices.refundExtraPayment(invoice.id, { payment_reference: 'ocpay_…' }); // an extra payment, once
await oncharge.invoices.del(draftId);                              // drafts only

See Invoices.

Subscriptions#

TypeScript
const plan = await oncharge.plans.create(
  { name: 'Monthly box', amount: 3000, currency: 'USD', interval: 'month', trial_days: 14, intro: { amount: 1500, periods: 2 } },
  { idempotencyKey: 'plan-monthly-box' },
);
// → { id, object: 'plan', interval_text: 'month', active: true, … }; an add-on is { kind: 'addon', name, amount }

await oncharge.plans.list({ include_archived: true });             // → { data }
await oncharge.plans.retrieve(plan.id);
await oncharge.plans.update(plan.id, { active: false });           // name, description, metadata or archive; never the price
await oncharge.plans.createPaymentLink(plan.id, { title: 'Join' }); // → { id, code, url, plan_id }

// A hosted sign-up page: the customer agrees to the recurring terms and enters a card on OnCharge's page
const signup = await oncharge.subscriptions.checkout({ plan_id: plan.id, customer_email: 'ada@example.com' }, { idempotencyKey: 'signup-ada' });
// → { id, status: 'incomplete', url, sign_up_expires_at, … }
// Or for an existing customer: OnCharge emails them the sign-up link (never returned)
await oncharge.subscriptions.create({ customer_id: customerId, plan_id: plan.id }, { idempotencyKey: 'sub-1001' });

await oncharge.subscriptions.list({ status: 'past_due', limit: 50 });   // → { data, has_more }; page with starting_after
await oncharge.subscriptions.retrieve(signup.id);                       // with billings and history
await oncharge.subscriptions.update(signup.id, { payment_method_id: cardId }); // another of the customer's saved cards
await oncharge.subscriptions.change(signup.id, { plan_id: yearlyPlanId, proration: 'next_period' });
await oncharge.subscriptions.pause(signup.id, { periods: 2 });
await oncharge.subscriptions.resume(signup.id);
await oncharge.subscriptions.cancel(signup.id);                         // at the end of the period; { at_period_end: false } for now
await oncharge.subscriptions.retry(signup.id);                          // a past-due subscription, now

plans.update and subscriptions.update are PATCH requests, signed like the others. Subscriptions are not available yet: until they are, these calls answer 404 not_found. See Subscriptions.

Errors#

ClassWhenUseful fields
OnChargeApiErrorOnCharge answered with an error.status, code (OnCharge's error, e.g. validation_error, invalid_signature), message, body
OnChargeConnectionErrorNo answer: network failure or timeout.cause
OnChargeSignatureErrorA webhook signature is missing, malformed, too old or wrong.code
OnChargeErrorBase class of all of the above (also thrown for bad options).

Retry 429, 5xx and connection errors with backoff and the same idempotency key.

Webhooks#

TypeScript
const event = OnCharge.webhooks.constructEvent(rawBody, request.headers.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET!, {
  toleranceSeconds: 300, // default
});
// Throws OnChargeSignatureError (code: missing_signature | invalid_signature_header | timestamp_outside_tolerance
//   | signature_mismatch | invalid_payload). Returns the typed event.

rawBody is the request body exactly as received (a string or bytes). Also available:

  • OnCharge.webhooks.verifySignature(rawBody, header, secret, options?) checks without parsing.
  • OnCharge.webhooks.generateTestHeader({ payload, secret, timestamp? }) returns a valid OnCharge-Signature for your tests.
  • OnCharge.webhooks.SIGNATURE_HEADER (OnCharge-Signature) and EVENT_ID_HEADER (OnCharge-Event-Id).

The same functions are exported by name (constructEvent, verifyWebhookSignature, generateTestHeader), with the OnChargeEvent and OnChargeEventType types and EVENT_TYPES (every type, for an endpoint's event list). OnChargeEvent is typed per event: switch on event.type and event.data has that event's shape, data.rail included. See Webhooks for the event types.

TypeScript
switch (event.type) {
  case 'payment.captured':
    if (event.data.session_id === null) {
      // crypto or Card to Crypto paid to your wallet: event.data.rail, .method, .coin_amount, .payout_tx
    }
    break;
  case 'payout.failed':
    console.log(event.data.problem?.reason);
    break;
}

RUO compliance feed#

TypeScript
import { createComplianceFeed } from '@oncharge/node';

const feed = createComplianceFeed({
  connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE, // occs_<id>.<secret>; unset → every endpoint answers 409 (not connected)
  host: 'shop.example.com', // exactly as connected
  site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/', terms_page_url: 'https://shop.example.com/terms' },
  async listItems({ cursor, limit }) {
    const items = await loadPublishedCatalog(cursor, limit); // products (gated ones too), pages, posts
    return { items, nextCursor: items.length === limit ? cursor + limit : null };
  },
  reviewerAccess: async () => ({ accountExists: true, canViewCatalog: true, ownerConfirmed: true }), // optional
});

const response = await feed.handle(request); // Request → Response
OptionNotes
connectionCodeThe one-time occs_… code. Or pass connectionId and signingKey (hex SHA-256 of the secret) instead.
hostThe bare host name as connected in the portal.
site{ name, tagline?, home_url, terms_page_url?, privacy_policy_url?, refund_page_url?, shipping_page_url?, contact_page_url? }, or a function returning it.
listItems({ cursor, limit })Returns { items, nextCursor, truncated? }; nextCursor is null on the last page.
reviewerAccess{ accountExists, canViewCatalog, ownerConfirmed }, or a function returning it.
nonceStore{ claim(nonce, ttlSeconds) } returning false for a nonce already seen. Default: in memory, per process; use shared storage when you run several instances (createMemoryNonceStore() is exported).
versionReported as plugin_version.

The endpoint is chosen from the last path segment (proof, content, reviewer-access), so route every request under your base path to feed.handle. See RUO compliance feed.

Low-level signing#

signedRequestHeaders({ apiKey, apiSecret, method, path, body, timestamp? }) returns the three X-Oncharge-* headers, for endpoints the client does not wrap (disputes, risk). signRequest({ apiSecret, timestamp, method, path, body }) and requestSigningString({ timestamp, method, path, body }) expose the steps. Pass path without the query string and body exactly as you will send it. See Authentication.

@oncharge/node/next#

app/api/webhooks/oncharge/route.ts
import { createWebhookHandler } from '@oncharge/node/next';

export const { POST } = createWebhookHandler({
  secret: process.env.ONCHARGE_WEBHOOK_SECRET,
  async onEvent(event, { request }) {
    // event.type, event.data.session_id, event.data.order_id, …
    // throw to have OnCharge retry later
  },
  // toleranceSeconds: 300,
  // eventIdStore: { has(id), add(id) } | false,
});
OptionNotes
secretYour webhook signing secret. If it is missing the handler answers 500 {"error":"not_configured"}.
onEvent(event, { request })Called once per verified event. Throw to make the handler answer 500, so OnCharge retries.
toleranceSecondsDefault 300.
eventIdStoreRemembers handled event IDs so retries are acknowledged without calling onEvent again. Default: in memory (createMemoryEventIdStore()); pass a store backed by your database or Redis when you run several instances, or false to turn it off.

Bad signatures get 400 {"error":"<code>"}; handled and duplicate events get 200.

app/.well-known/oncharge-compliance/[route]/route.ts
import { createComplianceFeedRoute } from '@oncharge/node/next';

export const { GET } = createComplianceFeedRoute({
  connectionCode: process.env.ONCHARGE_COMPLIANCE_CODE,
  host: 'shop.example.com',
  site: { name: 'Example Research Supply', home_url: 'https://shop.example.com/' },
  async listItems({ cursor, limit }) {
    const items = await loadPublishedCatalog(cursor, limit);
    return { items, nextCursor: items.length === limit ? cursor + limit : null };
  },
});

createComplianceFeedRoute takes the same options as createComplianceFeed.

@oncharge/js#

Shell
npm install @oncharge/js
TypeScript
import { mountCheckout } from '@oncharge/js';

const checkout = mountCheckout('#oncharge-checkout', {
  url: checkoutUrl, // session.checkout_url, or iframe_url with baseUrl
  onReady: () => {},
  onComplete: ({ sessionId, status }) => {}, // status: 'captured' | 'authorized'
  onError: ({ message, status }) => {}, // status: 'refused' | 'error' (optional)
  onRedirect: ({ url }) => window.location.assign(url), // default: navigate the top window
  autoResize: true, // default
  minHeight: 480, // default
});

checkout.iframe; // the HTMLIFrameElement
checkout.sessionId; // parsed from the URL
checkout.destroy();

mountCheckout adds embed=1, parent_origin and a fresh embed_nonce to the URL, and accepts a message only from that iframe, at the checkout's origin, with that nonce. It throws if the URL is not HTTPS (HTTP is allowed only for localhost). The same function is available without a bundler:

HTML
<script src="https://app.oncharge.io/js/v1/oncharge.js"></script>
<script>
  window.OnCharge.mountCheckout('#oncharge-checkout', { url: CHECKOUT_URL });
</script>

@oncharge/js/react#

TSX
import { OnChargeCheckout } from '@oncharge/js/react';

<OnChargeCheckout
  url={checkoutUrl}
  onComplete={({ sessionId, status }) => {}}
  onError={({ message }) => {}}
  onReady={() => {}}
  onRedirect={({ url }) => window.location.assign(url)}
  className="w-full"
  minHeight={480}
/>;

Props: url, baseUrl, onReady, onComplete, onError, onRedirect, className, style, minHeight, autoResize, title. The iframe is remounted only when url, baseUrl, minHeight, autoResize or title change. It is a client component ('use client').

See Messages from the checkout for the protocol underneath.

Other languages#

There is no official PHP or Python SDK. The Authentication examples are complete, dependency-free clients, and the OpenAPI spec works with OpenAPI code generators (add the signing headers in a request hook).

Gateway API#

Gateway (in @oncharge/node) calls the Gateway API. Give it your gateway key (Payments → Gateway API in the dashboard): wallets are then created with the callback relay, so OnCharge signs every callback it sends you.

server
import { Gateway, callbackToken, verifyCallbackToken, verifyRelayedCallback, parseGatewayCallback } from '@oncharge/node';

const gateway = new Gateway({ key: process.env.ONCHARGE_GATEWAY_KEY });
const callback = `https://shop.example.com/oncharge/callback?order=${order.id}&token=${callbackToken(process.env.ONCHARGE_CALLBACK_SECRET!, order.id)}`;
const wallet = await gateway.createWallet(process.env.ONCHARGE_PAYOUT_WALLET!, callback);

const hosted = gateway.checkoutUrl(wallet, { amount: '49.90', email });          // every available method, card included
const card = gateway.checkoutUrl(wallet, { amount: '49.90', email, provider: 'card' }); // the card page alone
const payApps = await gateway.preparePayApps(wallet, { amount: '49.90', email, providers: ['cashapp', 'venmo', 'card'] });

preparePayApps builds the Cash App, Venmo and card links for the same wallet and resolves Cash App to its own invoice (with the QR code) in parallel, so the payment page opens without a redirect; the card page opens in a new tab (frame is null). A payment through any of them, or through the hosted checkout, completes the order. The card page's id is card.

With a gateway key, each payment also reaches your webhook endpoints as payment.pending and payment.captured with data.rail crypto or card_to_crypto, and appears in oncharge.payments.list().

In the callback, verify OnCharge's signature over the full URL as it arrived, then your token:

callback
const rawQuery = req.originalUrl.split('?')[1] ?? '';
const url = `https://shop.example.com/oncharge/callback?${rawQuery}`; // your registered URL plus the raw query
if (!verifyRelayedCallback({ url, signature: req.get('X-OnCharge-Signature'), signingSecret: process.env.ONCHARGE_SIGNING_SECRET! })) return res.sendStatus(403);
const payment = parseGatewayCallback(rawQuery);
if (!verifyCallbackToken(process.env.ONCHARGE_CALLBACK_SECRET!, payment.get('order')!, payment.get('token'))) return res.sendStatus(403);

@oncharge/react#

Shell
npm install @oncharge/react
Cash App and Venmo, preloaded
'use client';
import { PayAppSwitcher } from '@oncharge/react';

// payApps: from gateway.preparePayApps() on your server
<PayAppSwitcher options={payApps} onSwitch={(provider) => saveChoice(provider)} />;

Every frame loads at once (preconnected, eager), the others behind their tabs, so switching is instant.

Providers you switch on and off
import { ProviderPicker, checkoutUrl } from '@oncharge/react';

<ProviderPicker
  enabled={['applepay', 'googlepay', 'cashapp', 'venmo']}
  amount={49.9}
  onSelect={(p) => (location.href = checkoutUrl(addressIn, { amount: '49.90', email, provider: p.id }))}
/>;

<CryptoPayment coin address amount /> shows a QR code, the exact amount and a copyable address; useCryptoQuote(coin, amount) prices the order. <OnChargeCheckout url /> embeds the Secure Checkout card form.