# Verify MoonPay webhooks

The `Moonpay-Signature-V2` header lets you confirm that a delivery came from MoonPay and wasn't changed on the way. It holds a timestamp `t` and `s`, a lowercase hex HMAC-SHA256 of the timestamp, a period and the raw body, keyed with your account's webhook API key. MoonPay's Platform docs include a complete Express example, and they document no replay window.

Agent skill: `npx skills add hookdeck/webhook-skills --skill moonpay-webhooks` ([details](https://hookdeck.com/webhooks/moonpay/skill))

> Independent reference generated from hookdeck/webhook-registry (commit ff7f882, 20 Nov 2026). [MoonPay's official docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview).

[Overview](https://hookdeck.com/webhooks/moonpay) · [Webhook events (11)](https://hookdeck.com/webhooks/moonpay/events) · [MCP events](https://hookdeck.com/webhooks/moonpay/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/moonpay/verify) · [Production guide](https://hookdeck.com/webhooks/moonpay/guide-duplicates-ordering-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/moonpay/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `Moonpay-Signature-V2` Format: t=<unix seconds>,s=<lowercase hex> | [MoonPay docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview) |
| Scheme | `HMAC-SHA256, hex` | [MoonPay docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview) |
| Signed material | `{t}.{raw body}` t from the Moonpay-Signature-V2 header, a literal period, then the raw request body. A JSON parser changes the bytes, so verify before you parse. | [MoonPay docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview) |
| Legacy signature | `Moonpay-Signature` Same t=,s= form as V2, but keyed with the endpoint's signing secret rather than the webhook API key. | [MoonPay docs](https://dev.moonpay.com/api-reference/widget/webhooks.openapi.json) |
| What to build | `Split the header into 't' and 's', recompute the hex HMAC-SHA256 of '{t}.{raw body}' with your webhook API key, and compare it to 's' in constant time.` | [MoonPay docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview) |
| Key | `shared secret` | [MoonPay docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview) |

## MoonPay webhook secret

The key is your account's webhook API key, from the dashboard's Developers page. It isn't the endpoint's signing secret, which only the legacy header uses. Keep it in an environment variable, not in source code.

- Where to find it: the Developers page of the MoonPay dashboard.
- Scope: MoonPay calls it your account's webhook API key, so the docs show no separate key per endpoint.
- Test and live mode: you create one webhook setting per mode. The docs don't say whether the key differs by mode, though their sample key is `wk_test_123`.
- Keep it on your server: MoonPay says to keep the webhook API key off the client.
- Legacy header: `Moonpay-Signature` uses the endpoint's signing secret, so a key that works for one header fails on the other.

Source: [MoonPay docs](https://dev.moonpay.com/api-reference/platform/webhooks/overview)

## Code

### Express

From [webhook-skills: skills/moonpay-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/moonpay-webhooks/examples/express/src/index.js)

```javascript
// Generated with: moonpay-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');

const app = express();

// Optional replay window in seconds. Off by default (0): retries and replays, including
// Hookdeck's, carry the original timestamp, so a window would reject late redeliveries.
// Set MOONPAY_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
// treated as 0, with a warning.
let warnedInvalidTolerance = false;
function timestampToleranceSeconds() {
  const raw = (process.env.MOONPAY_TIMESTAMP_TOLERANCE_SECONDS ?? '').trim();
  if (raw === '') return 0;
  if (!/^\d+$/.test(raw)) {
    if (!warnedInvalidTolerance) {
      console.warn(`MOONPAY_TIMESTAMP_TOLERANCE_SECONDS=${JSON.stringify(raw)} is not a whole number of seconds; the timestamp check is off`);
      warnedInvalidTolerance = true;
    }
    return 0;
  }
  return Number(raw);
}
timestampToleranceSeconds(); // surface an invalid value at startup

/**
 * Verify a MoonPay webhook signature (POST webhooks only).
 *
 * Header: `Moonpay-Signature-V2: t=<unix seconds>,s=<lowercase hex>`
 * s = hex HMAC-SHA256 over `<t>.<raw body>`, keyed with the webhook API key as a string.
 * GET callbacks sign the query string instead and are NOT covered here.
 *
 * @param {Buffer|string} rawBody - Raw request body (do NOT re-stringify parsed JSON)
 * @param {string} header - `Moonpay-Signature-V2` header value
 * @param {string} apiKey - Webhook API key (e.g. wk_test_xxxxx)
 * @param {number} toleranceSeconds - Max age of `t`; 0 turns the check off (default from env)
 * @param {number} nowSeconds - Current time in seconds (injectable for tests)
 * @returns {boolean} Whether the signature is valid (and fresh, if a window is set)
 */
function verifyMoonpayWebhook(
  rawBody,
  header,
  apiKey,
  toleranceSeconds = timestampToleranceSeconds(),
  nowSeconds = Date.now() / 1000
) {
  if (!header || !apiKey) return false;
  const parts = header.split(',').map((p) => p.trim().split('='));
  const t = parts.find(([k]) => k === 't')?.[1];
  const signature = parts.find(([k]) => k === 's')?.[1];
  if (!t || !/^\d+$/.test(t) || !signature) return false;

  // Opt-in replay window: retries and replays carry the original `t`.
  if (toleranceSeconds > 0 && Math.abs(nowSeconds - Number(t)) > toleranceSeconds) return false;

  const expected = crypto
    .createHmac('sha256', apiKey)
    .update(`${t}.`)
    .update(rawBody)
    .digest('hex');

  try {
    return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
  } catch {
    return false; // length mismatch = invalid
  }
}

// MoonPay webhook endpoint - must use the raw body for signature verification.
// '*/*' reads the raw bytes whatever the content type, so every request can be verified.
app.post('/webhooks/moonpay', express.raw({ type: '*/*' }), (req, res) => {
  const header = req.headers['moonpay-signature-v2'];
  const apiKey = process.env.MOONPAY_WEBHOOK_API_KEY;

  if (!header) {
    return res.status(400).send('Missing Moonpay-Signature-V2 header');
  }
  if (!apiKey) {
    console.error('MOONPAY_WEBHOOK_API_KEY is not set');
    return res.status(500).send('Webhook API key not configured');
  }
  if (!Buffer.isBuffer(req.body) || !verifyMoonpayWebhook(req.body, header, apiKey)) {
    console.error('MoonPay webhook signature verification failed');
    return res.status(400).send('Invalid signature');
  }

  // Parse only after verification.
  let event;
  try {
    event = JSON.parse(req.body.toString());
  } catch {
    return res.status(400).send('Invalid JSON');
  }

  const { type, data } = event;
  switch (type) {
    case 'transaction_created':
      console.log(`Buy transaction created: ${data?.id} (${data?.status})`);
      break;
    case 'transaction_updated':
      console.log(`Buy transaction updated: ${data?.id} (${data?.status})`);
      break;
    case 'transaction_failed':
      console.log(`Buy transaction failed: ${data?.id} (${data?.failureReason})`);
      break;
    case 'sell_transaction_created':
      console.log(`Sell transaction created: ${data?.id} (${data?.status})`);
      break;
    case 'sell_transaction_updated':
      console.log(`Sell transaction updated: ${data?.id} (${data?.status})`);
      break;
    case 'sell_transaction_failed':
      console.log(`Sell transaction failed: ${data?.id} (${data?.failureReason})`);
      break;
    case 'sell_transaction_requote_required':
      console.log(`Sell transaction needs a requote: ${data?.id}`);
      break;
    case 'identity_check_updated':
      console.log(`Identity check updated: ${data?.id} (${data?.status})`);
      break;
    case 'customer.identity_status_updated': // Platform webhook
      console.log(`Customer ${data?.customerId} identity status: ${data?.status}`);
      break;
    default:
      console.log(`Unhandled event type: ${type}`);
  }
  // Your code: persist / forward. Delivery is at-least-once and unordered: dedupe on type + data.id +
  // data.updatedAt (Platform events also repeat the `webhook-id` header), and use updatedAt
  // rather than arrival order to decide which state is newer.

  // Respond 2xx within 5 seconds; anything else is a failed delivery and is retried.
  res.status(200).send('OK');
});

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// Export app for testing
module.exports = { app, verifyMoonpayWebhook };

// Start server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/moonpay`);
  });
}
```

### Next.js

From [webhook-skills: skills/moonpay-webhooks/examples/nextjs/app/webhooks/moonpay/route.ts](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/moonpay-webhooks/examples/nextjs/app/webhooks/moonpay/route.ts)

```typescript
// Generated with: moonpay-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyMoonpayWebhook } from '../../../lib/moonpay';

interface MoonpayEvent {
  type: string;
  data?: Record<string, any>;
  externalCustomerId?: string;
}

export async function POST(request: NextRequest) {
  // Read the raw body BEFORE parsing - the signature is over the exact bytes, whatever the content type.
  const rawBody = await request.text();
  const header = request.headers.get('moonpay-signature-v2');
  const apiKey = process.env.MOONPAY_WEBHOOK_API_KEY;

  if (!header) {
    return NextResponse.json({ error: 'Missing Moonpay-Signature-V2 header' }, { status: 400 });
  }
  if (!apiKey) {
    console.error('MOONPAY_WEBHOOK_API_KEY is not set');
    return NextResponse.json({ error: 'Webhook API key not configured' }, { status: 500 });
  }
  if (!verifyMoonpayWebhook(rawBody, header, apiKey)) {
    console.error('MoonPay webhook signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  // Parse only after verification.
  let event: MoonpayEvent;
  try {
    event = JSON.parse(rawBody);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  const { type, data } = event;
  switch (type) {
    case 'transaction_created':
      console.log(`Buy transaction created: ${data?.id} (${data?.status})`);
      break;
    case 'transaction_updated':
      console.log(`Buy transaction updated: ${data?.id} (${data?.status})`);
      break;
    case 'transaction_failed':
      console.log(`Buy transaction failed: ${data?.id} (${data?.failureReason})`);
      break;
    case 'sell_transaction_created':
      console.log(`Sell transaction created: ${data?.id} (${data?.status})`);
      break;
    case 'sell_transaction_updated':
      console.log(`Sell transaction updated: ${data?.id} (${data?.status})`);
      break;
    case 'sell_transaction_failed':
      console.log(`Sell transaction failed: ${data?.id} (${data?.failureReason})`);
      break;
    case 'sell_transaction_requote_required':
      console.log(`Sell transaction needs a requote: ${data?.id}`);
      break;
    case 'identity_check_updated':
      console.log(`Identity check updated: ${data?.id} (${data?.status})`);
      break;
    case 'customer.identity_status_updated': // Platform webhook
      console.log(`Customer ${data?.customerId} identity status: ${data?.status}`);
      break;
    default:
      console.log(`Unhandled event type: ${type}`);
  }
  // Your code: persist / forward. Delivery is at-least-once and unordered: dedupe on type + data.id +
  // data.updatedAt (Platform events also repeat the `webhook-id` header), and use updatedAt
  // rather than arrival order to decide which state is newer.

  // Respond 2xx within 5 seconds; anything else is a failed delivery and is retried.
  return NextResponse.json({ received: true });
}
```

### FastAPI

From [webhook-skills: skills/moonpay-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/moonpay-webhooks/examples/fastapi/main.py)

```python
# Generated with: moonpay-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import logging
import os
import time

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

# Optional replay window in seconds. Off by default (0): retries and replays, including
# Hookdeck's, carry the original timestamp, so a window would reject late redeliveries.
# Set MOONPAY_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
# treated as 0, with a warning.
_warned_invalid_tolerance = False


def timestamp_tolerance_seconds() -> int:
    global _warned_invalid_tolerance
    raw = (os.getenv("MOONPAY_TIMESTAMP_TOLERANCE_SECONDS") or "").strip()
    if not raw:
        return 0
    if not (raw.isascii() and raw.isdigit()):
        if not _warned_invalid_tolerance:
            logging.getLogger(__name__).warning(
                "MOONPAY_TIMESTAMP_TOLERANCE_SECONDS=%r is not a whole number of seconds; the timestamp check is off",
                raw,
            )
            _warned_invalid_tolerance = True
        return 0
    return int(raw)


timestamp_tolerance_seconds()  # surface an invalid value at startup


def verify_moonpay_webhook(
    raw_body: bytes,
    header: str | None,
    api_key: str,
    tolerance: int | None = None,
    now: float | None = None,
) -> bool:
    """Verify a MoonPay webhook signature (POST webhooks only).

    Header: ``Moonpay-Signature-V2: t=<unix seconds>,s=<lowercase hex>``
    s = hex HMAC-SHA256 over ``<t>.<raw body>``, keyed with the webhook API key as a string.
    GET callbacks sign the query string instead and are NOT covered here.
    """
    if not header or not api_key:
        return False
    pairs = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
    t = next((v for k, v in pairs if k == "t"), None)
    signature = next((v for k, v in pairs if k == "s"), None)
    if not t or not (t.isascii() and t.isdigit()) or not signature:
        return False

    # Opt-in replay window: retries and replays carry the original `t`.
    if tolerance is None:
        tolerance = timestamp_tolerance_seconds()
    if tolerance > 0 and abs((time.time() if now is None else now) - int(t)) > tolerance:
        return False

    expected = hmac.new(
        api_key.encode("utf-8"), t.encode("utf-8") + b"." + raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature.encode(), expected.encode())


@app.post("/webhooks/moonpay")
async def moonpay_webhook(request: Request):
    # Read the raw body BEFORE parsing - the signature is over the exact bytes.
    raw_body = await request.body()
    header = request.headers.get("moonpay-signature-v2")
    api_key = os.environ.get("MOONPAY_WEBHOOK_API_KEY")

    if not header:
        raise HTTPException(status_code=400, detail="Missing Moonpay-Signature-V2 header")
    if not api_key:
        raise HTTPException(status_code=500, detail="Webhook API key not configured")
    if not verify_moonpay_webhook(raw_body, header, api_key):
        raise HTTPException(status_code=400, detail="Invalid signature")

    # Parse only after verification.
    try:
        event = json.loads(raw_body)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON")
    if not isinstance(event, dict):
        raise HTTPException(status_code=400, detail="Expected a JSON object")

    event_type = event.get("type")
    data = event.get("data") or {}

    if event_type == "transaction_created":
        print(f"Buy transaction created: {data.get('id')} ({data.get('status')})")
    elif event_type == "transaction_updated":
        print(f"Buy transaction updated: {data.get('id')} ({data.get('status')})")
    elif event_type == "transaction_failed":
        print(f"Buy transaction failed: {data.get('id')} ({data.get('failureReason')})")
    elif event_type == "sell_transaction_created":
        print(f"Sell transaction created: {data.get('id')} ({data.get('status')})")
    elif event_type == "sell_transaction_updated":
        print(f"Sell transaction updated: {data.get('id')} ({data.get('status')})")
    elif event_type == "sell_transaction_failed":
        print(f"Sell transaction failed: {data.get('id')} ({data.get('failureReason')})")
    elif event_type == "sell_transaction_requote_required":
        print(f"Sell transaction needs a requote: {data.get('id')}")
    elif event_type == "identity_check_updated":
        print(f"Identity check updated: {data.get('id')} ({data.get('status')})")
    elif event_type == "customer.identity_status_updated":  # Platform webhook
        print(f"Customer {data.get('customerId')} identity status: {data.get('status')}")
    else:
        print(f"Unhandled event type: {event_type}")
    # Your code: persist / forward. Delivery is at-least-once and unordered: dedupe on type + data.id +
    # data.updatedAt (Platform events also repeat the `webhook-id` header), and use updatedAt
    # rather than arrival order to decide which state is newer.

    # Respond 2xx within 5 seconds; anything else is a failed delivery and is retried.
    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
```

Or install the MoonPay webhooks skill: `npx skills add hookdeck/webhook-skills --skill moonpay-webhooks`

## Common failures

- **The body was parsed first.** The signature covers the raw bytes, and MoonPay warns that a JSON parser changes them. Verify first, then parse.
- **The wrong key for the header.** `Moonpay-Signature-V2` uses your webhook API key from the Developers page. The legacy `Moonpay-Signature` uses the endpoint's signing secret, so mixing them up always fails.
- **Looking for `X-Signature`.** MoonPay's Platform OpenAPI file names this header, while its Platform overview and widget docs say to verify `Moonpay-Signature-V2`. Check which headers a test mode delivery carries.
- **A `GET` request treated as a webhook.** MoonPay also sends signed `GET` requests to partner endpoints. Those sign the query string instead of a body, so a body check fails on them.

From [Hookdeck's MoonPay guide](https://hookdeck.com/webhooks/moonpay/guide-duplicates-ordering-retries-timeouts).

---

Not affiliated with MoonPay. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/moonpay.json) · [Report a correction](https://hookdeck.com/contact)
