Integration
Integrate from any backend
Use the Node.js SDK, or call the REST API from any language. The examples create a customer, charge them, list payments, issue a refund and verify webhook signatures.
Install
For Node.js, use the @paymenthooks/sdk package below. The quickstart examples further down use plain HTTP, so they work in any language; there is no Python or Go package. For WHMCS there is a gateway module.
Node.js SDK
@paymenthooks/sdk wraps the REST API with typed methods. It needs Node.js 18 or later and has no runtime dependencies. Install the latest 4.x (currently 5.3.0): 4.2 types subscription checkouts (recurring lines, billing cycles, startsAt), usage billing and catalog keys; 3.0.0 introduced the camelCase money fields of the REST API (itemLocalCurrency, itemLocalCurrencyAmount, transactionAmountUsdCents), so 2.x and 1.x do not match the current API. It ships ESM and CommonJS builds and bundled TypeScript types; every request and response type is exported. Release notes: API changelog.
npm install @paymenthooks/sdk@^4import { PaymentHooks, ConflictError } from "@paymenthooks/sdk";
const ph = new PaymentHooks({
apiKey: process.env.PAYMENTHOOKS_SECRET_KEY!, // phk_live_...
// baseUrl: "https://paymenthooks.com/api/v1", timeout: 30000, fetch (defaults)
});
// Hosted checkout: create the session on your server, redirect to session.url
const session = await ph.checkoutSessions.create(
{
lineItems: [{ description: "Pro plan", quantity: 1, unitPrice: 2000 }],
itemLocalCurrency: "USD",
successUrl: "https://example.com/success",
cancelUrl: "https://example.com/cancel",
},
{ idempotencyKey: "order-1001" },
);
// Customers: 409 DUPLICATE_EMAIL throws ConflictError
try {
await ph.customers.create({ name: "Jane Doe", email: "[email protected]" });
} catch (err) {
if (err instanceof ConflictError && err.is("DUPLICATE_EMAIL")) {
// look the customer up instead
} else throw err;
}
// Lists resolve to { data, meta: { total, page, pageSize } }
const { data: payments } = await ph.payments.list({ status: "success", pageSize: 50 });
// Refund: transactionAmountUsdCents is required (USD cents);
// the gateway is refunded pro rata in the payment's transactionLocalCurrency
await ph.payments.refund(payments[0].id, { transactionAmountUsdCents: 500 }, { idempotencyKey: "refund-1001" });import express from "express";
import { verifyWebhookSignature, SIGNATURE_HEADER, WebhookVerificationError } from "@paymenthooks/sdk";
app.post("/webhooks/paymenthooks", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = await verifyWebhookSignature({
payload: req.body, // raw bytes (string or Uint8Array), never re-serialised
signature: req.header(SIGNATURE_HEADER) ?? "",
secret: process.env.PAYMENTHOOKS_WEBHOOK_SECRET!, // whsec_... of this endpoint
// toleranceSeconds: 300 (default)
});
} catch (err) {
if (err instanceof WebhookVerificationError) return res.status(400).send(err.code);
throw err;
}
if (event.type === "checkout.session.completed") {
// fulfil the order; de-duplicate on event.id
}
res.sendStatus(200);
});- Resources:
payments,refunds,customers(withaddressesandtaxIds),subscriptions,subscriptionSchedules,invoices,products,prices,checkoutSessions,paymentLinks,disputes,events,billingPortal,embedSettings,routingRules,webhookEndpoints,webhookLogs. - Every failure throws a
PaymentHooksErrorsubclass withstatus,codeandfields:AuthenticationError(401),PermissionError(403),NotFoundError(404),ConflictError(409),GoneError(410),UnprocessableError(422),InvalidRequestError(other 4xx),RateLimitError(429,retryAfter),ApiError(5xx),ApiConnectionError(network,TIMEOUT) andWebhookVerificationError. Check a code witherr.is("DUPLICATE_EMAIL"). The SDK never retries on its own. verifyWebhookSignatureresolves to the parsed event and throwsWebhookVerificationError(MISSING_SIGNATURE,INVALID_SIGNATURE_FORMAT,TIMESTAMP_OUT_OF_TOLERANCE,SIGNATURE_MISMATCH, ...) on any problem; it never returns false. It acceptsv1_previousduring a secret rotation.- The browser helpers (redirect, iframe and inline checkout) are in
@paymenthooks/sdk/browser; see Client SDK. - The full reference (every method, return value and error code) is in the package README on npm.
- To receive webhooks on your machine while developing, use the PaymentHooks CLI.
Authentication
All server requests use your secret key (prefix phk_live_), sent as Authorization: Bearer phk_live_... or in the x-api-key header (values that do not start with phk_ are ignored). The same key is used whether your account is in test or live mode, and it can only call endpoints covered by its scopes (otherwise 403 INSUFFICIENT_SCOPE). Every response is a { data, error } envelope.
curl -X POST "https://paymenthooks.com/api/v1/payments" \
-H "Authorization: Bearer phk_live_replace_with_your_secret_key" \
-H "Content-Type: application/json" \
-d '{ "customerId": "ph_cus_8f14e45fceea167a5a36dedd4bea2543", "transactionLocalCurrencyAmount": 9500, "transactionLocalCurrency": "USD", "paymentMethod": "card", "idempotencyKey": "order-12345" }'Quickstart
Each example creates a customer, charges them, lists recent payments, and refunds the payment with POST /payments/:id/refund, which requires an integer transactionAmountUsdCents (USD cents); the gateway is refunded pro rata in the payment's transactionLocalCurrency.
// ─── PaymentHooks Node.js server example ──────────────────────────────────────
// Plain HTTP with the built-in fetch API (Node 18+), so every call maps
// one-to-one to the API reference. Base URL: https://paymenthooks.com/api/v1
const PAYMENTHOOKS_API_BASE = "https://paymenthooks.com/api/v1";
// Secret key (phk_live_...). Keep it on the server; never ship it to a browser or app.
const PAYMENTHOOKS_SECRET_KEY = process.env.PAYMENTHOOKS_SECRET_KEY || "phk_live_replace_with_your_secret_key";
async function paymenthooksRequest(path, options = {}) {
const headers = {
"Authorization": `Bearer ${PAYMENTHOOKS_SECRET_KEY}`,
"Content-Type": "application/json",
};
// Refund, capture, checkout session, subscription and webhook endpoint
// creation honour the Idempotency-Key header.
if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
const res = await fetch(`${PAYMENTHOOKS_API_BASE}${path}`, {
method: options.method || "GET",
headers,
body: options.body ? JSON.stringify(options.body) : undefined,
});
const json = await res.json();
// Every response is { data, error }; error is { code, message, fields?, details? }
if (!res.ok || json.error) {
throw new Error(`PaymentHooks API error [${res.status}] ${json.error?.code}: ${json.error?.message}`);
}
return json.data;
}
async function main() {
// 1) Create a customer (name and email are required)
const customer = await paymenthooksRequest("/customers", {
method: "POST",
body: { name: "Jane Doe", email: "[email protected]", country: "US" },
});
console.log("Customer created:", customer.id);
// 2) Create a payment. POST /payments takes its idempotency key in the
// request body (idempotencyKey), not in a header.
const payment = await paymenthooksRequest("/payments", {
method: "POST",
body: {
customerId: customer.id, // required
transactionLocalCurrencyAmount: 9500, // smallest currency unit: 9500 = USD 95.00
transactionLocalCurrency: "USD",
paymentMethod: "card",
description: "Order #12345",
idempotencyKey: "order-12345",
},
});
// status: success | pending | action_required | failed | refunded | disputed | dispute_lost | requires_capture
console.log("Payment created:", payment.id, "status:", payment.status);
// 3) List recent payments
const recent = await paymenthooksRequest("/payments?pageSize=5");
console.log(`Found ${recent.length} recent payments`);
// 4) Refund it. Only payments with status "success" or "disputed" can be refunded.
if (payment.status === "success") {
const refund = await paymenthooksRequest(`/payments/${payment.id}/refund`, {
method: "POST",
idempotencyKey: `refund-${payment.id}`,
body: { transactionAmountUsdCents: 9500, reason: "requested_by_customer" }, // required, USD cents
});
console.log("Refund issued:", refund.id, "status:", refund.status);
}
}
main().catch((err) => {
console.error("Failed:", err.message);
process.exit(1);
});
// ─── Webhook signature verification ──────────────────────────────────────────
// Header: X-PaymentHooks-Signature: t=<unix seconds>,v1=<hex>[,v1_previous=<hex>]
// v1 = HMAC-SHA256(key = your whsec_... secret, message = t + "." + raw body bytes)
const crypto = require("crypto");
const WEBHOOK_TOLERANCE_SECONDS = 300;
function verifyWebhookSignature(rawBody, signatureHeader, webhookSecret) {
if (!signatureHeader || !webhookSecret) return false;
let timestamp;
const signatures = [];
for (const item of String(signatureHeader).split(",")) {
const i = item.indexOf("=");
if (i <= 0) continue;
const key = item.slice(0, i).trim();
const value = item.slice(i + 1).trim();
if (key === "t") timestamp = Number(value);
if (key === "v1" || key === "v1_previous") signatures.push(value);
}
if (!Number.isInteger(timestamp)) return false;
if (Math.abs(Date.now() / 1000 - timestamp) > WEBHOOK_TOLERANCE_SECONDS) return false;
const expected = crypto
.createHmac("sha256", webhookSecret)
.update(timestamp + ".")
.update(rawBody) // Buffer or string of the EXACT bytes received
.digest();
return signatures.some((sig) => {
const given = Buffer.from(sig, "hex");
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}
// Express example — express.raw keeps the body as the original bytes:
// app.post("/webhooks/paymenthooks", express.raw({ type: "application/json" }), (req, res) => {
// const sig = req.get("X-PaymentHooks-Signature");
// if (!verifyWebhookSignature(req.body, sig, process.env.PAYMENTHOOKS_WEBHOOK_SECRET)) {
// return res.status(400).end();
// }
// const event = JSON.parse(req.body.toString("utf-8"));
// // De-duplicate on event.id (delivery is at-least-once), then handle event.type
// res.status(200).end();
// });
Webhook signature verification
Every webhook payload is signed with HMAC-SHA256 using the signing secret of the endpoint it is delivered to. Verify the X-PaymentHooks-Signature header against the raw request body before acting on the event. The quickstart snippets above include ready-to-use verifier functions for each language.