Verify Recharge webhooks
Every Recharge webhook includes two signature headers, which let you verify that a request genuinely came from Recharge and wasn't changed in transit. X-Recharge-Webhook-Signature is an HMAC-SHA256 signature over the timestamp and raw body, and it's the one Recharge recommends for new integrations. The legacy X-Recharge-Hmac-Sha256 is a plain SHA-256 hash of your client secret and the body, with no timestamp.
The facts
{t}.{raw body} t from the signature header (equal to X-Recharge-Webhook-Timestamp), a literal dot, then the body bytes exactly as sent. Re-serialised JSON fails.
X-Recharge-Hmac-Sha256 hex(SHA-256(API Client Secret + raw body)), a plain keyed digest, secret first, not an HMAC despite the header name.
Recharge webhook secret
Recharge signs with your API Client Secret, which isn't the same as your API token. Keep it in an environment variable, not in source code.
- In the Dashboard: go to Integrations, then API Tokens, and click your token. The Edit API Token page shows the API Client Secret.
Source: Recharge docs ↗
Code
// Generated with: recharge-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
// Reject deliveries whose signed timestamp is more than 48 hours from now.
const TIMESTAMP_TOLERANCE_SECONDS = 172800;
/**
* Verify a Recharge webhook using the recommended timestamp-bound scheme.
*
* The `X-Recharge-Webhook-Signature` header carries comma-separated key/value
* pairs in the form `t=<epoch>,v1=<hex>`. The signing input is
* `<timestamp>.<payload_json>` (timestamp, literal dot, exact raw body bytes),
* signed with HMAC-SHA-256 keyed by the API Client Secret, hex-encoded.
*
* @param {Buffer} rawBody - Raw request body (Buffer, not parsed JSON)
* @param {string} signatureHeader - X-Recharge-Webhook-Signature header value
* @param {string} clientSecret - Recharge API Client Secret
* @returns {boolean} Whether the signature is valid and within tolerance
*/
function verifyRechargeWebhookTimestamped(rawBody, signatureHeader, clientSecret) {
if (!signatureHeader) return false;
// Parse `t=<epoch>,v1=<hex>` (future schemes may add v2=..., so parse by key).
const parts = {};
for (const pair of signatureHeader.split(',')) {
const [key, value] = pair.split('=');
if (key && value) parts[key.trim()] = value.trim();
}
const timestamp = parseInt(parts.t, 10);
const signature = parts.v1;
if (!Number.isFinite(timestamp) || !signature) return false;
// Reject the delivery if abs(now - t) > 48 hours (replay protection).
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - timestamp) > TIMESTAMP_TOLERANCE_SECONDS) return false;
// HMAC-SHA-256 over "<timestamp>.<raw body>", keyed by the client secret.
const digest = crypto
.createHmac('sha256', clientSecret)
.update(`${timestamp}.`)
.update(rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature));
} catch {
return false; // length mismatch = invalid
}
}
/**
* Verify a Recharge webhook using the legacy body-only scheme.
*
* GOTCHA: despite the `X-Recharge-Hmac-Sha256` header name, this is NOT HMAC.
* It is a plain SHA-256 of (clientSecret + rawBody), with the secret prepended,
* hex-encoded.
*
* @param {Buffer} rawBody - Raw request body (Buffer, not parsed JSON)
* @param {string} signatureHeader - X-Recharge-Hmac-Sha256 header value
* @param {string} clientSecret - Recharge API Client Secret
* @returns {boolean} Whether the signature is valid
*/
function verifyRechargeWebhookLegacy(rawBody, signatureHeader, clientSecret) {
if (!signatureHeader) return false;
const digest = crypto
.createHash('sha256')
.update(clientSecret) // secret first
.update(rawBody) // then the raw body bytes
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(digest),
Buffer.from(signatureHeader)
);
} catch {
return false; // length mismatch = invalid
}
}
// Recharge webhook endpoint - must use the raw body for signature verification
app.post(
'/webhooks/recharge',
express.raw({ type: 'application/json' }),
async (req, res) => {
const timestampedSignature = req.headers['x-recharge-webhook-signature'];
const legacySignature = req.headers['x-recharge-hmac-sha256'];
const clientSecret = process.env.RECHARGE_API_CLIENT_SECRET;
// 1. Verify first. Prefer the recommended timestamp-bound scheme; fall back
// to the legacy body-only header only when the new header is absent.
const verified = timestampedSignature
? verifyRechargeWebhookTimestamped(req.body, timestampedSignature, clientSecret)
: verifyRechargeWebhookLegacy(req.body, legacySignature, clientSecret);
if (!verified) {
console.error('Webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
// 2. Parse only after verification. Recharge wraps the resource by key,
// e.g. { "charge": {...} }, { "subscription": {...} }, { "order": {...} }.
const payload = JSON.parse(req.body.toString('utf8'));
// 3. Dispatch on the payload's top-level resource key. Recharge does NOT
// send a documented topic/action header - if you need to distinguish
// actions (created vs updated vs paid), register a distinct endpoint
// path per topic when creating the webhook subscription.
// (`included_objects` adds extra top-level keys, so match known
// resources rather than taking the only key.)
const resource = ['charge', 'subscription', 'order', 'customer', 'address'].find(
(key) => payload[key] !== undefined
);
console.log(`Received ${resource ?? 'unknown'} webhook`);
// Return 200 fast; do slow work asynchronously.
switch (resource) {
case 'charge':
console.log('Charge event:', payload.charge?.id);
// Your code: grant access, record revenue, dunning, etc.
break;
case 'subscription':
console.log('Subscription event:', payload.subscription?.id);
// Your code: onboarding, provisioning, revoke access, etc.
break;
case 'order':
console.log('Order event:', payload.order?.id);
// Your code: sync to OMS/ERP, trigger fulfillment, etc.
break;
case 'customer':
console.log('Customer event:', payload.customer?.id);
// Your code: CRM sync, payment method updates, etc.
break;
case 'address':
console.log('Address event:', payload.address?.id);
// Your code: update shipping records, etc.
break;
default:
console.log('Unhandled resource:', Object.keys(payload));
}
// Acknowledge receipt within 5 seconds
res.status(200).send('OK');
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = {
app,
verifyRechargeWebhookTimestamped,
verifyRechargeWebhookLegacy,
};
// 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/recharge`);
});
} // Generated with: recharge-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
// Reject deliveries whose signed timestamp is more than 48 hours from now.
const TIMESTAMP_TOLERANCE_SECONDS = 172800;
/**
* Verify a Recharge webhook using the recommended timestamp-bound scheme.
*
* The `X-Recharge-Webhook-Signature` header carries comma-separated key/value
* pairs in the form `t=<epoch>,v1=<hex>`. The signing input is
* `<timestamp>.<payload_json>` (timestamp, literal dot, exact raw body bytes),
* signed with HMAC-SHA-256 keyed by the API Client Secret, hex-encoded.
*/
function verifyRechargeWebhookTimestamped(
rawBody: string,
signatureHeader: string | null,
clientSecret: string
): boolean {
if (!signatureHeader) return false;
// Parse `t=<epoch>,v1=<hex>` (future schemes may add v2=..., so parse by key).
const parts: Record<string, string> = {};
for (const pair of signatureHeader.split(',')) {
const [key, value] = pair.split('=');
if (key && value) parts[key.trim()] = value.trim();
}
const timestamp = parseInt(parts.t, 10);
const signature = parts.v1;
if (!Number.isFinite(timestamp) || !signature) return false;
// Reject the delivery if abs(now - t) > 48 hours (replay protection).
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - timestamp) > TIMESTAMP_TOLERANCE_SECONDS) return false;
// HMAC-SHA-256 over "<timestamp>.<raw body>", keyed by the client secret.
const digest = crypto
.createHmac('sha256', clientSecret)
.update(`${timestamp}.`)
.update(rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature));
} catch {
return false; // length mismatch = invalid
}
}
/**
* Verify a Recharge webhook using the legacy body-only scheme.
*
* GOTCHA: despite the `X-Recharge-Hmac-Sha256` header name, this is NOT HMAC.
* It is a plain SHA-256 of (clientSecret + rawBody), with the secret prepended,
* hex-encoded.
*/
function verifyRechargeWebhookLegacy(
rawBody: string,
signatureHeader: string | null,
clientSecret: string
): boolean {
if (!signatureHeader) return false;
const digest = crypto
.createHash('sha256')
.update(clientSecret) // secret first
.update(rawBody) // then the raw body
.digest('hex');
try {
return crypto.timingSafeEqual(
Buffer.from(digest),
Buffer.from(signatureHeader)
);
} catch {
return false; // length mismatch = invalid
}
}
export async function POST(request: NextRequest) {
// Read the raw body as text - do NOT use request.json() before verifying.
const body = await request.text();
const timestampedSignature = request.headers.get('x-recharge-webhook-signature');
const legacySignature = request.headers.get('x-recharge-hmac-sha256');
const clientSecret = process.env.RECHARGE_API_CLIENT_SECRET!;
// 1. Verify first. Prefer the recommended timestamp-bound scheme; fall back
// to the legacy body-only header only when the new header is absent.
const verified = timestampedSignature
? verifyRechargeWebhookTimestamped(body, timestampedSignature, clientSecret)
: verifyRechargeWebhookLegacy(body, legacySignature, clientSecret);
if (!verified) {
console.error('Webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
// 2. Parse only after verification. Recharge wraps the resource by key,
// e.g. { "charge": {...} }, { "subscription": {...} }, { "order": {...} }.
const payload = JSON.parse(body);
// 3. Dispatch on the payload's top-level resource key. Recharge does NOT
// send a documented topic/action header - if you need to distinguish
// actions (created vs updated vs paid), register a distinct endpoint
// path per topic when creating the webhook subscription.
// (`included_objects` adds extra top-level keys, so match known
// resources rather than taking the only key.)
const resource = ['charge', 'subscription', 'order', 'customer', 'address'].find(
(key) => payload[key] !== undefined
);
console.log(`Received ${resource ?? 'unknown'} webhook`);
// Return 200 fast; do slow work asynchronously.
switch (resource) {
case 'charge':
console.log('Charge event:', payload.charge?.id);
// Your code: grant access, record revenue, dunning, etc.
break;
case 'subscription':
console.log('Subscription event:', payload.subscription?.id);
// Your code: onboarding, provisioning, revoke access, etc.
break;
case 'order':
console.log('Order event:', payload.order?.id);
// Your code: sync to OMS/ERP, trigger fulfillment, etc.
break;
case 'customer':
console.log('Customer event:', payload.customer?.id);
// Your code: CRM sync, payment method updates, etc.
break;
case 'address':
console.log('Address event:', payload.address?.id);
// Your code: update shipping records, etc.
break;
default:
console.log('Unhandled resource:', Object.keys(payload));
}
// Acknowledge receipt within 5 seconds
return NextResponse.json({ received: true });
} # Generated with: recharge-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
import json
import time
import hmac
import hashlib
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException
load_dotenv()
app = FastAPI()
recharge_client_secret = os.environ.get("RECHARGE_API_CLIENT_SECRET")
# Reject deliveries whose signed timestamp is more than 48 hours from now.
TIMESTAMP_TOLERANCE_SECONDS = 172800
def verify_recharge_webhook_timestamped(
raw_body: bytes, signature_header: str, client_secret: str
) -> bool:
"""Verify a Recharge webhook using the recommended timestamp-bound scheme.
The `X-Recharge-Webhook-Signature` header carries comma-separated key/value
pairs in the form `t=<epoch>,v1=<hex>`. The signing input is
`<timestamp>.<payload_json>` (timestamp, literal dot, exact raw body bytes),
signed with HMAC-SHA-256 keyed by the API Client Secret, hex-encoded.
"""
if not signature_header:
return False
# Parse `t=<epoch>,v1=<hex>` (future schemes may add v2=..., so parse by key).
parts = {}
for pair in signature_header.split(","):
key, _, value = pair.partition("=")
if key and value:
parts[key.strip()] = value.strip()
timestamp_str = parts.get("t")
signature = parts.get("v1")
if not timestamp_str or not timestamp_str.isdigit() or not signature:
return False
timestamp = int(timestamp_str)
# Reject the delivery if abs(now - t) > 48 hours (replay protection).
if abs(int(time.time()) - timestamp) > TIMESTAMP_TOLERANCE_SECONDS:
return False
# HMAC-SHA-256 over "<timestamp>.<raw body>", keyed by the client secret.
digest = hmac.new(
client_secret.encode("utf-8"),
f"{timestamp}.".encode("utf-8") + raw_body,
hashlib.sha256,
).hexdigest()
# Constant-time comparison to avoid timing attacks
return hmac.compare_digest(digest, signature)
def verify_recharge_webhook_legacy(
raw_body: bytes, signature_header: str, client_secret: str
) -> bool:
"""Verify a Recharge webhook using the legacy body-only scheme.
GOTCHA: despite the `X-Recharge-Hmac-Sha256` header name, this is NOT HMAC.
It is a plain SHA-256 of (client_secret + raw_body), with the secret prepended,
hex-encoded.
"""
if not signature_header:
return False
digest = hashlib.sha256(
client_secret.encode("utf-8") + raw_body # secret first, then raw body
).hexdigest()
# Constant-time comparison to avoid timing attacks
return hmac.compare_digest(digest, signature_header)
@app.post("/webhooks/recharge")
async def recharge_webhook(request: Request):
# Read the raw body for signature verification - do NOT parse JSON first.
raw_body = await request.body()
timestamped_signature = request.headers.get("x-recharge-webhook-signature")
legacy_signature = request.headers.get("x-recharge-hmac-sha256")
# 1. Verify first. Prefer the recommended timestamp-bound scheme; fall back
# to the legacy body-only header only when the new header is absent.
if timestamped_signature:
verified = verify_recharge_webhook_timestamped(
raw_body, timestamped_signature, recharge_client_secret
)
else:
verified = verify_recharge_webhook_legacy(
raw_body, legacy_signature, recharge_client_secret
)
if not verified:
raise HTTPException(status_code=400, detail="Invalid signature")
# 2. Parse only after verification. Recharge wraps the resource by key,
# e.g. {"charge": {...}}, {"subscription": {...}}, {"order": {...}}.
payload = json.loads(raw_body)
# 3. Dispatch on the payload's top-level resource key. Recharge does NOT
# send a documented topic/action header - if you need to distinguish
# actions (created vs updated vs paid), register a distinct endpoint
# path per topic when creating the webhook subscription.
# (`included_objects` adds extra top-level keys, so match known
# resources rather than taking the only key.)
resource = next(
(
key
for key in ("charge", "subscription", "order", "customer", "address")
if key in payload
),
None,
)
print(f"Received {resource or 'unknown'} webhook")
# Return 200 fast; do slow work asynchronously.
if resource == "charge":
print(f"Charge event: {payload['charge'].get('id')}")
# Your code: grant access, record revenue, dunning, etc.
elif resource == "subscription":
print(f"Subscription event: {payload['subscription'].get('id')}")
# Your code: onboarding, provisioning, revoke access, etc.
elif resource == "order":
print(f"Order event: {payload['order'].get('id')}")
# Your code: sync to OMS/ERP, trigger fulfillment, etc.
elif resource == "customer":
print(f"Customer event: {payload['customer'].get('id')}")
# Your code: CRM sync, payment method updates, etc.
elif resource == "address":
print(f"Address event: {payload['address'].get('id')}")
# Your code: update shipping records, etc.
else:
print(f"Unhandled resource: {list(payload.keys())}")
# Acknowledge receipt within 5 seconds
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 Recharge webhooks skill:
npx skills add hookdeck/webhook-skills --skill recharge-webhooks
Common failures
Verifying the legacy X-Recharge-Hmac-Sha256 as an HMAC
hmac(secret, body) never matches. The value is a plain SHA-256 of the client secret followed by the raw body, hex-encoded.
Body changed before verification
Recharge's docs say validation fails even if one space is lost. Verify the raw bytes before parsing or re-serialising.
Let Event Gateway verify Recharge signatures.
Event Gateway verifies the signature on each Recharge delivery before it reaches your service, then queues it and retries failures on your schedule.