Webhooks
Receive automatic notifications when payments are completed
Overview
Webhooks notify your application when a payment reaches completed status. HexPay sends a signed POST request to the webhookUrl you set when creating the payment.
No webhooks are sent for other statuses (pending, expired, cancelled). Use the API to track them.
Create Payment with Webhook
Learn how to include webhookUrl when creating payments
Webhook Request Structure
Headers
Content-Type: application/jsonX-Signature: <base64_signature>- Ed25519 signature of the raw request body, standard base64 with paddingX-Signature-Kid: <key_id>- ID of the key used for signing
Body
{
"payload": {
"paymentId": "019327c6-2058-7901-b234-56789abcdeff",
"status": "completed",
"orderId": "order-2026-00123",
"metadata": {"customer_id": "cust_abc123", "plan": "premium"}
},
"signAt": "2026-01-20T10:12:00Z"
}| Field | Description |
|---|---|
payload.paymentId | Payment ID |
payload.status | Always completed |
payload.orderId | orderId from the create request, or null |
payload.metadata | metadata from the create request, or null |
signAt | Signing time (UTC). Set anew on every delivery attempt |
Signature Verification
Security Critical: Always verify the signature before processing webhook data. This protects against forged requests and attacks.
Step 1: Get JWKS
GET https://api.hexpay.io/v1/webhook/keysFor the demo environment use https://api.demo.hexpay.io/v1/webhook/keys.
The JWK field x (public key) is base64url without padding, as required by RFC 8037. The X-Signature header is standard base64 with padding. Decode each with the matching alphabet.
Step 2: Verify Signature
const crypto = require('crypto');
// rawBody must be the exact bytes received (Buffer), not re-serialized JSON.
function verifySignature(rawBody, signature, kid, jwks) {
// Find key by kid
const key = jwks.keys.find(k => k.kid === kid);
if (!key) throw new Error('Unknown key');
// Import the Ed25519 public key directly from the JWK (Node.js >= 16)
const publicKey = crypto.createPublicKey({
key: { kty: key.kty, crv: key.crv, x: key.x },
format: 'jwk'
});
// X-Signature is standard base64
const signatureBytes = Buffer.from(signature, 'base64');
return crypto.verify(null, rawBody, publicKey, signatureBytes);
}import base64
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
def b64url_decode(value: str) -> bytes:
# JWK "x" is base64url without padding: restore padding before decoding
return base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
def verify_signature(raw_body: bytes, signature: str, kid: str, jwks: dict) -> bool:
# Find key by kid
key = next((k for k in jwks['keys'] if k['kid'] == kid), None)
if not key:
raise ValueError('Unknown key')
verify_key = VerifyKey(b64url_decode(key['x']))
# X-Signature is standard base64
signature_bytes = base64.b64decode(signature, validate=True)
try:
verify_key.verify(raw_body, signature_bytes)
return True
except BadSignatureError:
return Falseimport (
"crypto/ed25519"
"encoding/base64"
"errors"
"fmt"
)
type JWK struct {
Kty string `json:"kty"`
Crv string `json:"crv"`
Kid string `json:"kid"`
X string `json:"x"`
}
type JWKS struct {
Keys []JWK `json:"keys"`
}
func verifySignature(rawBody []byte, signature, kid string, jwks *JWKS) error {
// Find key by kid
var key *JWK
for i := range jwks.Keys {
if jwks.Keys[i].Kid == kid {
key = &jwks.Keys[i]
break
}
}
if key == nil {
return errors.New("unknown key")
}
// JWK "x" is base64url without padding
publicKeyBytes, err := base64.RawURLEncoding.DecodeString(key.X)
if err != nil {
return fmt.Errorf("decode public key: %w", err)
}
if len(publicKeyBytes) != ed25519.PublicKeySize {
return errors.New("invalid public key size")
}
// X-Signature is standard base64
signatureBytes, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return fmt.Errorf("decode signature: %w", err)
}
if !ed25519.Verify(ed25519.PublicKey(publicKeyBytes), rawBody, signatureBytes) {
return errors.New("invalid signature")
}
return nil
}JWKS Management & Key Rotation
Cache JWKS Locally
- Cache the JWKS response with TTL of 6-12 hours
- Only fetch on cache miss or unknown kid
- Never fetch on every webhook
Handle Unknown Keys
When you encounter an unknown kid:
- Fetch fresh JWKS from the endpoint
- Update your local cache
- Retry verification with new keys
- If still not found → reject the webhook
Key Rotation Flow
Security Best Practices
Essential Security Checks
- Signature: Always verify using the exact raw body and kid
- Timestamp: Reject webhooks with
signAtolder than 30 seconds - HTTPS Only: Use HTTPS for webhook URLs and JWKS fetching
- No Fallbacks: Never use a different key if the specified kid is not found
Replay Attack Protection
// Check timestamp (example)
const signedAt = new Date(webhookBody.signAt).getTime();
const messageAge = (Date.now() - signedAt) / 1000;
if (messageAge > 30 || messageAge < -5) {
throw new Error('Message too old or from future');
}Idempotency
- Store processed
paymentIdvalues - Skip reprocessing of duplicate webhooks
- Essential for handling retries
Handling Failures
When JWKS is Unavailable
- Queue the webhook for later processing
- Implement exponential backoff for retries
- Return HTTP 500 to trigger HexPay retry
Response Requirements
- Success: Return any
2xxstatus (200,201,202,204, …) only after successful verification and processing - Failure: Any other status, a network error or a timeout triggers a retry
- Timeout: Respond within 30 seconds
Delivery and Retries
Automatic Retries
HexPay retries a failed webhook about every 10 seconds for up to 6 hours after the payment is completed, then stops. Ensure your endpoint handles duplicate deliveries gracefully.
If your endpoint was unavailable longer than that, use GET /v1/payments with status=completed to reconcile.
Quick Implementation Checklist
- Verify signature with correct kid
- Check timestamp (max 30 seconds old)
- Cache JWKS with proper TTL
- Handle unknown kids with JWKS refresh
- Implement idempotency
- Use HTTPS exclusively
- Return 2xx only on success
- Handle duplicates gracefully
Monitor Payment Status
Use the payment ID to track payment details via API