# Gateway API

The OnCharge Gateway API takes Crypto payments and Card to Crypto (card, wallet and pay-app payments paid out in USDC) and forwards each one to a wallet you own as soon as it settles. There is no payout schedule: every payout is split on-chain in one transaction. Create wallets with a [gateway key](#accounts) from your OnCharge dashboard (open as soon as you sign up): OnCharge then signs every callback it sends you and shows each payment in your dashboard.

| Host | Use |
|---|---|
| `https://capi.oncharge.io` | API calls from your server |
| `https://ccheckout.oncharge.io` | Checkout pages you send the customer to |

**Split:** 94% of each payment to your wallet, 5% to OnCharge, 1% network gateway fee. Card to Crypto payments carry the payment method's own published fee, deducted before the payout, and blockchain network fees are additional. Check the live configuration at [`GET /healthz`](#health).

**Card to Crypto payments** arrive as USDC on Polygon. **Crypto payments** arrive in the coin the customer paid.

Looking for the WooCommerce plugin instead? See [Crypto payments plugin](https://oncharge.io/docs/crypto-plugin). For card processing through your own merchant account, see the [Quickstart](https://oncharge.io/docs/quickstart).

## How a payment works {#flow}

1. **Create a wallet for the order** on your server, with your gateway key, your payout wallet and a callback URL unique to the order.
2. **Send the customer to pay** on the hosted checkout, or show a crypto address on your own page.
3. **Receive the callback** when the payment arrives. Verify OnCharge's signature, then fulfil the order.

```bash title="The whole flow with curl"
# 1. Wallet for order 1001, with your gateway key; its callbacks come through OnCharge
curl -G 'https://capi.oncharge.io/control/wallet.php' \
  -H 'X-OnCharge-Key: ocg_…' \
  --data-urlencode 'address=0xYourPolygonUsdcWallet' \
  --data-urlencode 'callback=https://shop.example.com/oncharge/callback?order=1001&token=9f2c41d7' \
  --data-urlencode 'oncharge_relay=1'

# 2. Send the customer to the address_in it returned (already URL-encoded)
https://ccheckout.oncharge.io/pay.php?address=ADDRESS_IN&amount=49.90&email=shopper%40example.com&currency=USD
```

## Cards, wallets and pay apps {#cards}

Card to Crypto: customers pay by card, Apple Pay, Google Pay, Cash App, Venmo and more. The payment arrives as USDC, and the gateway forwards it to your Polygon wallet.

### Create a payment wallet {#card-wallet}

`GET https://capi.oncharge.io/control/wallet.php`

| Parameter | Required | Description |
|---|---|---|
| `address` | yes | Your USDC payout wallet on Polygon (`0x…`, an address you control). |
| `callback` | yes | URL-encoded callback URL, unique to this order. Include your order id and a secret token. |
| `oncharge_relay` | yes | `1`: callbacks come through OnCharge, signed with your key ([Callbacks](#callbacks)). Send your gateway key as the `X-OnCharge-Key` header. |

| Response field | Description |
|---|---|
| `address_in` | Encrypted wallet reference. Pass it to the checkout page as `address`. It is already URL-encoded: append it as it is. |
| `polygon_address_in` | The order's Polygon deposit address. Matches `address_in` in the callback. |
| `callback_url` | The callback URL as registered. |
| `ipn_token` | Token for occasional status reads. Store it with the order. |

The same callback URL always returns the same wallet, so rebuilding a checkout link is safe.

```js title="Node.js"
const callbackUrl = `https://shop.example.com/oncharge/callback?order=${order.id}&token=${order.callbackToken}`;
const url = new URL('https://capi.oncharge.io/control/wallet.php');
url.searchParams.set('address', process.env.ONCHARGE_PAYOUT_WALLET);
url.searchParams.set('callback', callbackUrl);
url.searchParams.set('oncharge_relay', '1');
const wallet = await fetch(url, { headers: { 'X-OnCharge-Key': process.env.ONCHARGE_GATEWAY_KEY } }).then((r) => r.json());
```

```php title="PHP"
$wallet = json_decode(file_get_contents('https://capi.oncharge.io/control/wallet.php?' . http_build_query([
    'address'        => getenv('ONCHARGE_PAYOUT_WALLET'),
    'callback'       => $callbackUrl,
    'oncharge_relay' => '1',
]), false, stream_context_create(['http' => ['header' => 'X-OnCharge-Key: ' . getenv('ONCHARGE_GATEWAY_KEY')]])), true);
```

### Hosted checkout {#pay}

`GET https://ccheckout.oncharge.io/pay.php` — a page you send the customer to. It lists every payment method available for the customer's country, amount and currency.

| Parameter | Required | Description |
|---|---|---|
| `address` | yes | `address_in` from the wallet, as returned. |
| `amount` | yes | Order total. |
| `email` | yes | The customer's email address. |
| `currency` | yes | Three-letter currency code. Some methods accept USD only: convert first with [Convert to USD](#convert-usd). |
| `logo` | no | URL of your logo. |
| `background`, `theme`, `button` | no | Page, accent and button colours: hex codes or CSS colour names. |

### Send the customer to one method {#process-payment}

`GET https://ccheckout.oncharge.io/process-payment.php` — skips the method list and opens one payment method. Use it to build your own buttons and choose exactly which methods your checkout offers.

| Parameter | Required | Description |
|---|---|---|
| `address` | yes | `address_in` from the wallet. |
| `amount` | yes | Order total. |
| `provider` | yes | Method id from [List payment methods](#providers), such as `cashapp`, `venmo`, `applepay` or `googlepay`, or `card` for the card page. |
| `email` | yes | The customer's email address. |
| `currency` | yes | Three-letter currency code. |

```html title="Your own buttons"
<a href="https://ccheckout.oncharge.io/process-payment.php?address={{address_in}}&amount=49.90&provider=cashapp&email={{email}}&currency=USD">Pay with Cash App</a>
<a href="https://ccheckout.oncharge.io/process-payment.php?address={{address_in}}&amount=49.90&provider=applepay&email={{email}}&currency=USD">Pay with Apple Pay</a>
<a href="https://ccheckout.oncharge.io/process-payment.php?address={{address_in}}&amount=49.90&provider=card&email={{email}}&currency=USD" target="_blank">Pay by card</a>
<a href="https://ccheckout.oncharge.io/pay.php?address={{address_in}}&amount=49.90&email={{email}}&currency=USD">More ways to pay</a>
```

Check each method's minimum order and region in [List payment methods](#providers) before showing its button. The amount is visible to the customer: always compare what arrives with what you expect.

### Cash App and Venmo side by side {#pay-apps}

All the Card to Crypto methods of one wallet pay the same deposit address, so you can offer Cash App, Venmo and card for one order without creating another wallet. For the fastest page:

1. Build the Cash App, Venmo and card links from the same `address_in` (`provider=cashapp`, `provider=venmo`, `provider=card`).
2. On your server, resolve the Cash App link to Cash App's native invoice (the page with the QR code) once, so the browser skips a redirect. `Gateway.preparePayApps()` does this for you.
3. Load both frames at once and keep the inactive one behind its tab. Add `<link rel="preconnect">` for `ccheckout.oncharge.io` on the checkout page.
4. Card opens a licensed card page in a new tab.

`Gateway.preparePayApps()` in [`@oncharge/node`](https://oncharge.io/docs/sdks#gateway) does steps 1 and 2, and `<PayAppSwitcher>` in [`@oncharge/react`](https://oncharge.io/docs/sdks#react) does 3 and 4. Tell customers to pay once: a payment through either page completes the order.

Cash App's native invoice is the one payment page that keeps its own name: it is served by Cash App's payment partner on its own host and cannot be renamed. Every other page is on `ccheckout.oncharge.io`.

## Crypto on your own page {#crypto}

Show the customer an address, an exact amount and a QR code. Payments are forwarded to your wallet in the same coin.

Coins are written as paths: `btc`, `eth`, `sol`, `ltc`, `doge`, `xrp`, `trc20/usdt`, `polygon/usdc`, `bep20/usdt`, `base/usdc` and so on. [List coins](#coins) returns them all. Use a payout wallet on the coin's network: one EVM address covers Ethereum, BNB Chain, Polygon, Base, Arbitrum, Optimism, Avalanche, Linea and other EVM networks.

### Create a crypto deposit address {#crypto-wallet}

`GET https://capi.oncharge.io/crypto/{coin}/wallet.php`

| Parameter | Required | Description |
|---|---|---|
| `address` | yes | Your payout wallet on the coin's network. For XRP: `r…` or `r…?dt=TAG`. |
| `callback` | yes | URL-encoded callback URL, unique to this order. |
| `pending` | no | `1` also sends a callback (with `pending=1`) when the transaction is first seen. |
| `confirmations` | no | Confirmations required before the confirmed callback (at least 1). |

Returns `address_in` (the address the customer pays), `callback_url` and `ipn_token`.

### Price an order in crypto {#crypto-convert}

`GET https://capi.oncharge.io/crypto/{coin}/convert.php?value=100&from=usd`

Returns `value_coin` (the amount to request) and `exchange_rate`.

```json title="Response"
{ "status": "success", "value_coin": "0.00166672", "exchange_rate": "0.0000166672" }
```

### QR code {#qrcode}

`GET https://capi.oncharge.io/crypto/{coin}/qrcode.php?address={address_in}&amount={value_coin}`

Returns `qr_code`, a base64 PNG (`data:image/png;base64,…`). `amount` is optional.

## Hosted crypto checkout {#hosted}

One link, every coin: the customer chooses the coin on a hosted page.

### Create a hosted crypto checkout {#multi-hosted}

`POST https://capi.oncharge.io/crypto/multi-hosted-wallet.php` with a JSON body. Give one payout wallet per network you accept; networks left out are not offered.

| Field | Required | Description |
|---|---|---|
| `evm`, `btc`, `bitcoincash`, `ltc`, `doge`, `solana`, `trc20`, `xmr`, `zec`, `ton`, `xrp` | at least one | Your wallet on each network you accept. `evm` covers ETH, USDT, USDC and tokens on EVM networks. |
| `fiat_amount` | yes | Order total. |
| `fiat_currency` | yes | Order currency, such as `USD`. |
| `callback` | yes | Callback URL unique to this order. |

Returns `payment_token`, `callback_url` and `ipn_token`.

```bash title="curl"
curl -X POST 'https://capi.oncharge.io/crypto/multi-hosted-wallet.php' \
  -H 'Content-Type: application/json' \
  -d '{"evm":"0xYourEvmWallet","btc":"bc1qYourBitcoinWallet","fiat_amount":49.9,"fiat_currency":"USD","callback":"https://shop.example.com/oncharge/callback?order=1001&token=9f2c41d7"}'
```

### Hosted crypto page {#hosted-page}

`GET https://ccheckout.oncharge.io/crypto/hosted.php?payment_token={payment_token}&add_fees=1`

`add_fees=1` adds the network fee to what the customer pays. The `logo`, `background`, `theme` and `button` branding options work here too.

## Rates, coins and payment methods {#data}

Read-only endpoints for building your checkout. They are safe to call from a browser (CORS is open).

### List payment methods {#providers}

`GET https://capi.oncharge.io/control/provider-status/`

Returns `providers[]` with `id` (the value for `provider`), `status` (`active` when available), `minimum_amount`, `minimum_currency` and `fees` (the method's published fee). Label each button in your own words (Cash App, Apple Pay, Card…).

### List coins {#coins}

`GET https://capi.oncharge.io/crypto/info.php`

Every supported coin and token, grouped by network, with its logo and minimum payment. Minimums reflect the split payout (two recipients), so they are higher than for a single-wallet payout.

### Coin details {#coin-info}

`GET https://capi.oncharge.io/crypto/{coin}/info.php` returns `coin`, `minimum` and `prices` (one price per fiat currency).

### Network fee estimate {#fees}

`GET https://capi.oncharge.io/crypto/{coin}/fees.php` returns `estimated_cost` (in the coin) and `estimated_cost_currency` (in each fiat currency).

### Convert to USD {#convert-usd}

`GET https://capi.oncharge.io/control/convert.php?value=49.90&from=eur` returns `value_coin` (in USD) and `exchange_rate`.

### Health {#health}

`GET https://capi.oncharge.io/healthz`

```json title="Response"
{ "service": "oncharge-gateway", "status": "configured", "api": "capi.oncharge.io", "checkout": "ccheckout.oncharge.io", "commission_percent": 5, "merchant_percent": 94, "sub_affiliates": true }
```

## Payment status {#status}

For occasional checks only: update orders from the [callback](#callbacks), not by polling.

| Endpoint | Parameters |
|---|---|
| `GET /control/payment-status.php` | `ipn_token` (card, wallet and pay-app payments) |
| `GET /crypto/payment-status.php` | `ipn_token`, `ticker` (the coin path) |
| `GET /crypto/control/swap-status.php` | `exchange_id` |

Card status returns `status` (`paid` or `unpaid`), `value_coin`, `txid_out` and `coin`.

These reads are rate limited upstream. The gateway keeps final answers for 24 hours and in-progress answers for 30 seconds, so repeated reads of one payment do not add to the limit. A `429` response carries `Retry-After`: wait that long before asking again. Every status response carries `X-OnCharge-Status-Cache` (`miss`, `hit`, `shared` or `bypass`).

## Swaps {#swaps}

The customer sends one coin and your wallet receives another.

| Endpoint | Parameters |
|---|---|
| `GET /crypto/swap-info.php` | none: lists swappable coins as paths |
| `GET /crypto/{from}/swap.php` | `ticker_to`, `address` (your receiving wallet), `amount`, `callback` |
| `GET /crypto/control/swap-status.php` | `exchange_id` (the `data.id` that `swap.php` returned) |

`swap.php` returns `data`: the exchange's `id`, `status`, `amount_from`, `amount_to` (an estimate: the rate floats), `exchange_address_wallet` (where to send the coins) and `expires_at`. Its `status` moves through `waiting`, `confirming`, `exchanging` and `sending` to `finished`, or ends `failed` or `expired`.

Every swap call creates a new exchange: never retry it automatically. Follow it with `swap-status.php`, or with the callback you passed.

## Partner splits {#partners}

Agencies and platforms can earn on the payments of merchants they bring. The merchant's 94% is shared between the merchant and your wallet; OnCharge's 5% and the 1% gateway fee are unchanged.

`GET https://capi.oncharge.io/control/custom-sub-affiliate.php` (also available as `/set-affiliate.php`)

| Parameter | Required | Description |
|---|---|---|
| `address` | yes | The merchant's Polygon USDC wallet. |
| `callback` | yes | Callback URL unique to this order. |
| `merchant_fee` | yes | Merchant share, such as `0.92`. |
| `sub_affiliate_fee` | yes | Your share, such as `0.02`. `merchant_fee + sub_affiliate_fee` must equal `0.94`. |
| `sub_affiliate` | yes | Your EVM wallet. |

Shares that do not add up, or a missing wallet, are refused with HTTP 400.

## Callbacks {#callbacks}

When a payment arrives, OnCharge requests your callback URL (`GET`) with your own parameters plus the payment data, for wallets created with your gateway key and `oncharge_relay=1`:

| Parameter | Description |
|---|---|
| `value_coin` | Amount received. Card to Crypto payments arrive in USDC after the method's own fee. |
| `coin` | Coin received, such as `polygon_usdc`, `btc` or `trc20_usdt`. |
| `txid_in` | Transaction that paid the order. Credit each one once. |
| `txid_out` | Transaction that forwarded the funds to you. |
| `address_in` | The order's deposit address. |
| `value_forwarded_coin` | Total forwarded to all payout wallets. |
| `address_out` | Share received by each payout wallet. |
| `pending` | `1` on an unconfirmed crypto notice. Do not ship yet. |

### Verify the signature {#signature}

Every callback OnCharge sends you is signed with your gateway key's signing secret:

- `X-OnCharge-Signature: t=<unix time>,v1=<hex>`: an HMAC-SHA256, with your signing secret (`ocgs_…`), of `<t>.<the full callback URL as it arrived>`.
- `X-OnCharge-Event-Id`: the payment. A repeat has the same id.

The full URL is **your callback URL as registered** (scheme, host and path) followed by `?` and **the raw query string exactly as it arrived**. Read the raw query from the request line; do not rebuild it from parsed parameters, because one changed byte invalidates the signature. Reject a signature that does not match, or a `t` more than five minutes old.

```js title="Node.js (Express)"
import { createHmac, timingSafeEqual } from 'node:crypto';

const CALLBACK_URL = 'https://shop.example.com/oncharge/callback'; // as registered

app.get('/oncharge/callback', async (req, res) => {
  const rawQuery = req.originalUrl.split('?')[1] ?? '';
  const { t = '', v1 = '' } = Object.fromEntries(String(req.get('X-OnCharge-Signature') ?? '').split(',').map((p) => p.trim().split('=')));
  const expected = createHmac('sha256', process.env.ONCHARGE_SIGNING_SECRET).update(`${t}.${CALLBACK_URL}?${rawQuery}`).digest('hex');
  const fresh = Math.abs(Date.now() / 1000 - Number(t)) <= 300;
  if (!fresh || v1.length !== expected.length || !timingSafeEqual(Buffer.from(v1), Buffer.from(expected))) return res.sendStatus(403);
  // …check your order token, ignore pending=1, credit txid_in once, compare coin and amount…
  res.send('ok');
});
```

```php title="PHP"
$raw = $_SERVER['QUERY_STRING'] ?? '';
parse_str(str_replace(',', '&', str_replace(' ', '', $_SERVER['HTTP_X_ONCHARGE_SIGNATURE'] ?? '')), $sig);
$t = (string) ($sig['t'] ?? '');
$expected = hash_hmac('sha256', $t . '.https://shop.example.com/oncharge/callback?' . $raw, (string) getenv('ONCHARGE_SIGNING_SECRET'));
if ($t === '' || abs(time() - (int) $t) > 300 || !hash_equals($expected, (string) ($sig['v1'] ?? ''))) {
    http_response_code(403);
    exit;
}
```

### Then check the payment {#checks}

1. **Your token.** Anyone can create a wallet whose callback names one of your orders. A token only your server can produce (for example an HMAC of the order id) proves the order reference is yours.
2. **Pending notices.** Ignore `pending=1` until the confirmed callback arrives.
3. **Each transaction once.** Callbacks repeat: answer `200` and credit each `txid_in` once.
4. **Coin, address and amount.** Compare `coin`, `address_in` and `value_coin` with the order before releasing goods. Card to Crypto payments arrive after the method's own fee, so decide what share of the total you accept.

Never use the gateway's parameter names (`value_coin`, `coin`, `txid_in`, `txid_out`, `address_in`, `value_forwarded_coin`, `address_out`, `pending`) in your own callback URL. When a name appears twice, use the last value: the gateway appends its parameters after yours.

## Accounts and keys {#accounts}

Create wallets with a **gateway key**: OnCharge then signs the callbacks it sends you, and every wallet and payment shows up in your dashboard under **Payments**, next to your other payments. Keys need no verification: create one as soon as you sign up.

Every payout wallet and swap destination a key is used with is screened against the OFAC sanctions list. A listed wallet switches the key off, and the dashboard says so. For a store's first 30 days, a card payment over $500, or over $2,000 of card payments in 24 hours, pauses the store's Card to Crypto in the plugin until the 24 hours have room again; it turns back on by itself.

1. In the dashboard, open **Payments → Gateway API** and select **Create key**. Copy the key (`ocg_…`) and its signing secret (`ocgs_…`): they are shown once.
2. Send the key with every call, as a header or a query parameter:

```bash title="A wallet linked to your account"
curl -G 'https://capi.oncharge.io/control/wallet.php' \
  -H 'X-OnCharge-Key: ocg_…' \
  --data-urlencode 'address=0xYourPolygonUsdcWallet' \
  --data-urlencode 'callback=https://shop.example.com/oncharge/callback?order=1001&token=9f2c41d7'
```

| Parameter | Where | Description |
|---|---|---|
| `X-OnCharge-Key` | header | Your gateway key. Or pass it as the `oncharge_key` query parameter. |
| `oncharge_relay=1` | query | Send this wallet's callbacks through OnCharge, signed with your key (see [Callback relay](#relay)). Or the `X-OnCharge-Relay: 1` header. |

- The key is removed before the request leaves OnCharge: the payment network never sees it.
- Payments appear when OnCharge sees them: through the relay, or when you read a payment's status through the gateway.
- Calls without a key, or with a revoked key, work exactly as before; they just do not show up in your dashboard.
- Keep the key on your server. Revoke it in the dashboard at any time.

## Callback relay {#relay}

Add `oncharge_relay=1` (with your key) when you create a wallet, and OnCharge receives the payment callback first: it checks the network's signature, records the payment in your dashboard, then sends you the same callback, retrying until your server answers `2xx`.

- **Same URL, same parameters.** You receive your callback URL with the gateway's parameters appended, exactly as without the relay. The wallet's `callback_url` in the response is still yours, and the same callback URL still returns the same wallet.
- **Signed by OnCharge.** Relayed callbacks carry `X-OnCharge-Signature: t=<unix time>,v1=<hex>`: an HMAC-SHA256, with your key's signing secret, of `<t>.<the full URL you received>`. Reject it if the signature does not match or `t` is more than five minutes old. `X-OnCharge-Event-Id` names the payment; a repeat has the same id.
- **Retries.** After 1 minute, 5 and 15 minutes, then 1, 3, 6, 12 and 24 hours. A crypto payment's unconfirmed notice (`pending=1`) and its confirmed callback are each delivered once.

```js title="Node.js: check a relayed callback"
import { createHmac, timingSafeEqual } from 'node:crypto';

function relayedCallbackIsValid(fullUrl, header, signingSecret) {
  const { t, v1 } = Object.fromEntries(String(header ?? '').split(',').map((p) => p.trim().split('=')));
  if (!t || !v1 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = createHmac('sha256', signingSecret).update(`${t}.${fullUrl}`).digest('hex');
  return v1.length === expected.length && timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
}
// fullUrl is the callback URL exactly as it arrived: https://shop.example.com/oncharge/callback?order=1001&…
```

Then run the same [checks](#checks) as for a direct callback.

## Webhooks and the payments API {#webhooks}

With your gateway key, each payment and conversion is also an OnCharge event, sent to the [webhook endpoints](https://oncharge.io/docs/webhooks) you set up in the dashboard and kept in [`GET /api/v1/events`](https://oncharge.io/docs/api#listevents) for 30 days:

| Event | When | `data.rail` |
|---|---|---|
| `payment.pending` | A payment is seen on the chain and not confirmed yet. | `crypto`, or `card_to_crypto` for a card wallet |
| `payment.captured` | The payment is confirmed and forwarded to your wallet. | the same |
| `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired` | A conversion starts, or ends. | `crypto` |

Each is sent once per state, with OnCharge references (`ocpay_…`, `ocswp_…`), your wallet masked and the public transaction hashes. Payments also appear in [`GET /api/v1/payments`](https://oncharge.io/docs/api#listpayments) (`source=gateway`). The callbacks above stay as they are: use whichever your integration prefers.

## Plugins and modules {#plugins}

Compatible open-source white-label gateway modules run on OnCharge unchanged. In the module's settings:

| Setting | Value |
|---|---|
| API Domain | `capi.oncharge.io` |
| Custom / Checkout Domain | `ccheckout.oncharge.io` |
| Wallet | Your Polygon USDC wallet |

Modules with both settings exist for Magento 2, PrestaShop, OpenCart and WHMCS: [contact OnCharge support](/contact) and we send you the one for your cart. For WooCommerce, use the [OnCharge Crypto Payments plugin](https://oncharge.io/docs/crypto-plugin).

## Errors {#errors}

| Status | Meaning |
|---|---|
| `400` | A parameter was refused, for example partner shares that do not add up or a network the gateway does not support. |
| `405` | Wrong method: wallet creation is `GET`, the hosted crypto checkout is `POST`. |
| `429` | Status reads are rate limited: wait for `Retry-After`. |
| `502` | The upstream payment network did not answer. Retry `GET` requests later. |

## Security notes {#security}

- Keep your callback secret on your server. Never put it in browser code.
- Use a self-custodial payout wallet you control; exchange deposit addresses are not recommended.
- Price orders on the server. The amount in a checkout link can be seen and edited by the customer.
- Update orders from verified callbacks. Use the status endpoints only for occasional checks.
