# openbcp Sandbox — integration guide (for developers and AI agents)

The sandbox is a free test copy of the openbcp payment API. It simulates USDT (BEP-20)
payments: **no blockchain, no real funds, no wallet needed**. Every payment is
confirmed automatically about 3 seconds after the invoice is created.

Integrate against the sandbox first, then go live by changing **two values**
(base URL and API key). No code changes.

| | Sandbox | Live |
|---|---|---|
| Base URL | `https://sandbox.openbcp.com` | `https://openbcp.com` |
| API key | starts with `test_` | your live key |
| Money | none (simulated) | real USDT on BSC |
| Data retention | invoices deleted after **24 hours** | permanent |
| Get a key | Dashboard → Integration → Sandbox | Dashboard → Integration → API Key |

Keep both in environment variables so going live is a config change:

```
PAYGATE_URL=https://sandbox.openbcp.com
PAYGATE_API_KEY=test_xxxxxxxxxxxxxxxx
```

## Same API, same SDKs

Endpoints, headers, request/response fields, statuses and webhook signing are identical
to live. Existing SDKs (Python, Node.js, Go, MCP) work unchanged: set the base URL and API key.
Extra fields only in the sandbox: `"sandbox": true` in API responses and webhook payloads.

## Authentication

Send the sandbox key in the `X-openbcp-Api-Key` header, server-side only.
Missing/invalid key -> `401`. More than 60 requests/minute per key -> `429`.

## 1. Create a payment

`POST {PAYGATE_URL}/api/v1/payment` — `Content-Type: application/json`

| Field | Type | Required | Notes |
|---|---|---|---|
| `amount_usdt` | string | yes | Your price, e.g. `"29.99"`. Min `0.01`, max `1000000`. Platform fee (default `0.03`) is added on top. |
| `external_id` | string | no | Your order id; returned in webhooks. |
| `callback_url` | string | no | Webhook URL. **Must be publicly reachable** http(s). `localhost`, private IPs and cloud-metadata addresses are rejected with `400`. |
| `success_url` | string | no | Customer is redirected here after payment. http(s) only. |
| `metadata` | object | no | Free-form JSON. |
| `sandbox_scenario` | string | no | Sandbox only. `paid` (default), `overpaid`, `partial`, `expired`, `unpaid`. See below. |

Response `201`:

```json
{
  "status": "success",
  "sandbox": true,
  "invoice_id": 42,
  "checkout_token": "<64 hex chars>",
  "deposit_address": "0x0000000000000000000000001234abcd5678ef90",
  "amount_usdt": "30.020000",
  "merchant_amount_usdt": "29.990000",
  "platform_fee_usdt": "0.03",
  "payment_url": "https://sandbox.openbcp.com/pay/<checkout_token>",
  "status_url": "https://sandbox.openbcp.com/api/v1/payment/42/status?token=<checkout_token>",
  "success_url": null,
  "network": "BEP20",
  "token": "USDT",
  "expires_at": "2026-01-01T12:05:00Z"
}
```

Redirect the customer to `payment_url`. The hosted checkout shows a TEST MODE banner and
completes by itself. `deposit_address` is synthetic — **never send real crypto to it**.
Invoices expire after 5 minutes.

## 2. Check status

* `GET /api/v1/payment/{invoice_id}/status?token={checkout_token}` (or header `X-openbcp-Api-Key`)
  -> `{ "payment_status": "UNPAID|PARTIAL|PAID|OVERPAID|EXPIRED|CANCELLED", "confirmations": 3, "required_confirmations": 3, "transactions": [...] }`
  Without the token or key the response is `404`.
* `GET /api/v1/payment/{invoice_id}` (API key) -> full invoice incl. `external_id`, `created_at`.
* `GET /api/v1/payment/{invoice_id}/webhooks` (API key, **sandbox only**) -> delivery log:
  `[{ "callback_url", "delivered", "attempts", "last_status_code", "last_attempt_at", "error" }]`.

Treat `PAID` and `OVERPAID` as success.

## 3. Receive the webhook

The sandbox POSTs JSON to `callback_url` when the invoice reaches `PAID`, `OVERPAID`, `PARTIAL`,
`EXPIRED` or `CANCELLED`. Headers:

* `X-openbcp-Timestamp`: unix seconds
* `X-openbcp-Signature`: hex `HMAC-SHA256(key = your API key, message = "<timestamp>.<raw body>")`

Always verify on the **raw request body** before parsing, and reject timestamps older than 5 minutes.

```python
import hmac, hashlib, time

def verify(api_key: str, raw_body: bytes, timestamp: str, signature: str) -> bool:
    if abs(time.time() - int(timestamp)) > 300:
        return False
    expected = hmac.new(api_key.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)
```

Payload:

```json
{
  "invoice_id": 42, "sandbox": true, "external_id": "order-123", "status": "PAID",
  "amount_usdt": "30.020000", "amount_received": "30.020000", "shortfall": "0.000000",
  "overpaid_by": "0.000000", "deposit_address": "0x00...", "txid": "0xsandbox...",
  "paid": true, "paid_at": "2026-01-01T12:00:03Z"
}
```

Respond with any `2xx` quickly. `5xx`/timeouts are retried (up to 5 times, increasing delay);
a `4xx` is treated as "declined" and not retried. Redirects are not followed.
Fulfil orders from the webhook (or by polling status), **never** from the browser redirect alone.

Testing webhooks from your laptop: expose it with a tunnel (`ngrok http 3000`,
`cloudflared tunnel --url http://localhost:3000`) and use that public URL as `callback_url`.

## Test scenarios (`sandbox_scenario`)

| Value | What happens | Final status |
|---|---|---|
| `paid` (default) | Full payment confirmed after ~3 s | `PAID` |
| `overpaid` | 110% confirmed after ~3 s | `OVERPAID` |
| `partial` | 50% confirmed after ~3 s, invoice later expires | `PARTIAL` (then `EXPIRED`) |
| `expired` | No payment; marked expired after ~3 s | `EXPIRED` |
| `unpaid` | Nothing happens until natural expiry (5 min) | `UNPAID` -> `EXPIRED` |

## Errors

All errors: `{"status":"error","message":"..."}`.

| HTTP | Meaning |
|---|---|
| 400 | Invalid/missing field (amount out of range, bad URL, unknown scenario, blocked `callback_url`) |
| 401 | Missing or invalid API key |
| 404 | Unknown invoice, or missing/wrong `token` on the status endpoint |
| 429 | Rate limit (60 req/min per key) or daily cap (200 invoices/day) |
| 501 | Endpoint not available in sandbox (e.g. `/resume`) |

## Not simulated in the sandbox

Real blockchain behaviour, fees/gas, refunds, resume-payment, withdrawals, wallets and the
dashboard totals. Use `sandbox_scenario=partial` to exercise underpayment handling.

## Minimal end-to-end example

```bash
curl -s -X POST "$PAYGATE_URL/api/v1/payment" \
  -H "X-openbcp-Api-Key: $PAYGATE_API_KEY" -H "Content-Type: application/json" \
  -d '{"amount_usdt":"10.00","external_id":"order-1","callback_url":"https://YOUR-TUNNEL/webhook"}'
# open payment_url in a browser -> status flips to PAID in ~3 seconds -> your webhook fires
```

```python
from paygate import PayGateClient   # official Python SDK
client = PayGateClient(base_url=os.environ["PAYGATE_URL"], api_key=os.environ["PAYGATE_API_KEY"])
inv = client.create_payment(amount_usdt="10.00", external_id="order-1",
                            callback_url="https://YOUR-TUNNEL/webhook")
print(inv.payment_url)
paid = client.poll_until_paid(inv.invoice_id)
```

## Go-live checklist

1. Webhook handler verifies the signature and is idempotent (retries can deliver twice).
2. Fulfilment keyed on `external_id` / `invoice_id`, only on `PAID`/`OVERPAID`.
3. Handled `PARTIAL`, `EXPIRED`, `CANCELLED`.
4. Set `PAYGATE_URL=https://openbcp.com` and `PAYGATE_API_KEY=<live key>`; set your receiving
   wallet address in the dashboard (Wallet tab). Make one small real payment to verify.
5. Never ship a `test_` key to production: sandbox payments move no money.

Machine-readable spec: `/docs/sandbox-openapi.json`
