Money and events
Webhooks
Webhooks are signed HTTP requests that HisarPay sends to your server when something happens in your account. Listen for events instead of polling: it is faster and does not use your rate limit.
Adding an endpoint
Add endpoints in the dashboard under Developers → Webhooks, or through the API with a live key. Leave events empty to receive every event. The signing secret (whsec_…) is returned once, in the create response.
curl -X POST https://hisarpay.com/v1/webhook-endpoints \
-H "Authorization: Bearer $HISARPAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://shop.example/webhooks/hisarpay",
"events": [
"invoice.paid",
"invoice.overpaid",
"invoice.partial",
"invoice.expired"
]
}'
curl -X POST https://hisarpay.com/v1/webhook-endpoints/3c9d…/rotate-secret \
-H "Authorization: Bearer $HISARPAY_API_KEY"const endpoint = await hisarpay.webhookEndpoints.create({
url: 'https://shop.example/webhooks/hisarpay',
events: ['invoice.paid', 'invoice.overpaid', 'invoice.partial', 'invoice.expired'],
});
saveSecret(endpoint.secret); // returned only once
const { secret } = await hisarpay.webhookEndpoints.rotateSecret(endpoint.id);$endpoint = $hisarpay->webhookEndpoints->create([
'url' => 'https://shop.example/webhooks/hisarpay',
'events' => ['invoice.paid', 'invoice.overpaid', 'invoice.partial', 'invoice.expired'],
]);
save_secret($endpoint['secret']);
$rotated = $hisarpay->webhookEndpoints->rotateSecret($endpoint['id']);endpoint = client.webhook_endpoints.create({
"url": "https://shop.example/webhooks/hisarpay",
"events": ["invoice.paid", "invoice.overpaid", "invoice.partial", "invoice.expired"],
})
save_secret(endpoint["secret"])
rotated = client.webhook_endpoints.rotate_secret(endpoint["id"])- Endpoints receive both live and test events; check the
livemodefield of the event. - If you pass a
callback_urlon an invoice, that invoice’s events are sent there too. These deliveries are signed with your default endpoint’s secret; without any endpoint they are not sent. - For safety, events only go to public addresses:
localhost, private networks and link-local addresses are refused. Use HTTPS.
Event types
| Event | When |
|---|---|
invoice.paid | An invoice was paid in full or within tolerance. |
invoice.overpaid | An invoice was paid more than due. |
invoice.partial | Part of an invoice was paid; the rest is due. |
invoice.expired | An invoice expired before it was paid. |
invoice.cancelled | An invoice was cancelled. |
invoice.payment_received | A payment that does not count towards the invoice arrived (other coin or cancelled invoice); it was credited. |
withdrawal.completed | A withdrawal was confirmed on chain. |
withdrawal.failed | A withdrawal could not be sent; it was refunded. |
withdrawal.rejected | A withdrawal was rejected in review. |
test.ping | Sent by the “Send test” button in the dashboard. |
Request and payload
Every event is a POST with a JSON body. The body always uses the same envelope: id, type, livemode, created_at and a data object that depends on the event.
POST /webhooks/hisarpay HTTP/1.1
Content-Type: application/json
User-Agent: HisarPay-Webhook/1.0
X-HisarPay-Event-Id: 5f0c6c1e-8a51-4c7e-9d0e-2b1f4f6a9c11
X-HisarPay-Signature: t=1792746760,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd{
"id": "5f0c6c1e-8a51-4c7e-9d0e-2b1f4f6a9c11",
"type": "invoice.paid",
"livemode": true,
"created_at": "2026-10-23T09:12:40.000Z",
"data": {
"invoice": {
"id": "0b6a3f52-3c1d-4a7e-8f4b-1d2c3e4f5a6b",
"object": "invoice",
"livemode": true,
"type": "choice",
"status": "paid",
"token": "USDT",
"amount": "26",
"paid_amount": "26",
"remaining_amount": "0",
"overpaid_amount": "0",
"underpaid_amount": "0",
"price_amount": "25.00",
"price_currency": "USD",
"rate_usd": "1",
"allowed_tokens": ["TRX", "USDT"],
"network_fee": "1",
"fee_paid_by_customer": false,
"commission_added": "0",
"order_id": "order_1001",
"description": "Order #1001",
"metadata": { "cart": "42" },
"address": "TQ5pRkV4n1hYp7Dn3fRzXw2Lc8uJmKb9eA",
"payment_url": "https://hisarpay.com/pay/0b6a3f52-3c1d-4a7e-8f4b-1d2c3e4f5a6b",
"success_url": "https://shop.example/thanks",
"return_url": null,
"callback_url": null,
"payment_link_id": null,
"customer_email": null,
"payer": null,
"expires_at": "2026-10-23T10:00:00.000Z",
"paid_at": "2026-10-23T09:12:39.000Z",
"created_at": "2026-10-23T09:00:00.000Z"
},
"payment": {
"txid": "9b7c1d2e…c3d4e",
"from": "TW8x…2nQe",
"amount": "26",
"token": "USDT",
"late": false,
"repriced": null,
"simulated": false
}
}
}Invoice events carry data.invoice and data.payment, and withdrawal events data.withdrawal. data.invoice is the same object GET /v1/invoices/{id} returns, without the payments list (the payment that triggered the event is data.payment).
Verifying signatures
The X-HisarPay-Signature header looks like t=<unix time>,v1=<signature>. The signature is the hex HMAC-SHA256 of t + "." + raw body, keyed with the endpoint’s secret. To verify:
- Read the body raw. If you parse the JSON and serialise it again, the bytes change and the signature no longer matches.
- Reject the request if
tis more than 5 minutes away from the current time. - Compute the expected signature and compare it, in constant time, with any of the
v1values in the header.
The SDKs do all of this in one call:
import express from 'express';
import { HisarPay, SignatureVerificationError } from '@hisarpay/node';
const app = express();
const secret = process.env.HISARPAY_WEBHOOK_SECRET!; // whsec_…
const LIVE = process.env.HISARPAY_API_KEY!.startsWith('hp_live_');
// express.raw keeps the exact bytes; register it before any express.json()
app.post('/webhooks/hisarpay', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = HisarPay.webhooks.constructEvent(req.body, req.headers['x-hisarpay-signature'], secret);
} catch (err) {
if (err instanceof SignatureVerificationError) return res.status(400).send(err.message);
throw err;
}
// test events arrive here too, and anyone can mark a test invoice as paid
if (event.livemode !== LIVE) return res.sendStatus(200);
if (event.type === 'invoice.paid' || event.type === 'invoice.overpaid') {
// fulfil the order once; record the event id
await fulfillOrder(event.data.invoice.order_id, event.id);
}
res.sendStatus(200);
});<?php
use HisarPay\Exception\SignatureVerificationException;
use HisarPay\Webhook;
$payload = file_get_contents('php://input'); // raw bytes
$header = $_SERVER['HTTP_X_HISARPAY_SIGNATURE'] ?? null;
try {
$event = Webhook::constructEvent($payload, $header, getenv('HISARPAY_WEBHOOK_SECRET'));
} catch (SignatureVerificationException $e) {
http_response_code(400);
exit;
}
// test events arrive here too, and anyone can mark a test invoice as paid
$live = str_starts_with((string) getenv('HISARPAY_API_KEY'), 'hp_live_');
if ($event['livemode'] === $live && in_array($event['type'], ['invoice.paid', 'invoice.overpaid'], true)) {
// fulfil the order once; record the event id
fulfill_order($event['data']['invoice']['order_id'], $event['id']);
}
http_response_code(200);import os
from flask import Flask, abort, request
from hisarpay import SignatureVerificationError, webhooks
app = Flask(__name__)
SECRET = os.environ["HISARPAY_WEBHOOK_SECRET"]
LIVE = os.environ["HISARPAY_API_KEY"].startswith("hp_live_")
@app.post("/webhooks/hisarpay")
def hisarpay_webhook():
try:
event = webhooks.construct_event(
request.get_data(), # raw bytes, not request.json
request.headers.get("X-HisarPay-Signature"),
SECRET,
)
except SignatureVerificationError:
abort(400)
# test events arrive here too, and anyone can mark a test invoice as paid
if event["livemode"] is LIVE and event["type"] in ("invoice.paid", "invoice.overpaid"):
# fulfil the order once; record the event id
fulfill_order(event["data"]["invoice"]["order_id"], event["id"])
return "", 200Without an SDK, the same check takes a few lines:
import { createHmac, timingSafeEqual } from 'node:crypto';
export function verifyHisarPay(rawBody: string, header: string, secret: string, tolerance = 300) {
const parts = header.split(',').map((p) => p.trim().split('='));
const t = Number(parts.find(([k]) => k === 't')?.[1]);
if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > tolerance) return false;
const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest();
return parts
.filter(([k]) => k === 'v1')
.some(([, v]) => {
const got = Buffer.from(v ?? '', 'hex');
return got.length === expected.length && timingSafeEqual(got, expected);
});
}<?php
function verify_hisarpay(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
$t = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
if ($k === 't') $t = (int) $v;
if ($k === 'v1') $signatures[] = $v;
}
if ($t === null || abs(time() - $t) > $tolerance) return false;
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
foreach ($signatures as $sig) {
if (hash_equals($expected, strtolower($sig))) return true;
}
return false;
}import hashlib, hmac, time
def verify_hisarpay(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
items = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
ts = next((v for k, v in items if k == "t"), None)
if ts is None or not ts.isdigit() or abs(time.time() - int(ts)) > tolerance:
return False
signed = ts.encode() + b"." + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, v.lower()) for k, v in items if k == "v1")Responding and duplicates
- Return a
2xxwithin 10 seconds. Queue heavy work and answer right away. Redirects (3xx) are not followed and count as failures. - The same event can arrive more than once. Store
X-HisarPay-Event-Id(theidin the body) and skip events you have already handled. - Ordering is not guaranteed. Decide based on the
statusin the event, or read the current state withGET /v1/invoices/{id}to be sure.
Retry schedule
Any response other than 2xx, a timeout or a connection error counts as a failure, and the event is sent again on this schedule:
| Attempt | After the previous one |
|---|---|
| 1 | Immediately |
| 2 | 30 s |
| 3 | 2 min |
| 4 | 10 min |
| 5 | 30 min |
| 6 | 1 h |
| 7 | 3 h |
| 8 | 6 h |
| 9 | 12 h |
| 10 | 24 h |
The ten attempts span about two days. If the last one fails too, the delivery is marked failed. Once you have fixed the problem, resend the event from the dashboard or the API; it goes to every matching endpoint again:
curl -X POST https://hisarpay.com/v1/events/5f0c6c1e-8a51-4c7e-9d0e-2b1f4f6a9c11/resend \
-H "Authorization: Bearer $HISARPAY_API_KEY"await hisarpay.events.resend('5f0c6c1e-8a51-4c7e-9d0e-2b1f4f6a9c11');$hisarpay->events->resend('5f0c6c1e-8a51-4c7e-9d0e-2b1f4f6a9c11');client.events.resend("5f0c6c1e-8a51-4c7e-9d0e-2b1f4f6a9c11")Rotating the secret
POST /v1/webhook-endpoints/{id}/rotate-secret creates a new secret. The old one stays valid for 24 hours, and during that time every delivery carries two signatures:
X-HisarPay-Signature: t=1792746760,v1=<new secret signature>,v1=<old secret signature>Verification passes when any v1 matches, so you can switch to the new secret whenever you like within those 24 hours, without downtime.
Testing
The Send test button next to an endpoint in the dashboard sends one test.ping event to it; it is never retried. For end-to-end scenarios use payment simulation; simulated payments produce real webhooks.