> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coinstack.net/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> The CoinStack API base URL is https://coinstack.net/api/v1. Authenticate with an API key sent as 'Authorization: Bearer sk_...' from a server, never from a browser. Every response is a JSON object with 'success' and 'response'. Amounts are strings; token amounts on quotes and payments are in the token's smallest unit. Fulfil an order when its checkout status is 'completed', not when the customer returns to success_url. Verify the CoinStack-Signature header on every webhook using the raw request body. The OpenAPI file is at https://docs.coinstack.net/openapi.json.

# Webhooks

> Get a signed request on your server when a checkout or payment changes.

A webhook is a URL on your server. When a checkout or payment changes, CoinStack sends a signed `POST` request to it, so your system learns about the change without asking.

## Add a webhook

In the dashboard, open **Developers**, select **Add webhook**, and enter the URL. Or use the API:

```bash theme={null}
curl https://coinstack.net/api/v1/webhooks \
  -H "Authorization: Bearer $COINSTACK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/webhooks/coinstack",
    "events": ["checkout.completed", "checkout.expired"]
  }'
```

The response includes the signing secret. It starts with `whsec_` and is shown only once, so store it now.

* The URL must start with `https://` and use a domain name, not an IP address.
* Leave `events` out to receive every event.
* An account can have up to 10 webhooks.

## Events

| Event | Sent when |
| - | - |
| `checkout.confirming` | A payment was detected and is being processed. |
| `checkout.partial` | Less than the full amount has been paid and the checkout is still open. |
| `checkout.completed` | The checkout was paid in full. |
| `checkout.expired` | The checkout closed before it was paid in full. |
| `checkout.resolved` | You marked an underpaid checkout as settled. |
| `payment.pending` | A payment was detected. |
| `payment.completed` | A payment's USDC reached your wallet. |
| `payment.refunded` | A payment could not be processed and was returned to the sender. |

Most integrations only need `checkout.completed`. Add `checkout.expired` if you release stock or cancel orders when a checkout closes unpaid.

## The request

Every event is a `POST` with a JSON body and a `CoinStack-Signature` header.

```json theme={null}
{
  "event_id": "e41b7c92-3a5d-4f8e-b1c6-9d2a7f4e0b85",
  "kind": "checkout.completed",
  "data": {
    "checkout": {
      "checkout_id": "8f3b2c1e-5d47-4a9b-b6e0-2c7f1a9d4e53",
      "quote_id": "0x5c1d9a7e3b6f48021e9d7c4a5b3f6e8d1a2c4b6e8f0a1c3e5d7f9b2a4c6e8d0f",
      "email": "customer@example.com",
      "reference": "order-1042",
      "description": "Order #1042",
      "success_url": "https://example.com/orders/1042/thanks",
      "cancel_url": "https://example.com/cart",
      "currency": "USD",
      "status": "completed",
      "amount": "25.00000000",
      "value": "25.00000000",
      "received": "24.77643200",
      "fee": "0.20000000",
      "underpaid": false,
      "overpaid": false,
      "late": false,
      "metadata": { "order_id": "1042" },
      "created_at": "2026-12-02T16:20:11.482913Z",
      "updated_at": "2026-12-02T16:24:37.905218Z",
      "expires_at": "2026-12-03T16:20:11.482501Z",
      "completed_at": "2026-12-02T16:24:37.905218Z",
      "url": "https://coinstack.net/checkout/8f3b2c1e-5d47-4a9b-b6e0-2c7f1a9d4e53"
    }
  },
  "created_at": "2026-12-02T16:24:37.905218Z"
}
```

| Field | Description |
| - | - |
| `event_id` | The event's ID. It stays the same when an event is retried or resent. |
| `kind` | The event name. |
| `data` | `checkout` for `checkout.*` events and `payment` for `payment.*` events. |
| `created_at` | When the event happened. |

`data` holds the checkout or payment as it was when the event happened. The fields are the same as in the [API reference](https://docs.coinstack.net/api-reference/webhook-events/checkout-event.md).

## Verify the signature

Anyone can send a request to your URL, so check that each one came from CoinStack before you act on it.

The `CoinStack-Signature` header looks like this:

```
CoinStack-Signature: t=1796228678,v1=0e6494f309fc69039d6469d87098d20bf41703c430fb059d36e057beeb6ce6a4
```

`t` is the time the request was signed, in Unix seconds. `v1` is the signature. To check it:

1. Read `t` and `v1` from the header.
2. Join `t`, a full stop and the raw request body into one string: `t.body`.
3. Compute the HMAC-SHA256 of that string, using your signing secret as the key, and write it as lowercase hex.
4. Compare the result with `v1` using a constant-time comparison.
5. Reject the request if `t` is more than five minutes old.

Use the body exactly as it arrived. If your framework parses the JSON and you turn it back into text, the bytes can differ and the signature will not match.

```javascript Node.js theme={null}
import crypto from "node:crypto";
import express from "express";

const app = express();
const secret = process.env.COINSTACK_WEBHOOK_SECRET;

function verify(header, body) {
  const parts = Object.fromEntries(
    String(header).split(",").map((part) => part.split("=")),
  );
  const expected = Buffer.from(
    crypto.createHmac("sha256", secret).update(`${parts.t}.${body}`).digest("hex"),
  );
  const given = Buffer.from(String(parts.v1));

  return (
    given.length === expected.length &&
    crypto.timingSafeEqual(given, expected) &&
    Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300
  );
}

app.post(
  "/webhooks/coinstack",
  express.raw({ type: "application/json" }),
  (request, response) => {
    const body = request.body.toString("utf8");

    if (!verify(request.get("CoinStack-Signature"), body)) {
      return response.status(400).send("Invalid signature");
    }

    const event = JSON.parse(body);

    if (event.kind === "checkout.completed") {
      // Mark the order for event.data.checkout.checkout_id as paid.
    }

    response.sendStatus(200);
  },
);

app.listen(3000);
```

```python Python theme={null}
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

app = Flask(__name__)
secret = os.environ["COINSTACK_WEBHOOK_SECRET"]


def verify(header, body):
    parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
    timestamp = parts.get("t", "")
    signed = timestamp.encode() + b"." + body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()

    return (
        hmac.compare_digest(parts.get("v1", "").encode(), expected.encode())
        and timestamp.isdigit()
        and abs(time.time() - int(timestamp)) <= 300
    )


@app.post("/webhooks/coinstack")
def coinstack_webhook():
    body = request.get_data()

    if not verify(request.headers.get("CoinStack-Signature", ""), body):
        return "Invalid signature", 400

    event = json.loads(body)

    if event["kind"] == "checkout.completed":
        # Mark the order for event["data"]["checkout"]["checkout_id"] as paid.
        pass

    return "", 200
```

```php PHP theme={null}
<?php

$secret = getenv('COINSTACK_WEBHOOK_SECRET');
$body = file_get_contents('php://input');
$parts = [];

foreach (explode(',', $_SERVER['HTTP_COINSTACK_SIGNATURE'] ?? '') as $part) {
    $pair = explode('=', $part, 2);

    if (count($pair) === 2) {
        $parts[$pair[0]] = $pair[1];
    }
}

$timestamp = $parts['t'] ?? '';
$expected = hash_hmac('sha256', $timestamp . '.' . $body, $secret);

if (!hash_equals($expected, $parts['v1'] ?? '') || abs(time() - (int) $timestamp) > 300) {
    http_response_code(400);
    exit('Invalid signature');
}

$event = json_decode($body, true);

if ($event['kind'] === 'checkout.completed') {
    // Mark the order for $event['data']['checkout']['checkout_id'] as paid.
}

http_response_code(200);
```

The signing secret is the whole string, including the `whsec_` prefix.

## Respond to an event

Answer with any `2xx` status within 10 seconds. Anything else, including a redirect, counts as a failure.

Do slow work after you respond. Save the event, return `200`, and process it in the background.

## Retries

If a delivery fails, CoinStack tries again after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 8 hours and 8 hours. That is 8 attempts over about a day. After the last one, the event is not sent again unless you resend it.

## Handle events safely

* **Expect duplicates.** The same event can arrive more than once. Record each `event_id` you have handled and skip repeats, or make your handler safe to run twice.
* **Do not rely on order.** Events can arrive out of order, and a retried event can arrive after a newer one. If the order matters, [get the checkout](https://docs.coinstack.net/api-reference/checkouts/get-a-checkout.md) when an event arrives and act on its current `status`.
* **Check that the checkout is yours.** Match `checkout_id` to an order you created before you fulfil anything.

## Test and resend

**Send test** on a webhook in the dashboard sends a sample `checkout.completed` event and shows whether your server accepted it. [Send a test event](https://docs.coinstack.net/api-reference/webhooks/send-a-test-event.md) does the same through the API. The sample checkout is for 10 US dollars and has the reference `test`.

Under **Recent events** in the dashboard you can see each event, whether it was delivered, and send it again. [List events](https://docs.coinstack.net/api-reference/events/list-events.md) and [Resend an event](https://docs.coinstack.net/api-reference/events/resend-an-event.md) do the same through the API.

## Rotate the secret

If a signing secret may have leaked, select **Rotate secret** on the webhook in the dashboard, or call [Rotate a webhook secret](https://docs.coinstack.net/api-reference/webhooks/rotate-a-webhook-secret.md). The old secret stops working straight away, so update your server as soon as you have the new one.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.