# Server helpers

> createInvoice and verifyWebhook for Node (@intents-fi/sdk) and PHP (intents-php): create the invoice, verify the webhook over the raw body, ship on invoice.paid.

```ts
import { createInvoice, verifyWebhook, WebhookSignatureError } from "@intents-fi/sdk";

// Your server, when the customer picks "Pay with crypto":
const invoice = await createInvoice({ amount: "42.00", reference: order.id });
// → invoice.url for a redirect, or invoice.id + invoice.clientSecret for the pop-up

// Your webhook route:
const event = await verifyWebhook(rawBody, request.headers, process.env.INTENTS_WEBHOOK_SECRET);
if (event.type === "invoice.paid") await markPaid(event.data.reference);
```

**Ship the order only on the `invoice.paid` webhook.** The browser's `onPaid` callback, the
pop-up's `paid` message and the redirect to your thank-you page are for the customer's screen.
Anyone can fire them from a browser console; only a verified webhook comes from us.

## createInvoice

`createInvoice(params, options?)` is `POST /v0/invoices` with one rule added: **`reference` is
required**. Pass your own order id. Calling it twice for the same order (a retried request, a double
click, a refreshed page) returns the same invoice rather than a second one. The repeat carries
`clientSecret: null`, because the secret is only shown once: keep the first one, or use `url`.

| Option | Default |
|---|---|
| `apiKey` | `INTENTS_SECRET_KEY`. Use an `ik_test_` key while you build |
| `baseUrl` | `INTENTS_API_URL`, else `https://api.intents.fi` |
| `fetch` | the global `fetch` |
| `client` | an existing `createClient()` instance, instead of the three above |

It throws `IntentsError` with the API's error code (`INVALID_REQUEST`, `UNAUTHORIZED`, …). Every
field is the generated `CreateInvoiceRequest` type:



```bash title="curl"
curl https://api.intents.fi/v0/invoices \
  -X POST \
  -H 'authorization: Bearer $INTENTS_SECRET_KEY' \
  -H 'x-intents-affiliate: <x-intents-affiliate>' \
  -H 'content-type: application/json' \
  -d '{
       "amount": "49.00",
       "settlement": {
         "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
         "address": "0x6A3fB91c7D8e45A2b0C1fE97D3a8B52c4e7F10dA"
       },
       "reference": "order_1042",
       "description": "Pro plan — 1 month",
       "customerEmail": "ana@example.com",
       "successUrl": "https://northwood.example/thanks"
     }'
```

```ts title="TypeScript"
const response = await fetch("https://api.intents.fi/v0/invoices", {
  method: "POST",
  headers: {
    authorization: `Bearer ${process.env.INTENTS_SECRET_KEY}`,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    "amount": "49.00",
    "settlement": {
      "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "address": "0x6A3fB91c7D8e45A2b0C1fE97D3a8B52c4e7F10dA"
    },
    "reference": "order_1042",
    "description": "Pro plan — 1 month",
    "customerEmail": "ana@example.com",
    "successUrl": "https://northwood.example/thanks"
  }),
});

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(`${error.code}: ${error.message}`);
}
const data = await response.json();
```

```python title="Python"
import os
import httpx

response = httpx.post(
    "https://api.intents.fi/v0/invoices",
    headers={"authorization": f"Bearer {os.environ['INTENTS_SECRET_KEY']}"},
    json={
        "amount": "49.00",
        "settlement": {
            "asset": "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "address": "0x6A3fB91c7D8e45A2b0C1fE97D3a8B52c4e7F10dA"
        },
        "reference": "order_1042",
        "description": "Pro plan — 1 month",
        "customerEmail": "ana@example.com",
        "successUrl": "https://northwood.example/thanks"
    },
)
response.raise_for_status()
data = response.json()
```



## verifyWebhook

`verifyWebhook(rawBody, headers, secret, { toleranceSeconds? })` checks the
`X-Intents-Signature` HMAC and that its timestamp is within five minutes, then returns the event,
typed. It throws `WebhookSignatureError`; its `reason` is one of `raw_body_required`,
`missing_secret`, `missing_signature`, `malformed_signature`, `timestamp_out_of_tolerance`,
`signature_mismatch` or `invalid_payload`. Answer `400` when it throws and do nothing else.

### It needs the raw body

The signature covers the bytes we sent. A framework that has parsed the JSON for you has thrown
those bytes away, and a re-serialised body never verifies.

**Next.js (App Router)**

```ts
export async function POST(request: Request) {
  const raw = await request.text();
  try {
    const event = await verifyWebhook(raw, request.headers, process.env.INTENTS_WEBHOOK_SECRET);
    // …
  } catch (e) {
    if (e instanceof WebhookSignatureError) return new Response("bad signature", { status: 400 });
    throw e;
  }
  return new Response("ok");
}
```

**Express.** Mount `express.raw` on the webhook route, before any `express.json()`:

```ts
app.post("/webhooks/intents", express.raw({ type: "application/json" }), async (req, res) => {
  const event = await verifyWebhook(req.body, req.headers, process.env.INTENTS_WEBHOOK_SECRET);
  // req.body is a Buffer here
  res.sendStatus(200);
});
```

**Hono**

```ts
app.post("/webhooks/intents", async (c) => {
  const event = await verifyWebhook(await c.req.text(), c.req.raw.headers, c.env.INTENTS_WEBHOOK_SECRET);
  return c.text("ok");
});
```

It runs on WebCrypto, so the same call works in Node 18+, edge runtimes and Workers.

### The event types

```ts
type WebhookEvent = InvoiceEvent | WebhookPingEvent;
// event.type: "invoice.processing" | "invoice.underpaid" | "invoice.paid" | "invoice.expired"
//           | "invoice.canceled" | "invoice.needs_review" | "webhook.test"
```

Switching on `event.type` narrows `event.data` to the invoice (the same shape as
`GET /v0/invoices/{id}`), or to the ping. Three small helpers:

| Helper | True when |
|---|---|
| `isFinal(event)` | the invoice will not change again: `paid`, `expired` or `canceled` |
| `isInvoiceEvent(event)` | it is an `invoice.*` event, not the `webhook.test` ping |
| `isTestEvent(event)` | it came from **Send test event**: a ping, or a sample invoice (`sample: true`). Acknowledge it, never ship on it |

### What it does not do for you

- **Duplicates.** The same event can arrive twice: a retry, or **Resend** in the dashboard, which
  re-sends the same `event.id`. `verifyWebhook` accepts both, because both are genuine. Make
  `markPaid` idempotent, or record `event.id` and skip one you have seen.
- **Order.** Events can arrive out of order. Act on `event.data.status`, and never move an order
  backwards.

## PHP

The same two calls for PHP, in one file with no framework: [intents-php](/docs/platform/server-sdk-php).

See [Verify and test webhooks](/docs/platform/verify-webhooks) for duplicates, ordering and the test tools, and [Webhooks](/docs/platform/webhooks) for the events and the retry schedule. The whole flow is in [Add crypto to your existing checkout](/docs/checkout/add-crypto).

---

Source: https://intents.fi/docs/platform/server-sdk · The whole corpus: https://intents.fi/docs/llms-full.txt
