# Norpo API — integration guide for AI coding assistants

> **For humans:** give this whole file to your AI assistant (Claude, ChatGPT, Cursor, Copilot…) and say:
> *"Integrate Norpo payments into my project using this guide."*
> It contains everything the assistant needs. Keep your API key out of the chat — put it in an environment variable yourself.

> **For the AI assistant:** follow this file exactly. Do not invent endpoints, fields or statuses that are not listed here. If something is not covered, tell the user to ask support@norpo.io instead of guessing.

---

## 1. What Norpo is

Norpo is a payment gateway. The merchant's server creates a payment through the API, sends the customer to the payment page Norpo returns, and is told when the payment is paid. The customer pays by card, Apple Pay, Google Pay, local methods or crypto. **The merchant is paid out straight to their own wallet. Payouts may be sent in ETH, USDC or USDT (Polygon or BEP-20), or POL, Polygon's native token.** No company or KYB is required.

- API base URL: `https://api.norpo.io`
- All requests and responses are JSON (`Content-Type: application/json`).
- Fee: 4.8% for card and local methods, 1.5% for crypto paid to the merchant's wallet. It is deducted from what the merchant receives; the customer pays the invoice amount.

## 2. Before you write code — what the user must do in the dashboard

1. Create an account at https://norpo.io (dashboard).
2. **Dashboard → Settings → Payout wallet:** an EVM address (0x…) from a wallet the user controls (not an exchange deposit address). Payouts may be sent in ETH, USDC or USDT (Polygon or BEP-20), or POL, Polygon's native token. Live payments are refused without it.
3. **Dashboard → Settings → API keys:** create a key. Two kinds:
   - `nrp_test_sk_…` — **test mode**: payments behave like real ones (statuses, callbacks, webhooks) but no money moves. Use it while building.
   - `nrp_live_sk_…` — real payments.
4. Store the key in an environment variable, e.g. `NORPO_API_KEY`. **Never** put it in frontend code, a mobile app, a public repo or a URL.

## 3. Hard rules for the integration

1. **Server-side only.** Every Norpo API call goes from the merchant's backend. The browser only ever sees the payment page URL.
2. **Callback / webhook URLs must be public HTTPS.** `localhost`, `127.0.0.1`, private IPs (`10.*`, `192.168.*`, `172.16–31.*`), `*.local` and cloud metadata addresses are rejected — and pointing callbacks at them is treated as an attack: the caller's IP is blocked from sign-in for an hour, and repeated attempts suspend the account. **While developing locally, do not send `callbackUrl` at all** — poll `GET /v1/payments/:id` instead, or use a public tunnel (ngrok, Cloudflare Tunnel) URL.
3. **Never mark an order paid from a callback alone.** On every callback or webhook, either verify the signature (JSON format) or re-fetch `GET /v1/payments/:id` and act only if `status` is `paid`.
4. **Be idempotent.** Callbacks and webhooks can arrive more than once. Use the payment id (or your `reference`) to make "mark order paid" happen once.
5. **One payment per checkout attempt.** Create a new payment each time a customer starts paying; store the returned `paymentId` with your order.
6. Amounts are plain numbers in the invoice currency (`49.99`, not cents).

## 4. Authentication

```
Authorization: Bearer nrp_live_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

A test key sees only test payments; a live key sees only live payments.

## 5. Create a payment

`POST /v1/payments`

| Field | Type | Required | Notes |
|---|---|---|---|
| `amount` | number | yes | Invoice amount, e.g. `49.99` |
| `currency` | string | no, default `USD` | Invoice currency. Supported for billing: `USD`, `EUR`, `GBP`, `CAD`, `AUD`, `CHF`, `SEK`, `INR`, `JPY`. `CAD`, `SEK` and `INR` also unlock Interac, Klarna and UPI for customers in those countries. |
| `reference` | string ≤120 | recommended | Your own order id. Echoed back in every response, callback and webhook. |
| `customerEmail` | string | no | Pre-fills the payment page; receipts go there. |
| `redirectUrl` | URL | recommended | Where the customer is sent after paying. |
| `callbackUrl` | public HTTPS URL | recommended in production | Norpo calls it when the payment is paid or failed. See §8. |
| `callbackFormat` | `"json"` \| `"query"` | no | `"json"` = signed POST (recommended). Omitted = legacy unsigned GET with query parameters. |

Request:

```bash
curl https://api.norpo.io/v1/payments \
  -H "Authorization: Bearer $NORPO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 49.99,
    "currency": "USD",
    "reference": "order_1042",
    "customerEmail": "buyer@example.com",
    "redirectUrl": "https://shop.example.com/orders/1042/thanks",
    "callbackUrl": "https://shop.example.com/api/norpo/callback",
    "callbackFormat": "json"
  }'
```

Response `201`:

```json
{
  "paymentId": "cmvqp1oy6001nq91odds25kju",
  "reference": "order_1042",
  "status": "pending",
  "order": {
    "kind": "onramp",
    "url": "https://api.norpo.io/return/p/cmvqp1oy6001nq91odds25kju",
    "checkoutUrl": "https://pay.norpo.io/…",
    "settleAsset": "USDC"
  },
  "callbackFormat": "json",
  "callbackSecret": "cbsec_…"
}
```

What to do with it:

- **Save** `paymentId` (and `callbackSecret` if present — it is returned **only once**, per payment) with your order.
- **Redirect the customer to `order.url`.** It is Norpo's page that opens the checkout, waits for the payment, confirms it and sends the customer back to your `redirectUrl`. `order.checkoutUrl` is the payment page itself; prefer `order.url`. Treat both URLs as opaque: do not parse, build or modify them.
- In test mode `order.url` points to Norpo's **test checkout**, where the payment is resolved with a "Pay" / "Fail" button.

## 6. Check a payment

`GET /v1/payments/:paymentId`

```json
{
  "paymentId": "cmvqp1oy6001nq91odds25kju",
  "reference": "order_1042",
  "status": "paid",
  "amount": 49.99,
  "currency": "USD",
  "settleAsset": "USDC",
  "current": null,
  "attempts": [{ "provider": "norpo", "kind": "onramp", "status": "paid" }]
}
```

`status` is one of:

| Status | Meaning | What to do |
|---|---|---|
| `pending` | Waiting for the customer | Keep the order open |
| `paid` | Paid. Funds go to the merchant's wallet | Fulfil the order (once) |
| `failed` | The payment did not go through | Let the customer try again with a new payment |
| `expired` | Abandoned | Same as failed |

`GET /v1/payments?limit=20` lists recent payments (max 100).

## 7. Test mode

With a `nrp_test_sk_…` key:

- `POST /v1/payments` returns `"test": true` and an `order.url` to the test checkout.
- Resolve a test payment from code (useful in automated tests):

```bash
curl -X POST https://api.norpo.io/v1/payments/$PAYMENT_ID/simulate \
  -H "Authorization: Bearer $NORPO_TEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"outcome":"paid"}'      # or "failed"
```

Callbacks and webhooks fire exactly as for live payments (with `"test": true`). Switching to production = replacing the test key with the live key; nothing else changes.

## 8. Per-payment callback (`callbackUrl`)

Sent once the payment becomes `paid` or `failed`.

### 8a. `callbackFormat: "json"` — signed POST (recommended)

Headers:

```
Content-Type: application/json
Norpo-Event: payment.paid            (or payment.failed)
Norpo-Signature: t=1793130763367,v1=5f2c…   (t = Unix time in milliseconds)
```

Body:

```json
{
  "id": "evt_9c1d…",
  "event": "payment.paid",
  "created": 1793130763,
  "data": {
    "id": "cmvqp1oy6001nq91odds25kju",
    "status": "paid",
    "reference": "order_1042",
    "amount": 49.99,
    "currency": "USD"
  }
}
```

Verify: `v1` must equal `hex(HMAC-SHA256(callbackSecret, "<t>.<raw request body>"))`. Use the **raw** body bytes, compare in constant time, and reject timestamps older than 5 minutes.

### 8b. Default — unsigned GET

`GET <callbackUrl>?status=paid&payment_id=…&reference=order_1042&amount=49.99&currency=USD` (`&test=1` in test mode).
It is **not signed**: always confirm with `GET /v1/payments/:id` before fulfilling.

Respond `200` quickly. If your endpoint was down, poll `GET /v1/payments/:id` — the payment status is always the source of truth.

## 9. Account webhooks (optional, all payments)

Add an endpoint in **Dashboard → Webhooks** (public HTTPS URL). The signing secret is shown once.

Events: `payment.settled`, `payment.failed`, `payout.sent`, `refund.created`.

Headers: `Norpo-Signature` (same format and check as §8a, with the endpoint secret), `Norpo-Event`, `Norpo-Delivery`.

`payment.settled` body:

```json
{
  "id": "evt_…",
  "event": "payment.settled",
  "created": 1793130763,
  "data": {
    "paymentId": "cmvqp1oy6001nq91odds25kju",
    "reference": "order_1042",
    "amount": 49.99,
    "currency": "USD",
    "customerEmail": "buyer@example.com",
    "txHash": "0x…",
    "amountReceived": "47.59"
  }
}
```

Failed deliveries are retried up to 6 times: after 30 s, 2 min, 10 min, 1 h, 3 h, 6 h. Return any `2xx` to acknowledge.

## 10. Signature verification — copy-paste

**Node.js (Express)**

```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();

// Raw body is required for the signature check.
app.post('/api/norpo/callback', express.raw({ type: 'application/json' }), async (req, res) => {
  const header = req.get('Norpo-Signature') || '';
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const secret = await loadCallbackSecretFor(/* your order */);           // saved from the create response
  const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.${req.body}`).digest('hex');
  const fresh = Math.abs(Date.now() - Number(parts.t)) < 5 * 60 * 1000;
  const ok = fresh && parts.v1 && expected.length === parts.v1.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
  if (!ok) return res.status(400).end();

  const evt = JSON.parse(req.body);
  if (evt.event === 'payment.paid') await markOrderPaidOnce(evt.data.reference, evt.data.id);
  res.sendStatus(200);
});
```

**PHP**

```php
$raw = file_get_contents('php://input');
parse_str(str_replace(',', '&', $_SERVER['HTTP_NORPO_SIGNATURE'] ?? ''), $sig);
$expected = hash_hmac('sha256', $sig['t'] . '.' . $raw, $callbackSecret);
if (!hash_equals($expected, $sig['v1'] ?? '') || abs(time() * 1000 - (int)$sig['t']) > 300000) {
  http_response_code(400); exit;
}
$evt = json_decode($raw, true);
if ($evt['event'] === 'payment.paid') { mark_order_paid_once($evt['data']['reference'], $evt['data']['id']); }
http_response_code(200);
```

**Python (Flask)**

```python
import hmac, hashlib, json, time
from flask import request, abort

@app.post("/api/norpo/callback")
def norpo_callback():
    raw = request.get_data()
    sig = dict(p.split("=", 1) for p in request.headers.get("Norpo-Signature", "").split(",") if "=" in p)
    expected = hmac.new(callback_secret.encode(), f"{sig.get('t')}.".encode() + raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig.get("v1", "")) or abs(time.time() * 1000 - int(sig.get("t", 0))) > 300_000:
        abort(400)
    evt = json.loads(raw)
    if evt["event"] == "payment.paid":
        mark_order_paid_once(evt["data"]["reference"], evt["data"]["id"])
    return "", 200
```

## 11. Minimal end-to-end flow (Node.js)

```js
// 1) Customer clicks "Pay" → your server creates the payment
const r = await fetch('https://api.norpo.io/v1/payments', {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.NORPO_API_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    amount: order.total, currency: 'USD', reference: order.id,
    customerEmail: order.email,
    redirectUrl: `https://shop.example.com/orders/${order.id}/thanks`,
    callbackUrl: 'https://shop.example.com/api/norpo/callback',
    callbackFormat: 'json',
  }),
});
if (!r.ok) throw new Error((await r.json()).message);          // show the message to the merchant/admin
const p = await r.json();
await db.orders.update(order.id, { norpoPaymentId: p.paymentId, norpoCallbackSecret: p.callbackSecret });

// 2) Send the customer to the payment page
res.redirect(p.order.url);

// 3) On your "thanks" page (or a cron), confirm before fulfilling
const s = await (await fetch(`https://api.norpo.io/v1/payments/${order.norpoPaymentId}`, {
  headers: { Authorization: `Bearer ${process.env.NORPO_API_KEY}` },
})).json();
if (s.status === 'paid') await markOrderPaidOnce(order.id, s.paymentId);
```

## 12. Errors

Errors come as `{ "error": "...", "message": "human-readable reason" }` (validation errors: `"error": "validation_error"`). Show `message` to the merchant — it says what to fix.

| HTTP | Typical cause | Fix |
|---|---|---|
| 400 | Invalid field, or `callbackUrl` is not a public HTTPS URL | Fix the request; never use localhost/private URLs |
| 401 | Missing or wrong API key | `Authorization: Bearer nrp_…` |
| 403 | Account suspended, or a test-only action with a live key | Contact support / use the right key |
| 404 | Payment not found for this key (test vs live) | Use the key that created it |
| 422 | No payout wallet; wallet refused; amount below the method's minimum | Add an EVM payout wallet (0x…) in Settings; raise the amount |
| 429 | Too many requests | Back off and retry |
| 503 | Payment network temporarily unavailable | Retry in a minute |

## 13. Ready-made plugins (no code)

- **WooCommerce:** "Norpo Payment Gateway" plugin
- **WHMCS** module and **XenForo** add-on
- Download: https://norpo.io/downloads/norpo-payment-gateway.zip (WooCommerce), https://norpo.io/downloads/norpo-whmcs.zip, https://norpo.io/downloads/norpo-xenforo.zip

If the user's platform is one of these, recommend the plugin instead of a custom integration.

## 14. Checklist before going live

- [ ] Payout wallet (EVM 0x… address) set in Settings
- [ ] API key only on the server, in an environment variable
- [ ] Full flow tested with `nrp_test_sk_…`: paid and failed, including your callback handler
- [ ] Callback signature verified (JSON) or payment re-fetched (GET) before fulfilment
- [ ] Fulfilment is idempotent
- [ ] `callbackUrl` / webhook URL is public HTTPS
- [ ] Test key swapped for `nrp_live_sk_…`

Support: support@norpo.io · Telegram @norpoio · Docs: https://norpo.io/docs
