Webhooks

Paymentsnp tells your server when a payment is verified, fails, is refunded or expires, and when an invoice changes. Every delivery is signed with your endpoint's secret, and failed deliveries are retried with backoff.

  • HMAC-SHA256 signatures
  • Up to 8 delivery attempts
  • Replay any delivery
Two headers on every delivery
Paymentnp-Signature: t=1791100000,v1=5f2c…
Paymentnp-Event-Id: 8f4f7c0e-2b1d-4a7e-9c55-…

# v1 = hex HMAC-SHA256(whsec_ secret, "<t>.<raw body>")

# Check a captured delivery locally
paymentsnp webhooks verify --secret whsec_... \
  --header 't=...,v1=...' --file body.json
The header names keep the original Paymentnp spelling.

Add an endpoint

Add endpoints under Dashboard > Webhooks, separately for Test and Live. Each endpoint has a whsec_ signing secret, shown once when you create it. Events are delivered only to endpoints in the environment where they happened.

Endpoint rules
SchemeHTTPS only
Port443 or 8443
AddressPublic addresses only. Private, loopback and Paymentsnp's own addresses are refused.
ChecksThe address is checked against these rules when you save it and again on every delivery, and the connection is pinned to the checked IP.

Headers and payload

Each event is a JSON POST with two headers:

  • Paymentnp-Signature: t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of "<t>.<raw body>" using your whsec_ secret.
  • Paymentnp-Event-Id, the same value as the id in the body.

The header names keep the original Paymentnp spelling on purpose, so existing integrations keep working.

payment.succeeded
POST /webhooks/paymentsnp HTTP/1.1
Content-Type: application/json
Paymentnp-Signature: t=1791100000,v1=5f2c…
Paymentnp-Event-Id: 8f4f7c0e-2b1d-4a7e-9c55-0d3e1f6a9b21

{
  "id": "8f4f7c0e-2b1d-4a7e-9c55-0d3e1f6a9b21",
  "type": "payment.succeeded",
  "api_version": "v1",
  "environment": "test",
  "created_at": "2026-10-01T06:45:05.000Z",
  "data": {
    "payment_id": "5b2d6c1e-…",
    "checkout_session_id": "c1a94d07-…",
    "order_id": "order-1001",
    "provider": "esewa",
    "provider_transaction_id": "000AB12",
    "amount_minor": 150000,
    "currency": "NPR",
    "is_simulated": false,
    "overpaid": false
  }
}

Every event has the envelope { id, type, api_version, environment, created_at, data }. is_simulated is true for Sandbox payments, and overpaid is true when an order that was already paid receives a second payment.

Verify the signature

  1. Read raw bodyThe exact bytes received, before JSON parsing
  2. Split the headerTake t and v1 from Paymentnp-Signature
  3. RecomputeHMAC-SHA256 of t + "." + body with whsec_
  4. CompareConstant-time, and reject t older than 5 minutes

Verify against the raw request body. Parsing the JSON and serialising it again changes the bytes and breaks the signature. Reply with any 2xx status once the event is stored.

With the standard library

import crypto from "node:crypto";
import express from "express";

const app = express();
const raw = express.raw({ type: "application/json" }); // verify raw bytes

app.post("/webhooks/paymentsnp", raw, (req, res) => {
  const header = req.get("Paymentnp-Signature") || "";
  const sig = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = crypto
    .createHmac("sha256", process.env.PAYMENTSNP_WEBHOOK_SECRET)
    .update(sig.t + "." + req.body)
    .digest();
  const given = Buffer.from(sig.v1 || "", "hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(sig.t)) <= 300;
  const valid =
    given.length === expected.length && crypto.timingSafeEqual(given, expected);
  if (!fresh || !valid) return res.sendStatus(400);

  const event = JSON.parse(req.body);
  if (event.type === "payment.succeeded") {
    // Skip if you already processed event.id, check event.data.order_id
    // and event.data.amount_minor, then fulfil the order once.
  }
  res.sendStatus(200);
});
<?php
$body = file_get_contents('php://input');
$sig = [];
foreach (explode(',', $_SERVER['HTTP_PAYMENTNP_SIGNATURE'] ?? '') as $part) {
  [$k, $v] = array_pad(explode('=', $part, 2), 2, '');
  $sig[$k] = $v;
}
$t = $sig['t'] ?? '';
$expected = hash_hmac('sha256', $t . '.' . $body, getenv('PAYMENTSNP_WEBHOOK_SECRET'));
if (!ctype_digit($t) || abs(time() - (int) $t) > 300
    || !hash_equals($expected, $sig['v1'] ?? '')) {
  http_response_code(400);
  exit;
}

$event = json_decode($body, true);
if ($event['type'] === 'payment.succeeded') {
  // Skip if you already processed $event['id'], check order_id
  // and amount_minor in $event['data'], then fulfil the order once.
}
http_response_code(200);
import hashlib
import hmac
import json
import os
import time

def verify(raw_body: bytes, header: str) -> dict:
    sig = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t = sig.get("t", "")
    secret = os.environ["PAYMENTSNP_WEBHOOK_SECRET"].encode()
    expected = hmac.new(secret, t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    if not t.isdigit() or abs(time.time() - int(t)) > 300:
        raise ValueError("stale timestamp")
    if not hmac.compare_digest(expected, sig.get("v1", "")):
        raise ValueError("bad signature")
    return json.loads(raw_body)

# event = verify(request.get_data(), request.headers["Paymentnp-Signature"])
# if event["type"] == "payment.succeeded": fulfil once per event["id"]
Reject a stale timestamp and compare in constant time.

With an SDK

Each SDK has a constructEvent helper (construct_event in Python) that verifies the signature in constant time, rejects old timestamps and returns the parsed event. It throws SignatureVerificationError when the check fails. The TypeScript helper also accepts a header with more than one v1= value.

import { Paymentsnp } from "@paymentsnp/sdk";

const event = await Paymentsnp.webhooks.constructEvent(
  rawBody,                                    // string or Uint8Array: the exact bytes received
  request.headers.get("paymentnp-signature"),
  process.env.PAYMENTSNP_WEBHOOK_SECRET!,
  { toleranceSeconds: 300 },                  // default
);
switch (event.type) {
  case "payment.succeeded": event.data.order_id; event.data.amount_minor; break;
  case "payment.failed":    event.data.attempt_id; event.data.reason; break;
  case "checkout.expired":  event.data.checkout_session_id; break;
}
<?php
$event = \Paymentsnp\Webhook::constructEvent(
    file_get_contents('php://input'),            // raw body
    $_SERVER['HTTP_PAYMENTNP_SIGNATURE'] ?? '',
    getenv('PAYMENTSNP_WEBHOOK_SECRET'),
    300                                           // tolerance in seconds (default)
);
from paymentsnp import Webhook, SignatureVerificationError

event = Webhook.construct_event(
    raw_body,                                 # bytes or str, exactly as received
    request.headers.get("Paymentnp-Signature"),
    os.environ["PAYMENTSNP_WEBHOOK_SECRET"],
    tolerance=300,                            # seconds (default)
)
From the SDK READMEs. The TypeScript helper is async because it uses Web Crypto.

To test your handler, the SDKs build a valid header with generateTestHeader (generate_test_header in Python), and the CLI signs a file with paymentsnp webhooks sign. See the CLI.

Handle each event once

Deliveries are retried, so the same event can reach you more than once. Store the event ID (from the body or Paymentnp-Event-Id) and skip any ID you have already handled. Before you fulfil on payment.succeeded, check that order_id and amount_minor match your order.

Delivery and retries

Timeout10 seconds per attempt
SuccessAny 2xx response
RedirectsNot followed. A redirect counts as a failure.
RetriesExponential backoff, with the gap capped at 1 hour
Give upMarked failed after 8 attempts

A failed delivery stays in the history, where you can replay it once your endpoint is fixed.

Event types

Events delivered to your endpoints
EventWhen it is sentData includes
payment.succeededThe provider confirmed the exact amount. Fulfil the order on this event.payment_id, checkout_session_id, order_id, provider, provider_transaction_id, amount_minor, currency, is_simulated, overpaid
payment.failedA payment attempt failed. The customer can try again on the same checkout.attempt_id, reason
payment.manually_confirmedA team member recorded a Fonepay payment from its panel reference. Not verified by the provider.provider_reference, verification: "manual"
payment.refundedA refund made in the provider panel was recorded. Paymentsnp moved no money.refundable_minor
checkout.expiredA session ended unpaid.checkout_session_id
invoice.finalizedA draft invoice was numbered and opened.invoice_id, invoice_number, total_minor, due_date
invoice.paidAn invoice was paid through hosted checkout and verified by the provider.verification: "provider"
invoice.marked_paidAn invoice was marked paid outside Paymentsnp, or by a manually confirmed Fonepay payment.verification: "manual"
invoice.voidedAn invoice, or a draft, was voided.invoice_id, status

The dashboard's test button sends a webhook.test event, signed like the rest. Invoice events are sent for merchant invoices only, never for automatic checkout receipts.

Delivery history, replay and tests

  • History: each endpoint lists its deliveries and their attempts.
  • Replay: send any past delivery again, for example after fixing your endpoint.
  • Enable or disable: pause an endpoint without deleting it.
  • Test send: deliver a signed webhook.test event on demand.

Owners and administrators manage endpoints. Developers can view deliveries and send test events.

What counts as proof of payment

Return URLs are never proof of payment. Paymentsnp marks a payment succeeded only on authoritative provider evidence: a status lookup or a verified signature with the exact amount. There are no inbound provider IPN endpoints; verification runs from the return and from background re-checks for eSewa and Khalti.

On your side, fulfil on a verified payment.succeeded webhook or on a session whose status is paid when you read it through the API.