Skip to content

Receive webhooks

View as Markdown

Overview

TapPay sends a webhook to your server when something happens, such as a successful payment. The webhook is small: it carries only the event id, its type and the objectId. You verify its signature, then read the object from the API.

Before you begin

Your key needs the webhooks:manage scope and you use your secret key, shown below as sk_test_YOUR_SECRET_KEY. You also need a public HTTPS address on your server that accepts POST requests. Webhooks are real in the sandbox, so you can test with a sandbox key. If you use a ready-made plugin instead of code, see the no-code plugins.

Steps

Create the endpoint

Register the URL of your webhook endpoint and the events it should receive. The response contains the webhook secret, which starts with whsec_. It is shown only once, so store it safely on your server. The enabledEvents list is an allowlist: use an exact type such as payment.succeeded, a group such as payment.*, or * for every event. See Events for all types. You can register many endpoints, and each has its own events and its own secret.

curl -sS -X POST "https://api.tappay.mn/api/v1/webhook-endpoints" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com/webhooks/node-'"$(openssl rand -hex 8)"'","enabledEvents":["payment.succeeded","invoice.paid"],"description":"Docs example endpoint"}'
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const webhookEndpoint = await tappay.webhookEndpoints.create({
  body: {
    url: `https://example.com/webhooks/node-${crypto.randomUUID()}`,
    enabledEvents: ['payment.succeeded', 'invoice.paid'],
    description: 'Docs example endpoint',
  },
});
console.log(JSON.stringify(webhookEndpoint));
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$webhookEndpoint = $tappay->webhookEndpoints->create([
    'body' => [
        'url' => 'https://example.com/webhooks/node-' . vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)) . '',
        'enabledEvents' => ['payment.succeeded', 'invoice.paid'],
        'description' => 'Docs example endpoint',
    ],
]);
echo json_encode($webhookEndpoint);
import json
import uuid
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
webhook_endpoint = client.webhook_endpoints.create({
    "body": {
        "url": "https://example.com/webhooks/node-" + str(uuid.uuid4()) + "",
        "enabledEvents": ["payment.succeeded", "invoice.paid"],
        "description": "Docs example endpoint",
    },
})
print(json.dumps(webhook_endpoint))

Verify the signature

Every webhook has the headers TapPay-Timestamp, TapPay-Nonce and TapPay-Signature. Build the string POST, the path with the query, the timestamp, the nonce and the SHA-256 hex of the raw body, each on its own line. Sign it with HMAC-SHA256 using the secret and compare v1= plus the base64 result with the header, in constant time. During a secret rotation the header holds two signatures separated by a comma, and either may match. Reject a timestamp that is more than 300 seconds from now.

Verify the raw request body. Compute the signature over the exact bytes you received. If your framework parses JSON first and you serialise it again, the hash changes and every valid webhook fails. Each program below defines a verify function you can call from your handler with the raw body. A small block at the end reads the test input from standard input and prints valid or invalid.

# Standard tools only: sed/grep read the input, openssl signs (it takes the secret as an argument, so use it for a demo, not on a shared host).
verify_webhook() { # raw_body timestamp nonce signatures secret path
  local body_hash canonical expected now sig result=invalid
  body_hash=$(printf '%s' "$1" | openssl dgst -sha256 -hex | awk '{print $NF}')
  canonical=$(printf 'POST\n%s\n%s\n%s\n%s' "$6" "$2" "$3" "$body_hash")
  expected="v1=$(printf '%s' "$canonical" | openssl dgst -sha256 -hmac "$5" -binary | openssl base64 -A)"
  now=$(date +%s)
  if [ $(( now > $2 ? now - $2 : $2 - now )) -le 300 ]; then
    for sig in $(printf '%s' "$4" | tr ',' ' '); do
      [ "$sig" = "$expected" ] && result=valid
    done
  fi
  echo "$result"
}

input=$(cat)
pick() { printf '%s' "$input" | sed -E "s/.*\"$1\":\"(([^\"\\\\]|\\\\.)*)\".*/\1/"; }
raw_body=$(pick rawBody | sed -e 's/\\"/"/g' -e 's/\\\\/\\/g')
verify_webhook "$raw_body" "$(pick TapPay-Timestamp)" "$(pick TapPay-Nonce)" "$(pick TapPay-Signature)" "$TAPPAY_WEBHOOK_SECRET" "$(pick path)"
import { readFileSync } from 'node:fs';
import { TapPay, SignatureVerificationError } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
// rawBody must be the exact bytes you received, before any JSON parsing.
const { rawBody, headers, path } = JSON.parse(readFileSync(0, 'utf8'));
try {
  // During a rotation pass both secrets: the new one and the previous one.
  const secrets = [process.env.TAPPAY_WEBHOOK_SECRET, process.env.TAPPAY_WEBHOOK_SECRET_PREVIOUS].filter(Boolean);
  const event = tappay.webhooks.constructEvent(rawBody, headers, { secrets, path });
  console.log(event.id ? 'valid' : 'invalid');
} catch (e) {
  if (!(e instanceof SignatureVerificationError)) throw e;
  console.log('invalid');
}
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;
use TapPay\Exception\SignatureVerificationError;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
// rawBody must be the exact bytes you received (file_get_contents('php://input')), before any JSON decoding.
$in = json_decode(file_get_contents('php://stdin'), true);
try {
    // During a rotation pass both secrets: the new one and the previous one.
    $secrets = array_values(array_filter([getenv('TAPPAY_WEBHOOK_SECRET'), getenv('TAPPAY_WEBHOOK_SECRET_PREVIOUS')]));
    $event = $tappay->webhooks->constructEvent($in['rawBody'], $in['headers'], ['secrets' => $secrets, 'path' => $in['path']]);
    echo $event->id ? 'valid' : 'invalid';
} catch (SignatureVerificationError $e) {
    echo 'invalid';
}
import json
import os
import sys
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
# raw_body must be the exact bytes you received, before any JSON parsing.
data = json.load(sys.stdin)
# During a rotation pass both secrets: the new one and the previous one.
secrets = [s for s in (os.environ.get("TAPPAY_WEBHOOK_SECRET"), os.environ.get("TAPPAY_WEBHOOK_SECRET_PREVIOUS")) if s]
try:
    event = client.webhooks.construct_event(data["rawBody"], data["headers"], secrets=secrets, path=data["path"])
    print("valid" if event.id else "invalid")
except tappay.SignatureVerificationError:
    print("invalid")

Rotate the secret

Replace the webhook secret of an endpoint without downtime. TapPay returns the new secret once. For overlapHours hours, from 0 to 72, both secrets sign each webhook, as in the step above. Put the new secret on your server in that time.

curl -sS -X POST "https://api.tappay.mn/api/v1/webhook-endpoints/ENDPOINT_ID/rotate-secret" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Idempotency-Key: $(openssl rand -hex 16)" \
  -H "Content-Type: application/json" \
  -d '{"overlapHours":1}'
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const webhookEndpoint = await tappay.webhookEndpoints.rotateSecret({ id: 'ENDPOINT_ID', body: { overlapHours: 1 } });
console.log(JSON.stringify(webhookEndpoint));
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$webhookEndpoint = $tappay->webhookEndpoints->rotateSecret(['id' => 'ENDPOINT_ID', 'body' => ['overlapHours' => 1]]);
echo json_encode($webhookEndpoint);
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
webhook_endpoint = client.webhook_endpoints.rotate_secret({"id": "ENDPOINT_ID", "body": {"overlapHours": 1}})
print(json.dumps(webhook_endpoint))

Change the events

Change the allowlist of an endpoint with a PATCH request. The new enabledEvents list replaces the old one. The same call can change the url and the description, or set status to DISABLED to pause deliveries.

curl -sS -X PATCH "https://api.tappay.mn/api/v1/webhook-endpoints/ENDPOINT_ID" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27" \
  -H "Content-Type: application/json" \
  -d '{"enabledEvents":["payment.*","invoice.*"]}'
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const webhookEndpoint = await tappay.webhookEndpoints.update({ id: 'ENDPOINT_ID', body: { enabledEvents: ['payment.*', 'invoice.*'] } });
console.log(JSON.stringify(webhookEndpoint));
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$webhookEndpoint = $tappay->webhookEndpoints->update(['id' => 'ENDPOINT_ID', 'body' => ['enabledEvents' => ['payment.*', 'invoice.*']]]);
echo json_encode($webhookEndpoint);
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
webhook_endpoint = client.webhook_endpoints.update({"id": "ENDPOINT_ID", "body": {"enabledEvents": ["payment.*", "invoice.*"]}})
print(json.dumps(webhook_endpoint))

List your endpoints

Every endpoint has its own events, apiVersion and secret. This lets you send payment events to one server and refund events to another. List all your endpoints to check them. The secret is not returned again.

curl -sS "https://api.tappay.mn/api/v1/webhook-endpoints" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const webhookEndpoint = await tappay.webhookEndpoints.list();
console.log(JSON.stringify(webhookEndpoint));
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$webhookEndpoint = $tappay->webhookEndpoints->list();
echo json_encode($webhookEndpoint);
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
webhook_endpoint = client.webhook_endpoints.list()
print(json.dumps(webhook_endpoint))

List your events

Every event is stored, so you can read what you may have missed, for example while your server was down. Filter by type or objectId, and continue with cursor while hasMore is true.

curl -sS "https://api.tappay.mn/api/v1/events?limit=10" \
  -H "Authorization: Bearer sk_test_YOUR_SECRET_KEY" \
  -H "TapPay-Version: 2026-09-27"
import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: 'sk_test_YOUR_SECRET_KEY' });
const page = await tappay.events.list({ query: { limit: '10' } }).firstPage();
console.log(JSON.stringify(page));
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => 'sk_test_YOUR_SECRET_KEY']);
$page = $tappay->events->list(['query' => ['limit' => '10']])->firstPage();
echo json_encode(['data' => $page->data, 'hasMore' => $page->hasMore, 'nextCursor' => $page->nextCursor]);
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
page = client.events.list({"limit": "10"}).first_page()
print(json.dumps({"data": page.data, "has_more": page.has_more, "next_cursor": page.next_cursor}))

Verify

Make a sandbox payment as in the checkout guide and watch your endpoint receive payment.succeeded. Check the delivery in Retrieve an event. If your server was failing, fix it and use Resend an event to deliver the event again. Webhook events include invoice.paid, invoice.partially_paid, invoice.expired, payment.processing, payment.succeeded, payment.failed, payment.overpaid and payment.finalized. The full list of event types is in Events.

A webhook carries only { id, type, objectId }. With an SDK, constructEvent checks the signature over the raw body and returns the event, and events.retrieveObject reads the object with GET, for example payments.retrieve for a payment.* event. During a secret rotation pass both secrets, the new one and the previous one. The SDK pages show every option.

import express from 'express';
import { TapPay, SignatureVerificationError } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
const app = express();

// express.raw keeps the body as bytes. A parsed JSON body fails with RAW_BODY_REQUIRED.
app.post('/webhooks/tappay', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = tappay.webhooks.constructEvent(req.body, req.headers, {
      // During a rotation both secrets are valid: the new one and the previous one.
      secrets: [process.env.TAPPAY_WEBHOOK_SECRET, process.env.TAPPAY_WEBHOOK_SECRET_PREVIOUS].filter(Boolean),
      path: req.originalUrl,
    });
  } catch (err) {
    if (err instanceof SignatureVerificationError) return void res.sendStatus(400);
    throw err;
  }
  // The event is thin: read the object itself with GET before you act on it.
  const object = await tappay.events.retrieveObject(event);
  console.log(event.type, object.status);
  res.sendStatus(200);
});
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;
use TapPay\Exception\SignatureVerificationError;

$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
try {
    // php://input is the raw body. A json_decode result fails with RAW_BODY_REQUIRED.
    $event = $tappay->webhooks->constructEvent(file_get_contents('php://input'), getallheaders(), [
        // During a rotation both secrets are valid: the new one and the previous one.
        'secrets' => array_values(array_filter([getenv('TAPPAY_WEBHOOK_SECRET'), getenv('TAPPAY_WEBHOOK_SECRET_PREVIOUS')])),
        'path' => $_SERVER['REQUEST_URI'],
    ]);
} catch (SignatureVerificationError $e) {
    http_response_code(400);
    exit;
}
// The event is thin: read the object itself with GET before you act on it.
$object = $tappay->events->retrieveObject($event);
http_response_code(200);
import os
import tappay
from flask import Flask, request

client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
app = Flask(__name__)


@app.post("/webhooks/tappay")
def webhook():
    try:
        # request.get_data() is the raw body. A json.loads result fails with RAW_BODY_REQUIRED.
        event = client.webhooks.construct_event(
            request.get_data(),
            request.headers,
            # During a rotation both secrets are valid: the new one and the previous one.
            secrets=[s for s in (os.environ.get("TAPPAY_WEBHOOK_SECRET"), os.environ.get("TAPPAY_WEBHOOK_SECRET_PREVIOUS")) if s],
            path=request.full_path.rstrip("?"),
        )
    except tappay.SignatureVerificationError:
        return "", 400
    # The event is thin: read the object itself with GET before you act on it.
    obj = client.events.retrieve_object(event)
    print(event.type, obj["status"])
    return "", 200

To check every delivery, go through your events with the list iterator of an SDK. It fetches the next pages for you:

import { TapPay } from '@tappay-mn/node';

const tappay = new TapPay({ apiKey: process.env.TAPPAY_SECRET_KEY });
// The iterator fetches the next page when it needs it.
for await (const event of tappay.events.list({ query: { limit: 50 } })) {
  console.log(event.id, event.type, event.deliveryStatus);
}
<?php
require 'vendor/autoload.php';

use TapPay\TapPay;

$tappay = new TapPay(['apiKey' => getenv('TAPPAY_SECRET_KEY')]);
// The iterator fetches the next page when it needs it.
foreach ($tappay->events->list(['query' => ['limit' => 50]])->autoPaging() as $event) {
    echo $event['id'], ' ', $event['type'], ' ', $event['deliveryStatus'], PHP_EOL;
}
import os
import tappay

client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
# The iterator fetches the next page when it needs it.
for event in client.events.list({"limit": 50}).auto_paging_iter():
    print(event["id"], event["type"], event["deliveryStatus"])

Common mistakes

  • Parsing the JSON before you verify. Compute the signature over the raw body exactly as it arrived, not over a re-serialized copy.
  • Comparing signatures with a plain equality check. Use a constant-time comparison.
  • Trusting the webhook body as the full object. It is thin, so read the object again with a GET request.
  • Listing too few events. An endpoint receives only the types in its enabledEvents, so add payment.* or * if you wait for a type that is missing.
  • Keeping the old secret after a rotation. Put the new secret on every server before the overlap ends, or valid webhooks fail.
  • Handling an event twice. Events can be delivered more than once, so remember the event id and skip repeats.

Next steps

Change the events or the URL with Update a webhook endpoint. Replace a secret without downtime with Rotate a webhook secret. To receive payment notices without writing code, use a plugin.