# Billions > This file is very large and may be truncated. For an index of this content, please refer to https://docs.billions.works/llms.txt instead. > Integrate Billions payments into your application, store, or billing platform. # Create an invoice API Source: https://docs.billions.works/api/create-invoice Request and response fields for the public invoice-creation endpoint. Create an invoice with `POST /public/v1/invoices/create` on the [sandbox or production API host](/integration/prerequisites#choose-an-environment). Send JSON with `Content-Type: application/json` and your server-side API key in the `x-api-key` header. The [production OpenAPI schema](https://api.billions.works/public/v1/swagger.json) is the source of truth for the deployed field types and required fields. ## Request body Only `currency` and `amount` are required by the current OpenAPI schema. `idempotencyKey`, `order_no`, and `callbackUrl` are strongly recommended for a reliable store integration. | Field | Type | Required | Meaning | | - | - | - | - | | `currency` | string | Yes | Invoice currency code. Use the [currencies endpoint](/api/overview#endpoints) to discover supported values. A code such as `USDT` may be mapped to a network-specific internal ticker. | | `amount` | number or string | Yes | Requested amount in major units; must be greater than zero. Prefer a decimal string in your own order records. | | `idempotencyKey` | string | No | Stable key for retries of the same logical creation attempt. Use a new key for an intentional new attempt. | | `type` | `b2b` or `b2c` | No | Invoice type; defaults to `b2c`. | | `order_no` | string | No | Your stable business order reference. Keep it across payment attempts for the same order. | | `description` | string | No | Description shown with the invoice where supported. | | `autoconvert` | string | No | Supported currency code without a network suffix for automatic conversion. | | `callbackUrl` | HTTP or HTTPS URL string | No | Your notification endpoint. It must be publicly reachable for live callback delivery. | | `success_url` | HTTP or HTTPS URL string | No | Optional customer redirect URL after a successful checkout. A redirect is not proof of payment. | | `return_url` | HTTP or HTTPS URL string | No | Optional customer return URL. A return is not proof of payment. | | `fail_url` | HTTP or HTTPS URL string | No | Optional customer redirect URL after an unsuccessful checkout. | | `expiresAt` | date-time string | No | Requested expiration time. If omitted, the current backend defaults to two hours after creation. Always use the returned `expires_at` as the authoritative deadline. | Unknown fields are not part of the published OpenAPI schema. For example, `callbackUrl` uses camel case while `order_no` and the redirect URL fields use underscores. Follow the schema exactly rather than converting every key to one naming convention. ## Response fields to persist and compare The response includes `id`, `invoice_url`, `status`, `order_no`, `amount`, `settlement_currency`, `currency`, and `expires_at`, as well as fees, payment totals, and optional redirect URLs. Store the invoice ID and your payment attempt before opening `invoice_url`. | Field | Meaning | | - | - | | `id` | Billions invoice ID used for authenticated retrieval. | | `invoice_url` | Hosted checkout URL. Redirect to this value unchanged. | | `status` | Current invoice status; retrieve it again before fulfillment. | | `order_no` | Your order reference, when supplied. | | `amount` | Requested invoice amount, returned as a string. | | `settlement_currency` | Currency code corresponding to the requested invoice denomination; compare this with the order currency. | | `currency` | Internal currency ticker; it can include a network suffix such as `USDT_TRON`. Do not compare it directly with an order denominated in `USDT`. | | `final_amount`, `paid_amount` | Amount due after applicable fees and amount recorded as paid. Do not infer completion from either amount alone. | | `expires_at` | Actual expiration time in the API response; it may be `null` on an existing invoice. | For example, an invoice requested in `USDT` can have `settlement_currency: "USDT"` and `currency: "USDT_TRON"`. Match your order to `settlement_currency` and the requested `amount`, then require `completed` from the authenticated API before fulfillment. See [callbacks and security](/integration/callbacks-and-security#match-the-invoice-to-your-order). See [Statuses and lifecycle](/api/statuses#invoice-statuses) for every invoice status and how to handle it. The [create-invoice example](/examples/create-an-invoice) shows TypeScript, Python, PHP, and cURL. The live OpenAPI documents for [sandbox](https://api-sandbox.billions.works/public/v1/docs) and [production](https://api.billions.works/public/v1/docs) show the schemas currently deployed in each environment. # Public API overview Source: https://docs.billions.works/api/overview Environments, authentication, and endpoints available in Billions Public API v1. Billions Public API v1 is available in separate sandbox and production environments. | Environment | Base URL | | - | - | | Sandbox | `https://api-sandbox.billions.works` | | Production | `https://api.billions.works` | Use sandbox for development, automated tests, and integration verification. Move to the production base URL only after completing the go-live checklist. For a guided check of invoice creation, redirect, and callbacks, see [Test in sandbox](/integration/sandbox-testing). ## Authentication levels Most merchant endpoints require the API key in a request header: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} x-api-key: ``` Endpoints that can move funds require both the API key and an HMAC signature created with the API key secret. See [Request signing](/api/request-signing). | Authentication | Endpoints | | - | - | | None | Version, currencies, countries | | API key | Merchant profile, invoice creation, fee estimation, invoice retrieval, sandbox payment simulation | | API key + signed request | Withdrawal creation, crypto refunds, fiat refunds | ## Endpoints | Method | Path | Purpose | | - | - | - | | `GET` | `/public/v1/version` | Return the public API version | | `GET` | `/public/v1/currencies` | List currently supported currencies and their metadata | | `GET` | `/public/v1/countries` | List supported countries | | `GET` | `/public/v1/me` | Return the merchant associated with the API key | | `POST` | `/public/v1/invoices/create` | Create an invoice | | `POST` | `/public/v1/invoices/mark-as-paid` | Simulate a paid invoice in sandbox only; see [Sandbox testing](/integration/sandbox-testing#option-1-mark-an-invoice-as-paid-with-the-sandbox-api) | | `POST` | `/public/v1/invoices/estimateFees` | Estimate invoice fees | | `GET` | `/public/v1/invoices/{id}` | Retrieve the current invoice by Billions ID | | `GET` | `/public/v1/invoices/byOrder/{order_no}` | Retrieve invoices by your order reference | | `POST` | `/public/v1/withdrawals/create` | Create a signed withdrawal request | | `POST` | `/public/v1/refunds/refundCrypto` | Create a signed crypto refund request | | `POST` | `/public/v1/refunds/refundFiat` | Create a signed fiat refund request | See [Create an invoice API](/api/create-invoice) for a field-by-field request reference and the response fields used for payment verification. See [Statuses and lifecycle](/api/statuses) for the meanings of invoice, withdrawal, and refund request states. ## Discover the API Use the OpenAPI specification for the environment you are calling to inspect its currently deployed request and response schemas. During a staged rollout, an endpoint may appear in one environment before another: * Sandbox Swagger UI: [`https://api-sandbox.billions.works/public/v1/docs`](https://api-sandbox.billions.works/public/v1/docs) * Sandbox OpenAPI JSON: [`https://api-sandbox.billions.works/public/v1/swagger.json`](https://api-sandbox.billions.works/public/v1/swagger.json) * Production Swagger UI: [`https://api.billions.works/public/v1/docs`](https://api.billions.works/public/v1/docs) * Production OpenAPI JSON: [`https://api.billions.works/public/v1/swagger.json`](https://api.billions.works/public/v1/swagger.json) The field explanations in [Create an invoice API](/api/create-invoice) complement the live schema. Check the production Swagger link above if you need to confirm a recent backend change. ## Rate limits and network allowlists No numeric Public API rate limit or guaranteed callback source-IP range is published here. Do not build against an assumed requests-per-minute limit or hard-code an IP list found in an old response. Handle `429` and transient errors with bounded backoff, honor `Retry-After` when present, and preserve idempotency keys across retries. If your firewall requires a fixed callback source range, ask Billions support for the current operational guidance. > [!WARNING] > > Keep API keys and API key secrets on your backend. Never expose them in a > browser bundle, mobile application, URL, callback payload, or log. # Request signing Source: https://docs.billions.works/api/request-signing Sign withdrawals and refunds with RFC 8785 JCS and HMAC-SHA256. Requests that move funds require an additional signature. This protects the HTTP method, exact route, timestamp, request ID, and complete JSON body from tampering. The following endpoints require signing: * `POST /public/v1/withdrawals/create` * `POST /public/v1/refunds/refundCrypto` * `POST /public/v1/refunds/refundFiat` Invoice creation and read-only endpoints continue to use the API key without these additional signing headers. The official [TypeScript](/sdks/typescript#withdrawals-and-refunds), [Python](/sdks/python#withdrawals-and-refunds), and [PHP](/sdks/php#withdrawals-and-refunds) SDKs calculate these signatures automatically when you configure the original API `secretKey`. Use the manual procedure below for direct HTTP integrations. ## Required headers ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} x-api-key: x-billions-timestamp: x-billions-request-id: x-billions-request-signature: v1=<64 lowercase HMAC hex characters> content-type: application/json ``` The timestamp must be within five minutes of Billions server time. The request ID provides idempotency and becomes `request.id` in a successful response. ## Signature calculation Parse the body as JSON and canonicalize it using [RFC 8785 JCS](https://www.rfc-editor.org/rfc/rfc8785.html). The exact route path must include `/public/v1` and must not include the hostname or query string. ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} canonical = RFC8785_JCS(parsed_request_json) message = "POST\n" + path + "\n" + timestamp + "\n" + requestId + "\n" + canonical signature = lowercase_hex(HMAC_SHA256(UTF8(secretKey), UTF8(message))) header = "v1=" + signature ``` Use the original `secretKey` returned once when the API key was created as UTF-8 **text**. Although it looks like a 64-character hexadecimal value, do not hex-decode it. Older API keys that were issued before signed operations were introduced must be revoked and reissued. ### TypeScript / Node.js Install an RFC 8785 implementation: ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} npm install canonicalize ``` ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} import { createHmac, randomUUID } from 'node:crypto'; import canonicalize from 'canonicalize'; function signBillionsRequest( path: string, body: unknown, apiKey: string, secretKey: string, requestId = randomUUID(), ) { const timestamp = String(Math.floor(Date.now() / 1000)); const canonicalBody = canonicalize(body); if (canonicalBody === undefined) { throw new Error('Body is not valid RFC 8785 JSON'); } const message = `POST\n${path}\n${timestamp}\n${requestId}\n${canonicalBody}`; const signature = createHmac('sha256', secretKey) .update(message, 'utf8') .digest('hex'); return { requestId, headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'x-billions-timestamp': timestamp, 'x-billions-request-id': requestId, 'x-billions-request-signature': `v1=${signature}`, }, }; } ``` ### PHP Use an RFC 8785-compatible library to produce `$canonicalJson`; ordinary `json_encode()` with sorted top-level keys is not sufficient. ```php theme={"theme":{"light":"github-dark","dark":"github-dark"}} 'EUR', 'amount' => '70', 'withdrawalMethodId' => 123, ]; $timestamp = (string) time(); // uuid_create() is provided by the PECL UUID extension. Any RFC 4122 UUID v4 // generator can be used here. $requestId = uuid_create(UUID_TYPE_RANDOM); // Produce this with an RFC 8785 JCS implementation. $canonicalJson = $jcsCanonicalizer->canonicalize($body); $message = "POST\n{$path}\n{$timestamp}\n{$requestId}\n{$canonicalJson}"; $signature = hash_hmac('sha256', $message, $secretKey); $headers = [ 'Content-Type: application/json', 'x-api-key: ' . $apiKey, 'x-billions-timestamp: ' . $timestamp, 'x-billions-request-id: ' . $requestId, 'x-billions-request-signature: v1=' . $signature, ]; ``` ## Safe retries For a retry caused by a timeout or lost response: * reuse the same request ID; * reuse the identical JSON body and endpoint; * calculate a fresh timestamp and signature if the old timestamp expired. With an SDK, persist the request ID before the first call and pass that same ID and payload on retry. The SDK creates a fresh timestamp and signature for each call. Retrying an identical completed operation returns the original request without creating another debit or payout. Reusing a request ID with another body or endpoint returns `409`. If the original request is still running or requires reconciliation, the retry also returns `409`. ## Common responses | Status | Meaning | | - | - | | `400` | The signed JSON is valid, but operation data or business validation failed | | `401` | API key, timestamp, request ID format, or signature is missing or invalid | | `403` | The API key must be reissued before signed operations can be used | | `409` | The request ID was reused with different data, or the original operation is still being reconciled | > [!WARNING] > > Never generate a new request ID only because the response was lost. A new ID > authorizes a new financial operation. # Statuses and lifecycle Source: https://docs.billions.works/api/statuses Understand invoice, withdrawal, and refund statuses returned by the Public API. The Public API returns a `status` for three kinds of records: invoices, withdrawal requests, and refund requests. These are **different status vocabularies**. Always read the status from the authenticated API response; a callback is a notification that the invoice may have changed, not the source of truth. ## Invoice statuses The `status` field appears in invoice creation and retrieval responses. These are the values in the [production OpenAPI schema](https://api.billions.works/public/v1/swagger.json): | Status | Meaning | Integration handling | | - | - | - | | `pending` | The invoice is open and awaiting payment. | Keep the order unpaid. | | `processing` | A payment has been detected or is being processed; completion has not been confirmed. | Show a pending state; do not fulfill. | | `aml_check` | The payment is undergoing a compliance check. | Keep fulfillment on hold. | | `aml_block` | The payment is blocked by a compliance decision. | Do not fulfill; follow your review and support process. | | `completed` | The payment is confirmed for this invoice. | After matching the invoice ID, order, amount, and settlement currency, fulfill exactly once. | | `failed` | The payment attempt did not complete successfully. | Keep the order unpaid; offer a deliberate new attempt if appropriate. | | `expired` | The invoice passed its payment deadline without completion. | Keep the order unpaid; create a new attempt rather than reusing its checkout URL. | | `refund_processing` | A refund has been requested and is not yet complete. | Show the refund as pending; do not mark it refunded yet. | | `refunded` | The refund has completed. | Mark the payment as refunded in your records. | An invoice can move from `completed` to `refund_processing`, then to `refunded`. If a refund fails or is declined, the invoice can return to `completed`; inspect the **refund request** for the refund outcome. Do not assume that `completed` is the last possible invoice status. > [!WARNING] > > Only an authenticated invoice lookup returning `completed` can authorize > fulfillment. `processing`, `aml_check`, a customer's return from checkout, > or an `invoice.paid` callback on its own is not sufficient. ## Withdrawal request statuses The `status` field tracks the Billions withdrawal request. Public API-created requests currently start in `processing`, but clients must handle every documented value. | Status | Meaning | | - | - | | `created` | The request exists but has not entered processing. | | `pending` | The request is awaiting confirmation or another processing step. | | `processing` | The withdrawal is being handled; payout is not yet confirmed. | | `success` | The withdrawal completed successfully. | | `rejected` | The withdrawal was rejected or could not be completed. | `success` and `rejected` are terminal request outcomes. Do not treat `processing` as proof that the recipient has been paid. ## Refund request statuses The `status` field on a refund request is separate from the original invoice status. Public API-created refund requests currently start in `processing`. | Status | Meaning | | - | - | | `new` | The refund request exists and has not entered processing. | | `processing` | The refund is being reviewed or sent; it is not complete. | | `refunded` | The refund completed successfully. | | `failed` | The refund could not be completed. | | `declined` | The refund was declined during review. | `refunded`, `failed`, and `declined` are terminal request outcomes. After a failed or declined refund, the original invoice can again report `completed`; that means the payment still stands, **not** that the refund succeeded. ## Callback events Native invoice callbacks have an `event` (`invoice.status_changed` or `invoice.paid`) plus `previous_status` and `status`. These describe an invoice transition, not a separate webhook-delivery status. Callback delivery may be delayed or retried, so retrieve the current invoice before acting. See [Callbacks and security](/integration/callbacks-and-security). For the request and response fields of money operations, see [Withdrawals and refunds](/api/withdrawals-and-refunds). # Withdrawals and refunds Source: https://docs.billions.works/api/withdrawals-and-refunds Create signed withdrawal, crypto refund, and fiat refund requests. Withdrawals and refunds are server-side money operations. Every request on this page must include the headers described in [Request signing](/api/request-signing). The official SDKs generate the signature and request headers for these operations. See the [TypeScript](/sdks/typescript#withdrawals-and-refunds), [Python](/sdks/python#withdrawals-and-refunds), and [PHP](/sdks/php#withdrawals-and-refunds) examples. The direct HTTP examples below are useful when integrating without an SDK. | Operation | TypeScript and PHP | Python | | - | - | - | | Withdrawal | `createWithdrawal()` | `create_withdrawal()` | | Crypto refund | `refundCrypto()` | `refund_crypto()` | | Fiat refund | `refundFiat()` | `refund_fiat()` | > [!NOTE] > > Use `https://api-sandbox.billions.works` as the base URL while developing and > testing these flows. ## Create a withdrawal ```http theme={"theme":{"light":"github-dark","dark":"github-dark"}} POST /public/v1/withdrawals/create ``` ```json theme={"theme":{"light":"github-dark","dark":"github-dark"}} { "currency": "EUR", "amount": "70", "withdrawalMethodId": 123 } ``` | Field | Type | Description | | - | - | - | | `currency` | string | Currency of the existing withdrawal method | | `amount` | string | Positive amount; send monetary values as strings | | `withdrawalMethodId` | integer | Existing withdrawal method owned by the API-key merchant | The selected method must use the same currency, the merchant must be operational, the amount must satisfy configured limits, and the available balance must be sufficient. Create and manage withdrawal methods in the Billions dashboard, then send the method ID in this request. ### Direct HTTP TypeScript ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} const path = '/public/v1/withdrawals/create'; const body = { currency: 'EUR', amount: '70', withdrawalMethodId: 123, }; const { headers } = signBillionsRequest(path, body, apiKey, secretKey); const response = await fetch(`${billionsApiUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body), }); if (!response.ok) throw new Error(`Withdrawal failed: ${response.status}`); const { request } = await response.json(); ``` ### cURL Generate the timestamp, UUID, and signature on your backend before making the request: ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} curl --request POST \ --url "$BILLIONS_API_URL/public/v1/withdrawals/create" \ --header "Content-Type: application/json" \ --header "x-api-key: $BILLIONS_API_KEY" \ --header "x-billions-timestamp: $BILLIONS_TIMESTAMP" \ --header "x-billions-request-id: $BILLIONS_REQUEST_ID" \ --header "x-billions-request-signature: v1=$BILLIONS_SIGNATURE" \ --data '{"currency":"EUR","amount":"70","withdrawalMethodId":123}' ``` ## Refund a crypto invoice ```http theme={"theme":{"light":"github-dark","dark":"github-dark"}} POST /public/v1/refunds/refundCrypto ``` Refund to the single sender address recorded on the invoice: ```json theme={"theme":{"light":"github-dark","dark":"github-dark"}} { "invoiceId": "29d30442-91b3-451b-91ed-2ae2c17f89b0", "withdrawToSameAddress": true, "reason": "Customer request" } ``` Or provide the destination explicitly: ```json theme={"theme":{"light":"github-dark","dark":"github-dark"}} { "invoiceId": "29d30442-91b3-451b-91ed-2ae2c17f89b0", "address": "TExampleRefundAddress", "reason": "Customer request" } ``` `withdrawToSameAddress: true` is accepted only when the invoice contains exactly one incoming transaction with a sender address. The invoice must belong to the merchant, be `completed`, use a non-fiat payment currency, and have no active or completed refund. ### Direct HTTP TypeScript ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} const path = '/public/v1/refunds/refundCrypto'; const body = { invoiceId: '29d30442-91b3-451b-91ed-2ae2c17f89b0', withdrawToSameAddress: true, reason: 'Customer request', }; const { headers } = signBillionsRequest(path, body, apiKey, secretKey); const response = await fetch(`${billionsApiUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body), }); ``` ## Refund a fiat invoice ```http theme={"theme":{"light":"github-dark","dark":"github-dark"}} POST /public/v1/refunds/refundFiat ``` ```json theme={"theme":{"light":"github-dark","dark":"github-dark"}} { "invoiceId": "29d30442-91b3-451b-91ed-2ae2c17f89b0", "reason": "Customer request" } ``` The invoice must belong to the merchant, be `completed`, settle in fiat, and have no active or completed refund. The merchant balance must cover the refund. ### Direct HTTP TypeScript ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} const path = '/public/v1/refunds/refundFiat'; const body = { invoiceId: '29d30442-91b3-451b-91ed-2ae2c17f89b0', reason: 'Customer request', }; const { headers } = signBillionsRequest(path, body, apiKey, secretKey); const response = await fetch(`${billionsApiUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body), }); ``` ## Response All three endpoints return the operation under `request`. Its `id` equals the signed `x-billions-request-id`. ```json theme={"theme":{"light":"github-dark","dark":"github-dark"}} { "request": { "id": "cd7c2f8a-08b6-4db4-8a93-f00ce1f75ea5", "currency": "EUR", "amount": "70", "withdrawal_method_id": 123, "status": "processing", "created_at": "2026-10-15T10:00:00.000Z", "updated_at": "2026-10-15T10:00:00.000Z" } } ``` Refund responses additionally include `invoice_id`, `type`, `to_address`, and `withdraw_to_same_address`. See [Statuses and lifecycle](/api/statuses#withdrawal-request-statuses) for the meanings of withdrawal and refund request statuses. # AI integration implementation checklist Source: https://docs.billions.works/developer/ai-integration-checklist A task-by-task checklist for coding agents implementing Billions payments. This page is a working checklist for a coding agent, not a replacement for the [full Billions documentation](https://docs.billions.works/llms-full.txt). Read the relevant source pages before writing code. If a requirement conflicts with the current API schema or an SDK's current README, verify the deployed environment and report the discrepancy instead of guessing. ## 1. Understand the project * [ ] Inspect the application stack, existing checkout flow, order model, payment status transitions, background jobs, and test conventions. * [ ] Identify where server-side secrets, the Billions API base URL, and callback URLs are configured. Never put credentials in frontend or mobile code, URLs, logs, or committed files. * [ ] Identify the order's stable reference, the place to persist a Billions invoice ID, and the code path that fulfills an order exactly once. * [ ] Ask for missing business decisions—such as settlement currency, supported payment methods, or fulfillment policy—rather than inventing them. ## 2. Choose one documented integration path * [ ] For an existing store or billing platform, check the relevant [platform integration](/store-integrations/overview) before writing a custom gateway. Follow that module's own installation and callback instructions. * [ ] For a custom backend, use the [official SDK](/sdks/overview) for the project's runtime when suitable. Otherwise use the [Public API](/api/overview). * [ ] Use the [Unified Merchant API](/integration/unified-merchant-api) only when adapting an existing compatible SDK or module; it is a partial compatibility layer, not the default path for a new integration. * [ ] Check the currently deployed [OpenAPI schema](/api/overview#discover-the-api) for exact request and response fields. Do not invent endpoints or SDK methods. ## 3. Prepare the environment and credentials * [ ] Direct the merchant to [sign up in the Billions app](https://app.billions.works/sign-up) and create separate sandbox and production API keys in **Settings → API**. * [ ] Start with `https://api-sandbox.billions.works` and sandbox credentials. Keep them separate from production credentials and `https://api.billions.works`. * [ ] Do not assume that a platform module can switch hosts: the current WooCommerce and WHMCS modules call production only. BILLmanager has a configurable API origin. Follow each module's guide. * [ ] Store the API key in server-side secret storage. Store the original API key secret only if the chosen flow needs signed money operations or optional webhook signature verification. * [ ] Configure a publicly reachable HTTPS callback URL for a custom integration. Check that the deployed service can reach the Billions API. * [ ] Confirm supported currencies through the API instead of assuming a hard-coded list. Follow [prerequisites](/integration/prerequisites). ## 4. Create an invoice safely * [ ] Create invoices on the backend, never in the browser. Send the documented currency, amount, `order_no`, `idempotencyKey`, and callback URL. * [ ] Keep `order_no` stable for the business order. Use a stable `idempotencyKey` for retries of the **same logical creation attempt**, and a new key for a deliberately new payment attempt. * [ ] Persist the invoice ID, order reference, idempotency key, status, and expiration when provided. Handle network timeouts without creating an accidental second payment attempt. * [ ] Redirect the customer using the returned `invoice_url` unchanged. Do not construct a checkout URL or treat the customer's return as payment proof. * [ ] Follow the [payment flow](/integration/payment-flow) and [create-invoice example](/examples/create-an-invoice). ## 5. Confirm payment from the authoritative API * [ ] Accept the documented callback payload and read `data.invoice_id` for new integrations. Treat the callback as a signal, not as proof of payment. * [ ] Optionally verify `x-billions-signature` with the original API key secret and RFC 8785 JCS as defense in depth. Do not skip the API lookup even when the signature is valid. * [ ] Retrieve the invoice through the authenticated Billions API. Match its invoice ID, order reference, `amount`, and `settlement_currency` against the stored payment attempt before changing the order. `currency` may be a network-specific internal ticker such as `USDT_TRON`. * [ ] Fulfill only after the API returns `completed`. Keep `pending`, `processing`, `expired`, `failed`, and AML-related states distinct. Handle refund states if the application supports refunds. * [ ] Make callbacks, polling, and fulfillment idempotent. Persist the state transition before acknowledging the callback; enqueue slow side effects. * [ ] Add a recovery path for delayed or missed callbacks by retrieving the invoice from the API. Follow [callbacks and security](/integration/callbacks-and-security) and the [callback example](/examples/handle-a-callback). ## 6. Add optional money operations only when requested * [ ] Do not add withdrawals or refunds unless they are in scope. If needed, follow [request signing](/api/request-signing) and [withdrawals and refunds](/api/withdrawals-and-refunds) exactly. * [ ] Use the original API key secret, RFC 8785 canonical JSON, HMAC-SHA256, and the documented request-ID and retry rules. Never reuse a request ID for different operation data. ## 7. Test and hand off * [ ] Test a successful sandbox payment end to end and confirm that only the authenticated API response marks the order paid. * [ ] Test abandoned checkout, expired or failed invoice, duplicate and delayed callbacks, callback before customer return, and API timeouts. * [ ] Test invalid signatures and mismatched invoice details where applicable. Confirm that repeated callbacks cannot repeat fulfillment. * [ ] Run the project's relevant automated tests and the [go-live checklist](/integration/go-live-checklist). Do not claim an end-to-end payment was tested unless it actually was. * [ ] Report what was implemented, the files changed, tests run, remaining assumptions, and any steps that require merchant credentials or a real checkout. Do not silently switch to production. # Developer documentation Source: https://docs.billions.works/developer/overview Integrate Billions payments into your application, store, or billing platform. **Integrate with an AI coding agent** Copy this prompt into Codex, Claude Code, Cursor, or another coding agent: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} Integrate Billions payments into this project. Read https://docs.billions.works/llms-full.txt, including its AI integration implementation checklist. Inspect the project before choosing the documented SDK, API, or platform module. Keep secrets server-side, test in sandbox, verify payment through the authenticated API before fulfillment, and report any unverified assumptions or blocked steps. ``` Billions provides a hosted payment flow for accepting payments without building your own checkout or payment-status infrastructure. Your backend creates an invoice, redirects the customer to the hosted payment page, and confirms the result by retrieving the invoice from the authenticated Billions API. > [card] [Integrate the payment flow](/integration/overview) > > Follow the complete path from API credentials to production launch. > [card] [Start from an example](/examples/create-an-invoice) > > Create an invoice, handle a callback, and retrieve invoices from the API. > [card] [Choose an SDK](/sdks/overview) > > Use the TypeScript, Python, or PHP SDK to integrate the Billions API. > [card] [Explore the Public API](/api/overview) > > Review environments, authentication, request signing, withdrawals, and > refunds. > [card] [Test in sandbox](/integration/sandbox-testing) > > Simulate a paid invoice or test with Sepolia ETH before going live. > [card] [Connect a platform](/store-integrations/overview) > > Add Billions to WooCommerce or BILLmanager with an official module. ## How the integration works **1. Create an invoice** Your backend sends the amount, currency, order reference, callback URL, and an idempotency key to Billions. **2. Redirect the customer** Open the returned `invoice_url`. The customer completes payment on the Billions-hosted page. **3. Receive a callback** Billions notifies your callback endpoint that the invoice may have changed. **4. Verify with the API** Retrieve the invoice from the authenticated API and update the order only from that response. > [!WARNING] > > Never mark an order as paid from callback fields alone. Treat the callback > as a signal to retrieve the current invoice from the Billions API. ## Choose an integration path * Building a custom application? Start with the [integration guide](/integration/overview). * Using Node.js or another TypeScript runtime? See the [TypeScript SDK](/sdks/typescript). * Building with Python 3.10 or newer? See the [Python SDK](/sdks/python). * Building with PHP 8.1 or newer? See the [PHP SDK](/sdks/php). * Running WooCommerce? Install the [WooCommerce integration](/store-integrations/woocommerce). * Running BILLmanager 6? Install the [BILLmanager integration](/store-integrations/billmanager). * Running WHMCS? Install the [WHMCS integration](/store-integrations/whmcs). * Using Tilda? Follow the [Tilda Custom Payment Gateway guide](/store-integrations/tilda). # Create an invoice Source: https://docs.billions.works/examples/create-an-invoice Create a hosted payment invoice with an SDK. This example creates a `100 USDT` invoice for `ORDER-1001`. The examples below use the sandbox host explicitly. Replace it only when you are ready for production and have switched to production credentials. ```ts TypeScript theme={"theme":{"light":"github-dark","dark":"github-dark"}} import { BillionsApi } from '@billions-works/sdk-ts'; const api = new BillionsApi({ apiKey: process.env.BILLIONS_API_KEY!, baseUrl: 'https://api-sandbox.billions.works', }); const invoice = await api.createInvoice({ currency: 'USDT', amount: 100, order_no: 'ORDER-1001', idempotencyKey: 'ORDER-1001-attempt-1', callbackUrl: 'https://example.com/webhooks/billions', }); console.log(invoice.id); console.log(invoice.invoice_url); ``` ```python Python theme={"theme":{"light":"github-dark","dark":"github-dark"}} import os from billions_sdk import BillionsApi with BillionsApi( os.environ["BILLIONS_API_KEY"], base_url="https://api-sandbox.billions.works", ) as api: invoice = api.create_invoice( { "currency": "USDT", "amount": 100, "order_no": "ORDER-1001", "idempotencyKey": "ORDER-1001-attempt-1", "callbackUrl": "https://example.com/webhooks/billions", } ) print(invoice["id"]) print(invoice["invoice_url"]) ``` ```php PHP theme={"theme":{"light":"github-dark","dark":"github-dark"}} createInvoice([ 'currency' => 'USDT', 'amount' => 100, 'order_no' => 'ORDER-1001', 'idempotencyKey' => 'ORDER-1001-attempt-1', 'callbackUrl' => 'https://example.com/webhooks/billions', ]); echo $invoice['id'] . PHP_EOL; echo $invoice['invoice_url'] . PHP_EOL; ``` ```bash cURL theme={"theme":{"light":"github-dark","dark":"github-dark"}} BILLIONS_API_URL=https://api-sandbox.billions.works curl --request POST \ --url "$BILLIONS_API_URL/public/v1/invoices/create" \ --header "Content-Type: application/json" \ --header "x-api-key: $BILLIONS_API_KEY" \ --data '{ "currency": "USDT", "amount": 100, "order_no": "ORDER-1001", "idempotencyKey": "ORDER-1001-attempt-1", "callbackUrl": "https://example.com/webhooks/billions" }' ``` The TypeScript SDK otherwise defaults to production when `baseUrl` is absent. For all request and response fields, see [Create an invoice API](/api/create-invoice). ## What to store Store the returned invoice ID with your order before redirecting the customer. Also retain the order number, idempotency key, status, and expiration time. ## What to do next Redirect the customer to `invoice_url`, then implement [callback handling](/examples/handle-a-callback). # Get invoices from the API Source: https://docs.billions.works/examples/get-invoices-from-api Retrieve Billions invoices using your order reference. Retrieve invoices from the Billions API using the `order_no` stored with your order. This is useful for displaying payment status, reconciling local records, or restoring an invoice after an uncertain create request. For example, a create request may time out after Billions has created the invoice but before your backend receives the response. Before creating another invoice, query the API using the stable `order_no`. ```ts TypeScript theme={"theme":{"light":"github-dark","dark":"github-dark"}} const invoices = await api.getInvoicesByOrder('ORDER-1001'); for (const invoice of invoices) { console.log(invoice.id, invoice.status, invoice.invoice_url); } ``` ```python Python theme={"theme":{"light":"github-dark","dark":"github-dark"}} invoices = api.get_invoices_by_order_no("ORDER-1001") for invoice in invoices: print(invoice["id"], invoice["status"], invoice["invoice_url"]) ``` ```php PHP theme={"theme":{"light":"github-dark","dark":"github-dark"}} $invoices = $api->getInvoicesByOrderNo('ORDER-1001'); foreach ($invoices as $invoice) { echo $invoice['id'] . ' ' . $invoice['status'] . PHP_EOL; } ``` ```bash cURL theme={"theme":{"light":"github-dark","dark":"github-dark"}} curl --request GET \ --url "$BILLIONS_API_URL/public/v1/invoices/byOrder/ORDER-1001" \ --header "Content-Type: application/json" \ --header "x-api-key: $BILLIONS_API_KEY" ``` ## Retrieval and recovery rules 1. Retry the same logical create attempt with the same idempotency key. 2. Query by `order_no` when reconciling your local order with Billions. 3. Match the amount, currency, and intended attempt before redirecting. 4. Create a new attempt only when the previous attempt is no longer usable. # Handle a callback Source: https://docs.billions.works/examples/handle-a-callback Verify a payment callback against the authenticated API. Read `data.invoice_id` from the webhook envelope and retrieve the authoritative invoice. This is the recommended verification flow for both intermediate and final statuses. Webhook signature verification is optional defense in depth and does not replace the API lookup. ```ts TypeScript theme={"theme":{"light":"github-dark","dark":"github-dark"}} try { const webhook = request.body; const invoice = await api.getInvoiceFromWebhook(webhook); // Deduplicate deliveries using webhook.webhook_id. // Update intermediate state when useful. // Fulfill invoice.order_no exactly once only when status is completed. return response.status(200).send('OK'); } catch (error) { // A non-200 response causes Billions to retry the webhook. return response.status(500).send('Could not retrieve invoice'); } ``` ```python Python theme={"theme":{"light":"github-dark","dark":"github-dark"}} try: invoice = api.get_invoice_from_webhook(webhook) # Deduplicate deliveries using webhook["webhook_id"]. # Update intermediate state when useful. # Fulfill invoice["order_no"] exactly once only when status is completed. except Exception: # Return a non-200 response so Billions retries the webhook. raise ``` ```php PHP theme={"theme":{"light":"github-dark","dark":"github-dark"}} getInvoiceFromWebhook($webhook); // Deduplicate deliveries using $webhook['webhook_id']. // Update intermediate state when useful. // Fulfill $invoice['order_no'] exactly once only when status is completed. } catch (Throwable $exception) { // Return a non-200 response so Billions retries the webhook. } ``` ```bash cURL theme={"theme":{"light":"github-dark","dark":"github-dark"}} curl --request GET \ --url "$BILLIONS_API_URL/public/v1/invoices/$BILLIONS_INVOICE_ID" \ --header "Content-Type: application/json" \ --header "x-api-key: $BILLIONS_API_KEY" ``` To authenticate the callback before this lookup, verify `X-Billions-Signature` as described in [Callbacks and security](/integration/callbacks-and-security#webhook-signature). The official SDKs now provide `verifyWebhookSignature()` in TypeScript and PHP, and `verify_webhook_signature()` in Python. > [!WARNING] > > Add callback schema validation, order matching, and transactional idempotency > before using these illustrative handlers in production. A callback status is > informational until confirmed by the authenticated API. # Introduction Source: https://docs.billions.works/index Find developer documentation and legal information for Billions. Welcome to the Billions documentation. Choose the section that matches what you need. > [card] [Developer documentation](/developer/overview) > > Integrate Billions payments, explore implementation examples, choose an > SDK, or connect a store or billing platform. > [card] [Legal documents](/legal/overview) > > Review the Terms of Use, Privacy Policy, AML Policy, Risk Disclosure, > Cookie Policy, and service restrictions. ## Where should I start? * If you are building or maintaining an integration, go to the [Developer documentation](/developer/overview). * If you need policies, contractual terms, privacy information, or restricted jurisdictions, go to the [Legal section](/legal/overview). > [!NOTE] > > Need an account or API keys? [Sign up in the Billions app](https://app.billions.works/sign-up), > then open **Settings → API** to create sandbox and production keys. # Callbacks and security Source: https://docs.billions.works/integration/callbacks-and-security Process invoice notifications without trusting unverified input. Use callbacks to wake your integration, not as proof of payment. ## Callback payload Billions sends an HTTP `POST` request with a JSON body: ```json theme={"theme":{"light":"github-dark","dark":"github-dark"}} { "webhook_id": "b746acdb-52b3-43ee-baae-dcd122d34318", "event": "invoice.paid", "event_timestamp": "2026-08-04T09:42:08.189Z", "attempt": 1, "previous_attempt_timestamp": null, "invoice_id": "29d30442-91b3-451b-91ed-2ae2c17f89b0", "external_invoice_id": "12", "order_no": "ORDER-1001", "previous_status": "processing", "status": "completed", "amount": "100.00", "final_amount": "101.00", "paid_amount": "101.00", "merchant_fee": "1.00", "network_and_other_fees": "0.00", "merchant_receive_amount": "100.00", "currency": "USDT_TRON", "settlement_currency": "USDT", "payment_source": "internal", "payment_address": "T...", "payment_currency": "USDT_TRON", "payment_amount": "101.00", "transactions": [], "updated_at": "2026-08-04T09:42:08.000Z", "data": { "invoice_id": "29d30442-91b3-451b-91ed-2ae2c17f89b0", "external_invoice_id": "12", "order_no": "ORDER-1001", "previous_status": "processing", "status": "completed", "amount": "100.00", "final_amount": "101.00", "paid_amount": "101.00", "merchant_fee": "1.00", "network_and_other_fees": "0.00", "merchant_receive_amount": "100.00", "currency": "USDT_TRON", "settlement_currency": "USDT", "payment_source": "internal", "payment_address": "T...", "payment_currency": "USDT_TRON", "payment_amount": "101.00", "transactions": [], "updated_at": "2026-08-04T09:42:08.000Z" } } ``` For new integrations, `data` is the canonical event payload. Its fields are temporarily duplicated at the top level for backward compatibility. ### Envelope fields | Field | Type | Description | | - | - | - | | `webhook_id` | string | Stable delivery ID; use it to deduplicate retries | | `event` | string | `invoice.paid` or `invoice.status_changed` | | `event_timestamp` | string | ISO 8601 time when the event occurred; unchanged across retries | | `attempt` | integer | Delivery attempt number, starting at `1` | | `previous_attempt_timestamp` | string or null | Previous delivery attempt time; `null` on the first attempt | | `data` | object | Canonical invoice event payload | ### Invoice event fields | Field | Type | Description | | - | - | - | | `invoice_id` | string | Billions invoice ID used to retrieve authoritative state | | `external_invoice_id` | string or null | Invoice identifier from the underlying payment provider | | `order_no` | string or null | Your business order reference | | `previous_status` | string | Invoice status before the transition | | `status` | string | Invoice status after the transition | | `amount` | string | Requested invoice amount | | `final_amount` | string | Final amount including applicable fees | | `paid_amount` | string | Amount recorded as paid | | `merchant_fee` | string | Merchant fee for the invoice | | `network_and_other_fees` | string | Network and other applicable fees | | `merchant_receive_amount` | string | Amount credited to the merchant | | `currency` | string or null | Invoice currency | | `settlement_currency` | string or null | Settlement currency | | `payment_source` | string or null | Payment provider or processing source | | `payment_address` | string or null | Payment address when applicable | | `payment_currency` | string or null | Currency used by the active payment method | | `payment_amount` | string or null | Amount expected by the active payment method | | `transactions` | array | Transactions recorded for the invoice | | `updated_at` | string | ISO 8601 invoice update time | The request uses the `Content-Type: application/json` header. > [!WARNING] > > Even a correctly signed callback is a notification, not the recommended > source of payment truth. Retrieve the invoice using `data.invoice_id` and > trust the authenticated API response before fulfillment. ## Events and intermediate statuses | Event | When it is sent | | - | - | | `invoice.status_changed` | Any invoice status transition except transition to `completed` | | `invoice.paid` | The invoice transitions to `completed` | Callbacks can therefore report intermediate statuses such as `processing` and `aml_check`. Update visible payment state if useful, but fulfill an order only after the authenticated API returns `completed`. The complete invoice status reference is in [Statuses and lifecycle](/api/statuses#invoice-statuses). ## Safe callback algorithm **1. Accept the request** Parse the JSON and read `data.invoice_id`. You may verify the signature as defense in depth, but do not make fulfillment depend only on callback data. **2. Retrieve the invoice** Call the authenticated Billions API with the invoice ID. **3. Match your records** Confirm the retrieved invoice belongs to the expected `order_no` and payment attempt. **4. Apply the transition once** Update the order in a database transaction and make side effects idempotent. **5. Return promptly** Respond successfully after durable processing, or enqueue slow work for a background worker. ## Webhook signature Every delivery includes: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} x-billions-signature: jcs-sha256=<64 lowercase HMAC hex characters> ``` Billions signs the entire **parsed webhook object**, including the envelope, top-level compatibility fields, and `data`. Both sides canonicalize that JSON value with [RFC 8785 JCS](https://www.rfc-editor.org/rfc/rfc8785.html): ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} canonical = RFC8785_JCS(parsed_webhook_json) key = UTF8(original API key secretKey) digest = HMAC_SHA256(key, UTF8(canonical)) header = "jcs-sha256=" + lowercase_hex(digest) ``` The API key secret is used as UTF-8 text, not as hex-decoded bytes. It is the original `secretKey` displayed once when the API key was created. Reissue older API keys that do not have a signing secret. The official [TypeScript](/sdks/typescript#verify-a-webhook-signature), [Python](/sdks/python#verify-a-webhook-signature), and [PHP](/sdks/php#verify-a-webhook-signature) SDKs provide this JCS verification method. Use the examples below when handling signatures without an SDK. ### Verify in TypeScript / Node.js Install an RFC 8785 implementation with `npm install canonicalize`: ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} import { createHmac, timingSafeEqual } from 'node:crypto'; import canonicalize from 'canonicalize'; function verifyBillionsWebhook( webhook: unknown, signatureHeader: string, secretKey: string, ): boolean { const match = /^jcs-sha256=([a-f0-9]{64})$/.exec(signatureHeader); const canonical = canonicalize(webhook); if (!match || canonical === undefined) return false; const received = Buffer.from(match[1], 'hex'); const expected = createHmac('sha256', secretKey) .update(canonical, 'utf8') .digest(); return received.length === expected.length && timingSafeEqual(received, expected); } const signature = String(request.headers['x-billions-signature'] ?? ''); if (!verifyBillionsWebhook(request.body, signature, secretKey)) { return response.sendStatus(401); } // A valid signature does not replace this authoritative API lookup. const invoice = await api.getInvoice(request.body.data.invoice_id); ``` ### Verify in PHP Decode JSON as objects and canonicalize the resulting value with an RFC 8785 implementation. Do not replace JCS with ordinary `json_encode()` or a custom key sort. ```php theme={"theme":{"light":"github-dark","dark":"github-dark"}} canonicalize($webhook); $expected = 'jcs-sha256=' . hash_hmac('sha256', $canonicalJson, $secretKey); if (!hash_equals($expected, $signatureHeader)) { http_response_code(401); exit; } // Still retrieve the invoice from GET /public/v1/invoices/{id}. ``` JCS keeps array order, sorts object keys recursively by UTF-16 code units, and uses ECMAScript-compatible JSON serialization. Do not mutate string values, turn objects into arrays, or parse money into imprecise numbers before verification. Compare digests in constant time. ### Test vector ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} secretKey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef input JSON: {"status":"completed","message":"Заказ/1"} JCS output: {"message":"Заказ/1","status":"completed"} signature: jcs-sha256=f5aaad7e7c75acd4dd679d9a58f708d37fb061bfa7bfd2f12117992715153e92 ``` The signature changes on retries because `attempt` and `previous_attempt_timestamp` change. `event_timestamp` remains stable. Do not reject a valid retry only because its event timestamp is old; deduplicate using `webhook_id`. ## Recommended verification: retrieve the invoice Signature verification proves that the payload came from a holder of the API key secret. It does not make the webhook a better source of current state than the API. The recommended integration remains: ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} curl --request GET \ --url "$BILLIONS_API_URL/public/v1/invoices/$BILLIONS_INVOICE_ID" \ --header "x-api-key: $BILLIONS_API_KEY" ``` Use the returned invoice status, amount, settlement currency, and `order_no` for business decisions. This also handles missing or invalid signatures, delayed deliveries, and webhooks missed during downtime. The API returns the **current** invoice state, which may be newer than the event that triggered the callback. ## Match the invoice to your order Match the authenticated API response to the payment attempt you stored when creating the invoice: | Compare | Use from the retrieved invoice | Do not substitute | | - | - | - | | Invoice identity | `id` | A callback-only identifier without an API lookup | | Business order | `order_no` | The customer's return URL or callback status | | Requested amount | `amount` | `final_amount` (which can include fees) or `paid_amount` | | Order denomination | `settlement_currency` | The network-specific `currency` or `payment_currency` | For a request denominated in `USDT`, the invoice can return `settlement_currency: "USDT"` and `currency: "USDT_TRON"`. The latter identifies a network-specific internal ticker; it is not a mismatch with an order denominated in `USDT`. Keep the expected order amount and currency in your own records and stop fulfillment if the authenticated response differs. Fulfill only after that response also reports `completed`. > [!NOTE] > > No stable callback source-IP range is published for allowlisting. Do not use > an IP allowlist as your only authentication control. Use HTTPS, optional > HMAC signature verification, and the authenticated invoice lookup. Contact > Billions support if your network requires a published egress range. ## Security checklist * Keep API keys in server-side secret storage. * Require HTTPS for the callback endpoint. * Retrieve invoice state from the API before fulfillment. * If you verify signatures, use RFC 8785 JCS and a constant-time comparison. * Keep the API key secret server-side and reissue legacy keys when necessary. * Compare the invoice to the stored order and expected amount. * Treat all callback fields as untrusted input. * Avoid logging API keys or complete sensitive payloads. * Rate-limit the callback endpoint. * Make duplicate delivery harmless. > [!TIP] > > The Python SDK provides `get_invoice_from_webhook()` for every event status. > Its `verify_invoice_paid()` helper additionally requires `completed` status > and compares the webhook status and paid amount with the API result. ## Delivery and response behavior Your endpoint should acknowledge a callback only after the event is stored or processed durably. Billions considers delivery successful only when the endpoint returns HTTP `200`; other responses and transport errors are retried. Current delivery defaults: * Request timeout: 10 seconds. * Maximum delivery attempts: 10. * Retry delay: no earlier than 10 seconds after the previous attempt. * `event_timestamp` stays unchanged across retries. * `attempt` and `previous_attempt_timestamp` identify retry deliveries. Each request also includes: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} User-Agent: Billions-Webhooks/1.0 X-Billions-Webhook-Id: X-Billions-Webhook-Event: X-Billions-Webhook-Attempt: X-Billions-Signature: jcs-sha256=<64 lowercase hex characters> ``` > [!NOTE] > > The ID, event, and attempt headers identify a delivery but do not authenticate > it. Only `X-Billions-Signature` authenticates the payload, and the invoice API > remains the source of truth before changing order state. # Go-live checklist Source: https://docs.billions.works/integration/go-live-checklist Verify reliability and security before accepting production payments. ## Configuration * [ ] Production API credentials are stored in secret storage. * [ ] The production API host and version are configured. * [ ] Sandbox and production credentials are stored separately. * [ ] The production deployment cannot accidentally use the sandbox host. * [ ] The callback URL is public and uses HTTPS. * [ ] No credentials or sensitive payloads are written to logs. ## Payment behavior * [ ] Invoice creation uses a stable `order_no`. * [ ] Every logical create attempt has an idempotency key. * [ ] The Billions invoice ID is stored with the order. * [ ] Customers are redirected using the returned `invoice_url`. * [ ] Expired and failed invoices can be retried intentionally. ## Verification and reliability * [ ] Callback fields are not trusted as proof of payment. * [ ] Invoice state is retrieved from the authenticated API. * [ ] Webhook signature verification, when enabled, uses RFC 8785 JCS and the original API key secret. * [ ] Duplicate callbacks do not duplicate fulfillment. * [ ] Network timeouts and temporary failures are retried safely. * [ ] Monitoring alerts on repeated callback or API failures. ## Test cases * [ ] Successful payment * [ ] Abandoned checkout * [ ] Expired invoice * [ ] Duplicate callback * [ ] Callback arriving before the customer returns * [ ] Delayed payment confirmation * [ ] API timeout during invoice creation * [ ] API timeout during callback verification * [ ] Invalid or missing webhook signature * [ ] Signed money-operation retry with the same request ID * [ ] Reused request ID with different operation data returns `409` > [!NOTE] > > Add your production support contacts, status-page monitoring, and internal > environment-switching procedure before launch. # Integration overview Source: https://docs.billions.works/integration/overview Understand the components and responsibilities in a Billions payment integration. A Billions integration connects four components: 1. Your checkout, where the customer starts payment. 2. Your backend, which creates and verifies invoices. 3. The Billions hosted payment page. 4. Your callback endpoint, which reacts to invoice updates. ## Responsibilities | Component | Responsibility | | - | - | | Your frontend | Starts checkout and redirects to `invoice_url` | | Your backend | Stores credentials, creates invoices, and verifies status | | Billions | Hosts the payment experience and processes the payment | | Callback endpoint | Receives a notification and triggers API verification | ## Recommended integration order **1. Prepare your account** Obtain an API key and decide which environment you will use. **2. Create invoices** Implement invoice creation on your backend with stable order references and idempotency keys. **3. Redirect customers** Send the customer to the hosted payment URL returned by the API. **4. Handle callbacks safely** Expose an HTTPS endpoint and retrieve the invoice from the API before changing order state. **5. Test failure paths** Cover retries, expired invoices, duplicate callbacks, and delayed payments. **6. Go live** Switch to production credentials and complete the launch checklist. > [card] [Prepare the integration](/integration/prerequisites) > > Gather credentials and define your order model. > [card] [Follow the payment flow](/integration/payment-flow) > > Implement invoice creation through final order confirmation. If you already use a compatible SDK or payment module, see the [Unified Merchant API](/integration/unified-merchant-api) for the alternative setup and its supported operations. # Payment flow Source: https://docs.billions.works/integration/payment-flow Implement invoice creation, customer redirect, and payment confirmation. ## 1. Create the invoice on your backend Send the invoice currency, amount, your order reference, an idempotency key, and the callback URL. ```ts TypeScript theme={"theme":{"light":"github-dark","dark":"github-dark"}} const invoice = await api.createInvoice({ currency: 'USDT', amount: 100, order_no: 'ORDER-1001', idempotencyKey: 'ORDER-1001-attempt-1', callbackUrl: 'https://example.com/webhooks/billions', }); ``` ```python Python theme={"theme":{"light":"github-dark","dark":"github-dark"}} invoice = api.create_invoice( { "currency": "USDT", "amount": 100, "order_no": "ORDER-1001", "idempotencyKey": "ORDER-1001-attempt-1", "callbackUrl": "https://example.com/webhooks/billions", } ) ``` ```php PHP theme={"theme":{"light":"github-dark","dark":"github-dark"}} $invoice = $api->createInvoice([ 'currency' => 'USDT', 'amount' => 100, 'order_no' => 'ORDER-1001', 'idempotencyKey' => 'ORDER-1001-attempt-1', 'callbackUrl' => 'https://example.com/webhooks/billions', ]); ``` ```bash cURL theme={"theme":{"light":"github-dark","dark":"github-dark"}} curl --request POST \ --url "$BILLIONS_API_URL/public/v1/invoices/create" \ --header "Content-Type: application/json" \ --header "x-api-key: $BILLIONS_API_KEY" \ --data '{ "currency": "USDT", "amount": 100, "order_no": "ORDER-1001", "idempotencyKey": "ORDER-1001-attempt-1", "callbackUrl": "https://example.com/webhooks/billions" }' ``` Set `BILLIONS_API_URL=https://api-sandbox.billions.works` while testing and switch it to `https://api.billions.works` only for production. See [Create an invoice API](/api/create-invoice) for every request field and its current schema type. The TypeScript SDK defaults to **production** when `baseUrl` is omitted; set the sandbox host explicitly in test code. Persist at least: * The invoice `id` * `order_no` * The idempotency key used for the attempt * The current invoice `status` * The invoice expiration time, when `expires_at` is not `null` ## 2. Redirect to the hosted page Use the `invoice_url` from the response: ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} return response.redirect(invoice.invoice_url); ``` Do not construct or modify this URL yourself. ## 3. Treat the callback as a notification When the callback arrives, extract the invoice identifier and retrieve that invoice from the authenticated API. Callback delivery may be duplicated or delayed, so processing must be idempotent. ## 4. Update your order from the API response The invoice status can include: | Status | Suggested handling | | - | - | | `pending` | Keep the order awaiting payment | | `processing` | Show that payment is being processed | | `completed` | Mark the order as paid exactly once | | `expired` | Offer the customer a new payment attempt | | `failed` | Keep the order unpaid and allow recovery | | `refund_processing` | Show that a refund is being processed | | `refunded` | Mark the payment as refunded | | `aml_check` | Keep fulfillment on hold | | `aml_block` | Keep fulfillment blocked and follow your review process | See [Statuses and lifecycle](/api/statuses#invoice-statuses) for full status definitions, including the refund request states behind `refund_processing`. > [!WARNING] > > Status mapping is a business decision. Do not fulfill goods or services until > your backend has retrieved a `completed` invoice from the API. ## 5. Make completion idempotent Callbacks and status checks can run more than once. Use a transaction or conditional update so inventory, emails, and fulfillment happen only on the first transition to paid. ## Expiration and payment amount differences The current backend defaults an invoice without `expiresAt` to two hours after creation. Always store and use the response's `expires_at` instead of assuming that every invoice has the default lifetime. An expired or failed invoice requires a deliberate new payment attempt with a new idempotency key. Do not infer the treatment of an underpayment or overpayment from callback amount fields. No general automatic adjustment or refund policy is published for those cases. Retrieve the authoritative invoice, keep the order unpaid unless its status is `completed`, and reconcile any amount discrepancy with Billions support before fulfillment. # Prerequisites Source: https://docs.billions.works/integration/prerequisites Prepare credentials, endpoints, and order identifiers before coding. Before integrating, prepare the following: * A Billions API key stored only on your backend. * A public HTTPS callback endpoint. * A unique order reference in your system. * A persistent place to store the Billions invoice ID. * A strategy for retrying network requests safely. [Sign up in the Billions app](https://app.billions.works/sign-up), then open **Settings → API** to create separate API keys for sandbox and production. Use each key only with its matching environment. > [!NOTE] > > The SDKs use `https://api.billions.works` and public API version `v1` by > default. Use `https://api-sandbox.billions.works` while testing. ## Choose an environment | Environment | Base URL | Use it for | | - | - | - | | Sandbox | `https://api-sandbox.billions.works` | Integration development and testing | | Production | `https://api.billions.works` | Live payments and money operations | Keep separate credentials and configuration for each environment. Make the API base URL an environment variable so production cannot be selected accidentally: ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} BILLIONS_API_URL=https://api-sandbox.billions.works BILLIONS_API_KEY=your-sandbox-api-key ``` ## Keep credentials server-side Never embed the API key in browser code, a mobile application, a public repository, or logs. Load it from a secret manager or environment variable. For signed money operations and optional webhook signature verification, also store the original API key secret. It is displayed only once when the API key is created and must be treated as a server-side secret. ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} BILLIONS_API_SECRET=your-api-key-secret ``` ## Define two identifiers Use separate identifiers for separate jobs: | Field | Purpose | Recommendation | | - | - | - | | `order_no` | Connects the invoice to your business order | Use your stable internal order number | | `idempotencyKey` | Makes a create attempt safe to retry | Derive it from the order and payment attempt | An order may have more than one payment attempt. In that case, keep `order_no` stable and use a new idempotency key for each intentional attempt. > [!WARNING] > > Reuse an idempotency key only when retrying the same logical invoice creation. > Do not reuse one key for unrelated orders. Use the [public currencies endpoint](/api/overview#discover-the-api) instead of hard-coding a currency list. # Sandbox testing Source: https://docs.billions.works/integration/sandbox-testing Complete a sandbox payment with the test API or Sepolia test ETH, then verify callbacks. Sandbox and production have separate API hosts and credentials. For a custom integration, test against `https://api-sandbox.billions.works` before switching to production. You can finish a sandbox invoice either with the test API or by sending Sepolia test ETH to a TETH invoice. Neither option moves real funds. ## Prepare your test 1. [Sign in to the Billions app](https://app.billions.works), switch to **Sandbox**, and create a sandbox API key under **Settings → API**. 2. Configure your backend with the sandbox API URL and sandbox key. Keep both explicit; the [TypeScript SDK](/sdks/typescript) defaults to production if `baseUrl` is omitted. 3. Make your callback endpoint reachable over HTTPS. Create an invoice with a unique `order_no`, a stable `idempotencyKey`, a small supported amount, and `callbackUrl`. Store the returned `id` and `expires_at`. 4. Open the returned `invoice_url` to check the hosted checkout. The app's Sandbox **Demo Shop** creates a separate invoice; it does not test your callback endpoint. ## Option 1: Mark an invoice as paid with the sandbox API Send the invoice `id` returned by the create endpoint to `POST /public/v1/invoices/mark-as-paid` on the **sandbox host**. Use the same merchant's sandbox API key. This simulates a successful payment, updates the invoice to `completed`, and queues the normal `invoice.paid` callback when the invoice has a `callbackUrl`. No blockchain transfer is required. In the TypeScript example, `invoice` is the result of your earlier create call; for cURL, set `BILLIONS_INVOICE_ID` to that response's `id`. ```ts TypeScript theme={"theme":{"light":"github-dark","dark":"github-dark"}} const baseUrl = 'https://api-sandbox.billions.works'; const response = await fetch(`${baseUrl}/public/v1/invoices/mark-as-paid`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.BILLIONS_API_KEY!, }, body: JSON.stringify({ invoiceId: invoice.id }), }); if (!response.ok) throw new Error(`Sandbox payment failed: ${response.status}`); const paidInvoice = await response.json(); console.log(paidInvoice.status); // completed ``` ```bash cURL theme={"theme":{"light":"github-dark","dark":"github-dark"}} curl --request POST \ --url 'https://api-sandbox.billions.works/public/v1/invoices/mark-as-paid' \ --header 'Content-Type: application/json' \ --header "x-api-key: $BILLIONS_API_KEY" \ --data "{\"invoiceId\":\"$BILLIONS_INVOICE_ID\"}" ``` The invoice must belong to the authenticated merchant, have a valid UUID, still be unexpired, and be in `pending` or `processing`. A repeated call, an expired invoice, or another status returns `409`. An invalid UUID returns `400`; an unknown invoice or a request outside sandbox returns `404`. > [!WARNING] > > This endpoint is for testing only. It is unavailable in production; do not > put it in a production payment or fulfillment flow. ## Option 2: Pay with Sepolia test ETH The sandbox currency `TETH` is **native test ETH on Ethereum Sepolia** (chain ID `11155111`, internal ticker `ETH_TEST5`). It has no ERC-20 contract address. To exercise a real testnet transfer: 1. Create a sandbox invoice with `currency: "TETH"` and your `callbackUrl`. 2. Open its `invoice_url` and use the displayed Sepolia payment address and amount. Obtain Sepolia test ETH from a testnet faucet if needed. 3. From a wallet connected to **Sepolia**, send the requested test ETH to that address. Do not use Ethereum mainnet or send real ETH. 4. Wait for network confirmation, then retrieve the invoice from the API and check that your callback handler processed the update. Only TETH is listed as a Sepolia payment currency by the current [sandbox currencies endpoint](https://api-sandbox.billions.works/public/v1/currencies). Do not assume that other testnet ERC-20 tokens sent to the same address will pay this invoice. ## Verify the end-to-end result With either option, retrieve `GET /public/v1/invoices/{id}` using the sandbox API key. Confirm the invoice ID, `order_no`, `amount`, and `settlement_currency` match your stored attempt, then require `completed` before fulfillment. If you set `callbackUrl`, verify that your endpoint received the notification and still performed its own authenticated API lookup. The simulated payment tests your callback and order-state logic; the Sepolia transfer additionally tests the on-chain payment path. Repeat with duplicate callbacks, an abandoned checkout, expiration, and an API timeout. Verify that no test can create duplicate fulfillment. See the [go-live checklist](/integration/go-live-checklist) before replacing the sandbox host and credentials with production values. # Unified Merchant API Source: https://docs.billions.works/integration/unified-merchant-api Connect existing merchant-style SDKs and payment modules to Billions. The Unified Merchant API lets an existing payment integration create Billions invoices with limited changes to its configuration. Use this path if your application or store already has a compatible SDK or module. For a new integration, use the [Billions Public API](/api/overview) or an [official Billions SDK](/sdks/overview). ## Connect an existing integration **1. Create a Billions API key** In your Billions account settings, create an API key and save both values returned when it is issued: `apiKey` and `secretKey`. The secret is shown only once. Keep it on your server. **2. Change the API base URL** Replace the existing API base URL inside the SDK or module with `https://compatibility-cm.billions.works`. Keep the module's `/v1/...` endpoint paths. If its configuration contains a full URL ending in `/v1`, use `https://compatibility-cm.billions.works/v1` instead. **3. Enter the matching credentials** Set the module's Merchant UUID and payment secret to the values from the **same** Billions API key, following the mapping below. **4. Run a test payment** Create an invoice, open its returned payment URL, and confirm that the module receives a status update. Check the module's behavior for the operations it uses before enabling live checkout. | Existing integration field | Billions value | | - | - | | Merchant UUID | `apiKey` — the API key UUID, not the Billions merchant's internal ID | | Payment API Key / Secret | `secretKey` issued together with that `apiKey` | The payment secret is used to sign requests and callbacks. Older Billions API keys without a signing secret must be reissued. Keep the secret out of browser code, URLs, and logs. > [!NOTE] > > Change the URL used for **API requests**. Keep the checkout URL returned in > the invoice response and your own callback URL as they are; the module should > use the returned checkout URL without rewriting its host. ## SDKs and modules Compatible PHP SDKs can use this API for supported payment methods when their API base URL is configurable. Some community TypeScript clients require overriding the payment client's `baseUrl` instead; check whether that override still works when updating the package. Payment modules for the following platforms can be considered for this path when their API URL can be changed and their checkout uses the supported payment methods: * **Stores:** WooCommerce, PrestaShop, OpenCart, Magento, BigCommerce, CS-Cart, PHPShop, Easy Digital Downloads, Webasyst, VirtueMart. * **Billing and hosting:** WHMCS, BillManager, RootPanel, Clientexec, HostBill, Blesta, WISECP, Amember. * **Other platforms:** XenForo, Tilda, Azuriom, Invision Community, Watbot. Module versions and the methods they call vary. This list identifies the available modules, **not** a guarantee that every module and feature works unchanged. In particular, modules that require static wallets, refunds, mark-as-paid, or webhook resend need additional support beyond the current compatibility API. For WooCommerce, you can alternatively use the [official Billions plugin](/store-integrations/woocommerce). For BILLmanager 6, see the [official Billions module](/store-integrations/billmanager). For Tilda, see the [Billions Custom Payment Gateway setup](/store-integrations/tilda). For WHMCS, use the [official Billions gateway](/store-integrations/whmcs). ## Supported payment operations | Method | Path | Use | | - | - | - | | `POST` | `/v1/payment` | Create an invoice | | `POST` | `/v1/payment/info` | Retrieve an invoice by `uuid` or `order_id` | | `POST` | `/v1/payment/list` | List compatible invoices | | `POST` | `/v1/payment/services` | List available payment currencies and networks | | `POST` | `/v1/payment/qr` | Get a QR image for an invoice with a payment address | These endpoints use `merchant` and `sign` headers. The `sign` value is the lowercase MD5 hex digest of the Base64-encoded **exact JSON body bytes** followed by `secretKey`. It differs from the RFC 8785/HMAC signature used by [Billions signed money operations](/api/request-signing). Compatible SDKs and modules usually calculate this signature themselves. Invoices created here send compatible callbacks to `url_callback` when provided. Their `sign` is in the JSON body, and their format differs from [Billions-native webhooks](/integration/callbacks-and-security). Verify and process them according to the module's callback flow. > [!WARNING] > > Do not mix the two callback protocols. The Unified Merchant API uses a > lowercase MD5 `sign` in the callback JSON body and the `url_callback` field > when creating an invoice. The native Public API uses `callbackUrl` and can > send `X-Billions-Signature` using RFC 8785 JCS and HMAC-SHA256. A verifier > for one protocol does not authenticate the other. In either case, retrieve > the current invoice from the authenticated API before fulfillment. This is a partial payment API compatibility layer. Refunds, static wallets, mark-as-paid, webhook resend, and payout methods are not implemented in this API. Unsupported request options are rejected explicitly. *Every merchant must complete document verification and all applicable compliance checks before processing payments. API compatibility does not waive these requirements and is intended solely for lawful businesses and payments.* # Anti-Spam Policy Source: https://docs.billions.works/legal/anti-spam-policy Billions.works policy on unsolicited promotional messages. Billions.works does not permit the promotion of its website, products, or services through unsolicited bulk messages. This policy applies to our employees, contractors, affiliates, marketing partners, and any third parties acting on our behalf. We prohibit the use of purchased or harvested email lists, deceptive messaging, and unauthorized promotional campaigns. Any reported violation will be investigated, and appropriate corrective action will be taken, including termination of relationships with parties violating this policy. Suspected violations may be reported to our official support channels. # Legal Source: https://docs.billions.works/legal/overview Legal documents, policies, and service restrictions for Billions. This page provides a central index of the legal documents that govern the use of Billions services. New policies and agreements will be added here as they become available. > [!NOTE] > > The linked PDF documents are the authoritative versions of their respective > policies. The summaries on this page help you find the relevant document. ## Legal documents * [AML Policy](https://cdn.billions.works/legal/aml-policy.pdf) — explains the anti-money laundering, counter-terrorist financing, customer verification, monitoring, and risk-control requirements applied by Billions. * [Anti-Spam Policy](/legal/anti-spam-policy) — prohibits unsolicited bulk promotion and explains how reported violations are handled. * [Cookie Policy](https://cdn.billions.works/legal/cookie-policy.pdf) — explains how cookies and similar technologies may be used across Billions services. * [Privacy Policy](https://cdn.billions.works/legal/privacy-policy.pdf) — describes how personal data is collected, used, stored, and protected. * [Risk Disclosure](https://cdn.billions.works/legal/risk-disclosure.pdf) — outlines material risks associated with digital assets, payment processing, market conditions, and third-party services. * [Terms of Use](https://cdn.billions.works/legal/terms-of-use.pdf) — sets out the contractual terms, responsibilities, limitations, and acceptable use of Billions services. ## Prohibited countries and territories The following list is reproduced from **Annex 2 of the AML Policy** for easier reference. Billions services are not available in these countries and territories: 1. Belarus 2. Central African Republic 3. China 4. Democratic Republic of the Congo 5. Ukraine (temporarily occupied territories), including Crimea and Sevastopol and occupied parts of Donetsk, Kherson, Luhansk, and Zaporizhzhia 6. Guatemala 7. Haiti 8. Iran 9. Iraq 10. Lebanon 11. Libya 12. Macao SAR 13. Moldova 14. Myanmar 15. Nicaragua 16. North Korea 17. Russian Federation 18. Somalia 19. South Sudan 20. Sri Lanka 21. Sudan 22. Syria 23. Venezuela 24. Yemen 25. Zimbabwe > [!WARNING] > > Restrictions and regulatory requirements may change. Always refer to the > current [AML Policy](https://cdn.billions.works/legal/aml-policy.pdf) for the > authoritative list and its full context. # SDK overview Source: https://docs.billions.works/sdks/overview Choose an official SDK for your application. Official SDKs provide typed or idiomatic wrappers around the Billions public API. > [card] [TypeScript SDK](/sdks/typescript) > > For Node.js and TypeScript applications. Published as > `@billions-works/sdk-ts`. > [card] [Python SDK](/sdks/python) > > For synchronous and asynchronous Python 3.10+ applications. Published as > `py-billions-sdk`. > [card] [PHP SDK](/sdks/php) > > For PHP 8.1 and newer. Published as `billions-works/sdk-php`. All SDKs default to: * API host: `https://api.billions.works` * Public API version: `v1` For sandbox testing, configure the SDK base URL as `https://api-sandbox.billions.works`. ## Shared concepts The SDKs preserve public API field names such as `order_no`, `invoice_url`, and `expires_at`. All support idempotent invoice creation and invoice lookup by order number. They also provide country lookup, invoice fee estimates, webhook signature verification, authenticated invoice retrieval from a webhook, and signed withdrawals and refunds. Configure `secretKey` (or Python `secret_key`) with the original API secret for signing. The older `webhookSecret` / `webhook_secret` option is still accepted; if both are set, their values must match. Choose the SDK matching your backend runtime. API keys must never be used in frontend or mobile client code. # PHP SDK Source: https://docs.billions.works/sdks/php Install and use the official Billions PHP SDK. The PHP SDK requires PHP 8.1 or newer and uses Guzzle 7.8 or newer. > [card] [PHP SDK on GitHub](https://github.com/billions-works/billions-sdk-php) > > Browse the source code, examples, releases, and issue tracker. ## Installation ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} composer require billions-works/sdk-php ``` ## Initialize the client ```php theme={"theme":{"light":"github-dark","dark":"github-dark"}} createWithdrawal( ['currency' => 'EUR', 'amount' => '70', 'withdrawalMethodId' => 123], $requestId, ); $cryptoRefund = $api->refundCrypto( ['invoiceId' => 'invoice-id', 'withdrawToSameAddress' => true, 'reason' => 'Customer request'], $storedCryptoRefundRequestId, ); $fiatRefund = $api->refundFiat( ['invoiceId' => 'another-invoice-id', 'reason' => 'Customer request'], $storedFiatRefundRequestId, ); ``` The request ID argument is optional; the SDK generates a new UUID when it is omitted. See [Withdrawals and refunds](/api/withdrawals-and-refunds) for validation rules and response fields. ## Available methods ```php theme={"theme":{"light":"github-dark","dark":"github-dark"}} $api->getVersion(); $api->getCurrencies(); $api->getCountries(); $api->getMerchantInfo(); $api->estimateFees($payload); $api->createInvoice($payload); $api->createWithdrawal($payload, $requestId); $api->refundCrypto($payload, $requestId); $api->refundFiat($payload, $requestId); $api->getInvoice($invoiceId); $api->getInvoicesByOrderNo($orderNo); $api->getInvoiceFromWebhook($webhook); $api->verifyWebhookSignature($signatureHeader, $rawBody); $api->verifyInvoicePaid($invoiceId, $callbackData); $api->verifyInvoicePaid($callbackDataWithId); ``` API objects are returned as associative arrays with field names matching the public API JSON. `getCountries()` returns country codes and names. `estimateFees()` returns `amount`, `finalPrice`, `fee`, and `merchantReceiveAmount`, with optional `summaryFee`. ## Verify a webhook signature ```php theme={"theme":{"light":"github-dark","dark":"github-dark"}} $rawBody = file_get_contents('php://input'); $signature = $_SERVER['HTTP_X_BILLIONS_SIGNATURE'] ?? ''; if (!$api->verifyWebhookSignature($signature, $rawBody)) { http_response_code(401); exit; } $webhook = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); $invoice = $api->getInvoiceFromWebhook($webhook); ``` Set `secretKey` to the original API secret. The SDK parses the JSON, canonicalizes it according to RFC 8785 JCS, and verifies HMAC-SHA256 with a timing-safe comparison. It accepts the full `jcs-sha256=` header or a plain hex digest. Always use the retrieved invoice for payment decisions. ## Errors | Exception | Meaning | | - | - | | `BillionsApiException` | The API request failed; exposes `statusCode` and `responseBody` | | `InvoiceNotPaidException` | The retrieved invoice is not completed | | `CallbackVerificationException` | Callback data differs from the API invoice | See [Handle a callback](/examples/handle-a-callback) for verification code. # Python SDK Source: https://docs.billions.works/sdks/python Install and use the official Billions Python SDK. The Python SDK supports Python 3.10 or newer and uses `httpx` 0.27 or newer. It provides synchronous and asynchronous clients. > [card] [Python SDK on GitHub](https://github.com/billions-works/py-billions-sdk) > > Browse the source code, examples, releases, and issue tracker. ## Installation ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} pip install py-billions-sdk ``` ## Synchronous client Use `BillionsApi` as a context manager so its HTTP client is closed automatically: ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} import os from billions_sdk import BillionsApi with BillionsApi( os.environ["BILLIONS_API_KEY"], base_url=os.getenv("BILLIONS_API_URL"), secret_key=os.getenv("BILLIONS_API_SECRET"), ) as api: invoice = api.create_invoice( { "currency": "USDT", "amount": "100.00", "idempotencyKey": "ORDER-1001-attempt-1", "order_no": "ORDER-1001", "callbackUrl": "https://example.com/webhooks/billions", } ) print(invoice["invoice_url"]) ``` ## Withdrawals and refunds Both clients sign these requests automatically. Generate and store a distinct UUID for each intended money operation before calling the SDK. Reuse the same ID and payload if the response is lost. ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} from uuid import uuid4 with BillionsApi( os.environ["BILLIONS_API_KEY"], secret_key=os.environ["BILLIONS_API_SECRET"], ) as api: request_id = str(uuid4()) # Persist before making the request. withdrawal = api.create_withdrawal( {"currency": "EUR", "amount": "70", "withdrawalMethodId": 123}, request_id=request_id, ) crypto_request_id = str(uuid4()) # Persist a different ID. crypto_refund = api.refund_crypto( {"invoiceId": "invoice-id", "withdrawToSameAddress": True, "reason": "Customer request"}, request_id=crypto_request_id, ) fiat_request_id = str(uuid4()) # Persist a different ID. fiat_refund = api.refund_fiat( {"invoiceId": "another-invoice-id", "reason": "Customer request"}, request_id=fiat_request_id, ) ``` The `request_id` argument is optional, but passing one lets you safely retry an uncertain operation. On `AsyncBillionsApi`, await each of these methods. See [Withdrawals and refunds](/api/withdrawals-and-refunds) for the request rules and response fields. ## Asynchronous client `AsyncBillionsApi` exposes the same operations as coroutines: ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} import os from billions_sdk import AsyncBillionsApi async with AsyncBillionsApi(os.environ["BILLIONS_API_KEY"]) as api: invoice = await api.get_invoice("invoice-id") ``` ## Available methods Both clients expose the same methods. On `AsyncBillionsApi`, await HTTP operations; signature verification is synchronous. ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} api.get_version() api.get_currencies() api.get_countries() api.get_merchant_info() api.estimate_fees(payload) api.create_invoice(payload) api.create_withdrawal(payload, request_id=request_id) api.refund_crypto(payload, request_id=request_id) api.refund_fiat(payload, request_id=request_id) api.get_invoice(invoice_id) api.get_invoices_by_order_no(order_no) api.get_invoice_from_webhook(webhook) api.verify_webhook_signature(signature_header, raw_body) api.verify_invoice_paid(invoice_id, callback_data) api.verify_invoice_paid(callback_data_with_id) ``` `get_countries()` returns country codes and names. `estimate_fees()` returns `amount`, `finalPrice`, `fee`, and `merchantReceiveAmount`, with optional `summaryFee`. The default API host is `https://api.billions.works`, and the default public API version is `v1`. You can override both or inject a custom `httpx.Client` or `httpx.AsyncClient`. ## Verify a webhook signature ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} if not api.verify_webhook_signature(signature_header, raw_body): raise ValueError("Invalid webhook signature") invoice = api.get_invoice_from_webhook(webhook) ``` Set `secret_key` to the original API `secretKey` when creating the client. The method parses JSON text or bytes, canonicalizes it according to RFC 8785 JCS, and verifies HMAC-SHA256. It accepts `jcs-sha256=` or a plain hex digest. On `AsyncBillionsApi`, `get_invoice_from_webhook()` must be awaited. Use the authenticated invoice response for payment decisions even when the signature is valid. ## Process webhook events Use `get_invoice_from_webhook()` for both intermediate `invoice.status_changed` events and final `invoice.paid` events: ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} invoice = api.get_invoice_from_webhook(webhook) if invoice["status"] == "processing": # Update visible payment state, but do not fulfill the order. pass elif invoice["status"] == "completed": # Fulfill the order exactly once. pass ``` ## Verify a paid event ```python theme={"theme":{"light":"github-dark","dark":"github-dark"}} from billions_sdk import CallbackVerificationError, InvoiceNotPaidError try: invoice = api.verify_invoice_paid( webhook ) except (InvoiceNotPaidError, CallbackVerificationError): # Do not mark the order as paid. pass ``` `verify_invoice_paid()` accepts the current webhook envelope and legacy callback objects. It retrieves the authoritative invoice from the API, requires `completed` status, and compares the callback status and paid amount. Decimal forms such as `100`, `100.0`, and `100.000000000000000000` are treated as equivalent. ## Errors | Exception | Meaning | | - | - | | `BillionsApiError` | The API request failed; exposes `status_code` and `response_body` | | `InvoiceNotPaidError` | The authoritative invoice is not completed | | `CallbackVerificationError` | Callback data differs from the API invoice | Transport errors use `status_code == 0`. # TypeScript SDK Source: https://docs.billions.works/sdks/typescript Install and use the official Billions TypeScript SDK. > [card] [TypeScript SDK on GitHub](https://github.com/billions-works/billions-sdk-ts) > > Browse the source code, examples, releases, and issue tracker. ## Installation ```bash theme={"theme":{"light":"github-dark","dark":"github-dark"}} npm install @billions-works/sdk-ts ``` ## Initialize the client > [!WARNING] > > The TypeScript SDK uses `https://api.billions.works` when `baseUrl` is > omitted. Set `BILLIONS_API_URL=https://api-sandbox.billions.works` > explicitly before running any example with sandbox credentials. ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} import { BillionsApi } from '@billions-works/sdk-ts'; const api = new BillionsApi({ apiKey: process.env.BILLIONS_API_KEY!, secretKey: process.env.BILLIONS_API_SECRET, baseUrl: process.env.BILLIONS_API_URL, }); ``` Use `BILLIONS_API_URL=https://api-sandbox.billions.works` for testing. Omit `baseUrl` to use production. `secretKey` is the original secret issued with the API key; it enables signed money operations and webhook verification. ## Create an invoice ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} const invoice = await api.createInvoice({ currency: 'USDT', amount: 100, order_no: 'ORDER-1001', idempotencyKey: 'ORDER-1001-attempt-1', callbackUrl: 'https://example.com/webhooks/billions', }); console.log(invoice.invoice_url); ``` ## Withdrawals and refunds The SDK signs these operations automatically. Store a unique `requestId` for each intended operation before sending it; reuse that ID and the same payload if the response is lost. ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} import { randomUUID } from 'node:crypto'; const requestId = randomUUID(); // Persist with this withdrawal attempt. const withdrawal = await api.createWithdrawal( { currency: 'EUR', amount: '70', withdrawalMethodId: 123 }, { requestId }, ); // Persist a separate UUID for each refund attempt as well. const cryptoRequestId = randomUUID(); const cryptoRefund = await api.refundCrypto( { invoiceId: 'invoice-id', withdrawToSameAddress: true, reason: 'Customer request' }, { requestId: cryptoRequestId }, ); const fiatRequestId = randomUUID(); const fiatRefund = await api.refundFiat( { invoiceId: 'another-invoice-id', reason: 'Customer request' }, { requestId: fiatRequestId }, ); console.log(withdrawal.request.id); ``` Passing no second argument makes the SDK generate a fresh request ID. Save each ID before the call and reuse it with the identical payload on retry. See [Withdrawals and refunds](/api/withdrawals-and-refunds) for validation rules and response fields. ## Common operations ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} const version = await api.getVersion(); const currencies = await api.getCurrencies(); const countries = await api.getCountries(); const fees = await api.estimateFees({ currency: 'USDT', amount: '100' }); const invoice = await api.getInvoice('invoice-id'); const invoices = await api.getInvoicesByOrder('ORDER-1001'); const currentInvoice = await api.getInvoiceFromWebhook(webhook); const verifiedInvoice = await api.verifyInvoicePaid(webhook); ``` `getCountries()` returns country codes and names. `estimateFees()` returns `amount`, `finalPrice`, `fee`, and `merchantReceiveAmount`; `summaryFee` may also be present. Invoice objects include `invoice_url`, `order_no`, `expires_at`, `network_and_other_fees`, and `status`. ## Verify a webhook signature Pass the received `X-Billions-Signature` header and JSON body to the SDK: ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} const signature = String(request.headers['x-billions-signature'] ?? ''); const valid = await api.verifyWebhookSignature(signature, request.body); if (!valid) return response.sendStatus(401); // Always retrieve the current invoice before changing the order. const invoice = await api.getInvoiceFromWebhook(request.body); ``` The body may be the raw JSON text, UTF-8 bytes, or an already parsed object. The SDK canonicalizes the JSON according to RFC 8785 JCS, then verifies its HMAC-SHA256 signature using `secretKey`. It accepts both the full `jcs-sha256=` header and a plain hex digest. A valid signature does not replace the authenticated invoice lookup. ## Verify a payment callback `verifyInvoicePaid()` retrieves the invoice from the authenticated API, requires the invoice status to be `completed`, and compares the callback status and paid amount with the API result. ```ts theme={"theme":{"light":"github-dark","dark":"github-dark"}} import { CallbackVerificationError, InvoiceNotPaidError, } from '@billions-works/sdk-ts'; try { const invoice = await api.verifyInvoicePaid(webhook); // Transition invoice.order_no to paid exactly once. } catch (error) { if ( error instanceof InvoiceNotPaidError || error instanceof CallbackVerificationError ) { // Do not mark the order as paid. } } ``` `verifyInvoicePaid()` accepts the current webhook envelope as well as legacy callback objects. For intermediate events, use `getInvoiceFromWebhook()` and base any order state change on the API response. ## Handle errors Wrap API calls in `try/catch`, log a correlation identifier instead of secrets, and retry only operations that are safe to repeat. Reuse the same idempotency key when retrying the same invoice creation. # BILLmanager Source: https://docs.billions.works/store-integrations/billmanager Install and configure the official Billions payment module for BILLmanager 6. The official Billions module adds a payment method to BILLmanager 6. It creates invoices through the Billions Public API and sends customers to the hosted payment page. > [card] [BILLmanager module on GitHub](https://github.com/billions-works/billions-payments-for-billmanager) > > Browse installation packages, source code, releases, and issues. ## Requirements * BILLmanager 6 on a supported Linux host. * PHP CLI 7.4 or newer with XML/SimpleXML and mbstring. * A valid CA trust store and outbound HTTPS access to `api.billions.works`. * A publicly reachable HTTPS callback endpoint at `https:///mancgi/billionsresult.php`. * A Billions Public API key kept on the BILLmanager server. ## Install the module Download the package matching your host from the [latest GitHub release](https://github.com/billions-works/billions-payments-for-billmanager/releases/latest). The packages contain PHP code and are architecture-independent. | Host OS | Package | Installation command | | - | - | - | | Ubuntu 20.04 | `billions-billmanager-ubuntu20.deb` | `sudo apt install ./billions-billmanager-ubuntu20.deb` | | Ubuntu 24.04 | `billions-billmanager-ubuntu24.deb` | `sudo apt install ./billions-billmanager-ubuntu24.deb` | | Debian 12 | `billions-billmanager-debian12.deb` | `sudo apt install ./billions-billmanager-debian12.deb` | | Debian 13 | `billions-billmanager-debian13.deb` | `sudo apt install ./billions-billmanager-debian13.deb` | | Enterprise Linux 9 | `billions-billmanager-el9.noarch.rpm` | `sudo dnf install ./billions-billmanager-el9.noarch.rpm` | Run the matching command in the directory containing the downloaded package. If the new payment method does not appear after installation, restart BILLmanager. ## Configure the payment method Create a Billions payment method in BILLmanager and fill in these fields: | Field | Value | | - | - | | Public API key | The merchant `apiKey` issued by Billions. It stays on the server. | | Unique BILLmanager instance ID | A stable identifier of 3–30 ASCII letters, digits, underscores, or hyphens. Use a different ID for each installation sharing one API key. | | Public HTTPS origin of BILLmanager | For example, `https://billing.example.com`, without a path or trailing slash. | | Billions API origin | Optional. Leave empty for `https://api.billions.works`; use a configured test environment only when testing. | The module sends callbacks to `/mancgi/billionsresult.php?elid=`. The instance ID is part of the invoice idempotency key; keep it unchanged after the first payment. Enable the currencies supported by your merchant account. USD and EUR can be invoice currencies, while the customer chooses an available payment currency on the Billions checkout page. > [!NOTE] > > For sandbox testing, set the API origin to > `https://api-sandbox.billions.works` and use sandbox credentials. Restore the > production origin and credentials before accepting live payments. ## Payment confirmation The module creates an invoice with stable `order_no` and `idempotencyKey` values derived from the BILLmanager instance, payment method, and payment ID. Opening the payment page again reuses the stored invoice. When a callback arrives, the module retrieves the invoice from the authenticated Billions API. It compares the invoice ID, order number, amount, and settlement currency with the original payment before updating BILLmanager. The callback body and a customer's return from checkout are not payment proof. This flow needs the API key but does not require the API `secretKey`. * `completed` marks the payment paid. * `processing` marks it in progress. * `expired` or `failed` leaves it unpaid. Test a small payment before enabling the method for customers. If a payment remains unresolved after a missed notification, reconcile it against the Billions dashboard. ## Current limitations The module does not implement subscriptions or refunds. # Platform integrations Source: https://docs.billions.works/store-integrations/overview Connect Billions to supported stores and billing platforms. Platform integrations package invoice creation, customer redirection, and payment verification for a store or billing system. WooCommerce and WHMCS modules currently connect to production only; they do not have a sandbox API-host setting. BILLmanager is different: its API origin can be set to the [sandbox host](/store-integrations/billmanager#configure-the-payment-method) with sandbox credentials. For a custom integration, see [sandbox testing](/integration/sandbox-testing). > [card] [WooCommerce](/store-integrations/woocommerce) > > Accept Billions payments in Classic Checkout and WooCommerce Checkout Blocks. > [card] [BILLmanager](/store-integrations/billmanager) > > Accept Billions payments through the official BILLmanager 6 module. > [card] [WHMCS](/store-integrations/whmcs) > > Accept Billions payments through the official WHMCS gateway module. > [card] [Tilda](/store-integrations/tilda) > > Configure Tilda's Custom Payment Gateway to accept Billions payments. Existing payment modules may also be connected through the [Unified Merchant API](/integration/unified-merchant-api). This is a separate integration path from the official Billions modules. # Tilda Source: https://docs.billions.works/store-integrations/tilda Configure Billions as a Tilda Custom Payment Gateway. This guide covers the Billions integration with Tilda's [Custom Payment Gateway](https://help.tilda.cc/payments/custom-payment-gateway). Use this API URL for your production store: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} https://api.billions.works/integrations/tilda/create ``` For sandbox testing, use `https://api-sandbox.billions.works/integrations/tilda/create` with sandbox credentials. Tilda may require the custom gateway template to be enabled or approved for your project. ## 1. Create credentials In the Billions account for your chosen environment, open **Settings → API**, create an API key, and save both values when they are issued: | Billions credential | Tilda field | | - | - | | `API key` UUID | **Login** | | Original `Secret key` issued with that API key | **Secret for order signature** | Use the API key UUID in **Login**, not your Billions merchant ID. The secret is shown once when the key is created. Its hash, a webhook signature, or a signature from one order cannot replace it. Keep it out of URLs, browser code, and messages. This integration uses a regular Billions API key. ## 2. Create a Tilda gateway Open your Tilda site and go to **Site Settings → Payment Systems → Custom Payment Gateway → New payment system (for developers)**. If your project does not show this option, follow Tilda's [custom gateway approval process](https://help.tilda.cc/payments/custom-payment-gateway). | Tilda field | Value | | - | - | | Login | The Billions API key UUID | | Secret for order signature | The original secret from that same API key | | Currency | `USD` or `EUR` | | Country and widget language | Set only when needed; use a real supported country | | Title | For example, `Billions.works` | The site's cart currency must match the gateway currency. Changing the cart currency affects the **entire Tilda site**, not just a test page. Configure electronic receipts according to your merchant's jurisdiction. ## 3. Map the order fields In **Advanced settings**, set **API URL** to the production endpoint above (or the sandbox endpoint for testing) and use this field mapping: | Tilda field | Billions parameter | Setting | | - | - | - | | Login | `merchant` | Required; API key UUID | | Currency | `currency` | `USD` or `EUR` | | Language | `lang` | Optional; uppercase | | Country | `country` | Optional; uppercase | | Notification URL | `url_callback` | Required | | Order number | `order_id` | `_` | | Order description | `description` | Optional | | Order amount | `amount` | Dollars or euros, not cents; at most two decimal places | | Customer email | `email` | Optional | | Customer name | `name` | Optional | | Signature | `sign` | Required | | Products | `items` | One JSON array value; item fields include `name`, `quantity`, and `price` | Order time, phone number, image, and additional fields may be left blank when not needed. `url_return` is optional. Map Tilda's generated **Notification URL** to `url_callback`; Tilda then sends it with each order, so it does not need to be copied into your Billions dashboard. > [!NOTE] > > The endpoint accepts form fields and redirects to the Billions-hosted > checkout after a valid order. A repeated order with the same key, amount, > currency, and callback reuses its invoice. Changing those values for the > same order returns `409`. ## 4. Configure the order signature In Tilda's **Order signature** settings, select: | Setting | Value | | - | - | | Signature rules | All fields | | Excluded fields | `signature` (excluded by Tilda) and `sign` | | Ignore fields with empty values | On | | Field order | Alphabetical, ascending | | Delimiter | Vertical bar | | Add secret | First element | | Algorithm | MD5 | | HMAC, uppercase digest, Base64 | Off | Billions excludes `sign` and `signature`, sorts the remaining non-empty field names, joins their values with `|` after the secret, and compares the lowercase MD5 digest. Every additional non-empty field participates in the signature. See [Tilda's signature configuration guide](https://help.tilda.cc/payments/custom-payment-gateway). ## 5. Configure the payment notification In Tilda's **Notification** settings, use the same signature rules as the order and set: | Setting | Value | | - | - | | Successful payment indicator | Field `status`, value `paid` | | Transaction ID | Field `payment_id`, type UUID | | Successful processing response | `OK` | | Error response | `ERROR` | | Responses in JSON format | Off | Use `payment_id`, **not** `uuid`: the current Billions notification sends the invoice ID as `payment_id`. The notification is form-encoded and signed using the same secret. Tilda marks the order paid only after receiving a valid notification with the expected order number, amount, and status. A customer returning from the checkout page does not confirm payment. ## 6. Check the payment flow Publish a page with a product and shopping cart, then place a small order. The customer should be redirected to a Billions-hosted payment page. After payment, open **Tilda → Leads → Order details → Payment** and confirm that the order is marked paid. See [Tilda's guide to leads and orders](https://help.tilda.cc/leads). Before launch, compare the actual Tilda POST and notification against the configured field mapping and signature rules. In particular, confirm how `items` is serialized: the current endpoint accepts one field value and rejects repeated fields. Also test an invalid signature, changed amount or currency, duplicate orders, expired invoices, and notification retries. # WHMCS Source: https://docs.billions.works/store-integrations/whmcs Install and configure the official Billions payment gateway for WHMCS. The official Billions gateway adds hosted checkout to WHMCS. Customers select **Pay Now** on a WHMCS invoice and complete their payment on a Billions-hosted page. > [card] [WHMCS module on GitHub](https://github.com/billions-works/billions-payments-for-WHMCS) > > Find the installation package, source code, and release notes. ## Requirements * A currently supported WHMCS version running on PHP 8.2 or 8.3 with the cURL extension. * A Billions Public API key stored on the WHMCS server. * A public HTTPS **WHMCS System URL**, including its subdirectory if it has one. * Outbound HTTPS access from WHMCS to `https://api.billions.works` and a publicly reachable gateway callback URL. * Invoice currencies accepted by your Billions merchant account. USD and EUR can be invoice currencies. ## Install the module 1. Download the [latest module ZIP](https://github.com/billions-works/billions-payments-for-WHMCS/releases/latest/download/billions-payments-for-whmcs.zip). 2. Extract it into the **root directory of your WHMCS installation**. The package installs only these files: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} modules/gateways/billions.php modules/gateways/billions/Client.php modules/gateways/callback/billions.php ``` 3. In WHMCS, open **System Settings → Payment Gateways** and activate **Billions.works**. ## Configure the gateway | WHMCS setting | Value | | - | - | | Public API key | The API key issued by Billions. WHMCS stores it in a masked password field; keep it server-side. | | Unique WHMCS instance ID | A stable ID of 3–30 ASCII letters, digits, underscores, or hyphens. Use a different ID for each installation sharing a merchant account. | > [!WARNING] > > The current WHMCS module has **no sandbox mode or API-host setting**. Its > client is fixed to `https://api.billions.works/public/v1`, so even a staging > WHMCS installation calls production. Use a production key only when you > intend to create real invoices. For API sandbox testing, use a custom > integration rather than this module. Do not change the instance ID after accepting payments. It contributes to stable invoice identifiers and idempotency keys. Set the **WHMCS System URL** to its public HTTPS address, including any subdirectory. For example, if WHMCS runs at `https://billing.example.com/whmcs/`, Billions sends notifications to: ```text theme={"theme":{"light":"github-dark","dark":"github-dark"}} https://billing.example.com/whmcs/modules/gateways/callback/billions.php?invoiceid= ``` Ensure that this callback URL is reachable from the internet. Enable only currencies supported by your Billions merchant account. ## How payment confirmation works The gateway creates a Billions invoice when the customer selects **Pay Now**. Its stable `order_no` and `idempotencyKey` prevent a new invoice from being created whenever the WHMCS invoice page is reopened. If the WHMCS invoice amount changes after its Billions invoice is created, the gateway refuses to reuse the old payment link; an administrator must reconcile the payment. When a notification arrives, the gateway **retrieves the invoice from the authenticated Billions API**. It checks the order number, currency, amount, selected payment gateway, and current WHMCS balance before applying a verified `completed` payment. Other Billions statuses leave the WHMCS invoice unpaid. The callback body and a customer's return from checkout are not payment proof. This verification flow uses the API key and does not require an HMAC secret. Verify the checkout and callback with a controlled production payment before enabling the gateway for customers. If a notification cannot be verified, the callback returns a non-success HTTP response. Reconcile missed payments in the Billions dashboard. ## Current limitations * Subscriptions and automatic refunds are not implemented. * The Public API does not currently provide a checkout return URL for this gateway. Customers should return to WHMCS manually to view the updated invoice. For the latest installation details, see the [module README](https://github.com/billions-works/billions-payments-for-WHMCS#installation). # WooCommerce Source: https://docs.billions.works/store-integrations/woocommerce Install and configure the official Billions payment gateway for WooCommerce. The official plugin adds Billions as a WooCommerce payment gateway. It is standalone and does not require Composer, Guzzle, or the Billions PHP SDK. > [card] [WooCommerce plugin on GitHub](https://github.com/billions-works/billions-payments-for-woocommerce) > > Browse the plugin source code, releases, and issue tracker. ## Compatibility * PHP 8.1 or newer * WordPress 6.7 or newer * WooCommerce 10.5 or newer * Classic Checkout * Cart and Checkout Blocks * High-Performance Order Storage (HPOS) ## Install the plugin **1. Download the plugin** Download the [repository source ZIP](https://github.com/billions-works/billions-payments-for-woocommerce/archive/refs/heads/main.zip). This is the current source archive, not a versioned release asset. Check the plugin version and contents before installing it on a production site. **2. Upload it to WordPress** In WordPress, open **Plugins → Add New Plugin → Upload Plugin**, choose the ZIP file, and install it. **3. Activate the plugin** Activate **Billions Payments for WooCommerce**. **4. Configure the gateway** Open **WooCommerce → Settings → Payments**, select Billions, and configure the settings described below. ## Gateway settings | Setting | Purpose | | - | - | | Enable/Disable | Makes the Billions gateway available at checkout when the other required settings are valid. | | Title | Payment method name shown to customers. | | Description | Customer-facing checkout description. | | Billions API key | Production API key, stored as a password field. | | Invoice currency | Must match the WooCommerce order currency. | | Debug logging | Logs API request paths and errors in WooCommerce; it does not log the API key or full callback body. | > [!WARNING] > > This plugin has **no sandbox mode or API-host setting**. Its API client is > fixed to `https://api.billions.works`. A staging WordPress site using this > plugin still calls production. Do not enter a sandbox key expecting a test > payment; use the [custom API sandbox flow](/integration/sandbox-testing) for > integration tests instead. ## Payment behavior The plugin: 1. Creates a Billions invoice for the WooCommerce order. 2. Stores the invoice ID using WooCommerce order APIs. 3. Redirects the customer to the hosted payment page. 4. Receives the Billions callback. 5. Retrieves the invoice from the authenticated API. 6. Updates the order using only the API response. Invoice creation uses both an idempotency key and `order_no` derived from the site and order IDs, making retries safe. ## Currency behavior The store currency must match the configured Billions invoice currency. USD and EUR orders are supported directly: the invoice uses the store currency and the customer chooses an available cryptocurrency on the hosted payment page. A supported cryptocurrency can also be used as the WooCommerce base currency when it has been registered with WooCommerce. ## Current limitations * Refunds are not supported. * Subscriptions and recurring payments are not supported. * Saved payment methods are not supported. ## Troubleshooting * If the gateway is absent at checkout, confirm that it is enabled, has an API key, and its invoice currency matches the order currency. * If invoice creation fails, check the WooCommerce logs when debug logging is enabled and confirm that the server can reach `api.billions.works` over HTTPS. * If an order remains on hold after payment, check that the WooCommerce callback URL is public and the plugin can retrieve the invoice from the authenticated API. A customer's return from checkout does not mark it paid. > [!WARNING] > > Back up the site and test plugin updates in a staging environment before > deploying them to a production store.