Integration
Client SDK Integration
Create a checkout session on your server, then send the customer to PaymentHooks hosted checkout with a redirect, embed it on your allowed origins, or share a payment link.
Installation
Node.js package (server-side)
# npmnpm install @paymenthooks/sdk# yarnyarn add @paymenthooks/sdk# pnpmpnpm add @paymenthooks/sdk
import { PaymentHooks } from '@paymenthooks/sdk'; // 3.0.0 or later
// Secret key (phk_live_...). Server only.
const ph = new PaymentHooks({ apiKey: process.env.PAYMENTHOOKS_SECRET_KEY });
// Methods resolve to the response's data; failures throw a PaymentHooksError subclass.
const session = await ph.checkoutSessions.create(
{
lineItems: [{ description: 'Pro plan', quantity: 1, unitPrice: 2000 }], // 2000 = USD 20.00
itemLocalCurrency: 'USD',
successUrl: 'https://yoursite.com/success',
cancelUrl: 'https://yoursite.com/cart',
},
{ idempotencyKey: 'order_1042' },
);
// session.id, session.url
// Redirect the customer to session.url, or pass session.id to the browser script.
// Lists resolve to { data, meta: { total, page, pageSize } }.
const { data: payments, meta } = await ph.payments.list({ status: 'success', pageSize: 25 });The examples on this page require @paymenthooks/sdk 3.0.0 or later (npm package page). Earlier versions do not match the current API: 3.0.0 uses the REST money field names (e.g. itemLocalCurrency). Version 3 calls https://paymenthooks.com/api/v1 by default (override with baseUrl) and needs Node.js 18 or later.
Browser script
<script src="https://paymenthooks.com/sdk/paymenthooks.js"></script>
<script>
PaymentHooks.init({ publishableKey: "phk_pub_..." });
</script>Load paymenthooks.js from paymenthooks.com. It exposes a global PaymentHooks object and needs no build step. With a bundler, import the same init and checkout functions from @paymenthooks/sdk/browser (3.0.0 or later).
Choose your integration
| Method | Effort | UX | Best for |
|---|---|---|---|
| Redirect | Low | Leaves your site for hosted checkout | Any checkout built on checkout sessions |
| Payment link | Lowest | Standalone hosted page | Fixed-price links, no server code |
Redirect Checkout
Send the customer to the PaymentHooks-hosted checkout page. After a successful payment they are returned to your successUrl with session_id and payment_id query parameters. You can also redirect to the session's url directly from your server without the script.
PaymentHooks.init({ publishableKey: "phk_pub_..." });
// Same window
PaymentHooks.checkout({ sessionId: "SESSION_ID" });
// Or open hosted checkout in a popup window
PaymentHooks.checkout({ sessionId: "SESSION_ID", newWindow: true });Iframe Embed
Show hosted checkout inside your own page. Card entry still happens on PaymentHooks, inside the frame. Embedding is off by default: checkout pages are served with X-Frame-Options: DENY and frame-ancestors 'none', so browsers refuse to frame them.
- In the dashboard open Developers > Embedded Checkout and add each origin that will embed checkout, exactly as the browser reports it: scheme, host and optional port, for example
https://shop.example.com. Up to 20 origins; wildcards and paths are rejected. The same list is available atGET/PUT /api/v1/merchant/embed-settings(account:read/account:writescopes). - Create the session on your server, then call
renderCheckout(script) orrenderInline(@paymenthooks/sdk/browser). They load/checkout/:sessionId?embed=iframe(or?embed=inline).
For requests carrying ?embed= from an allowed merchant, PaymentHooks drops X-Frame-Options and sends Content-Security-Policy: frame-ancestors listing only your allowed origins. Without ?embed, or with no origins configured, framing stays denied. Origins must use https; http://localhost is accepted only in non-production environments for local development.
<script src="https://paymenthooks.com/sdk/paymenthooks.js"></script>
<div id="checkout-container"></div>
<script>
PaymentHooks.init({ publishableKey: "phk_pub_..." });
// Loads https://paymenthooks.com/checkout/SESSION_ID?embed=iframe in an iframe.
PaymentHooks.renderCheckout({
sessionId: "SESSION_ID",
container: "#checkout-container",
onReady: function () { /* checkout rendered */ },
onSuccess: function (e) { /* e.paymentId, e.status -- confirm on your server */ },
onError: function (e) { /* e.code, e.message */ },
onCancel: function (e) { /* e.sessionId -- the customer cancelled */ },
});
</script>import { init, renderInline } from "@paymenthooks/sdk/browser";
init({ publishableKey: "phk_pub_..." });
const unsubscribe = renderInline({
sessionId: "SESSION_ID",
container: "#checkout-container",
onReady: () => {},
onSuccess: ({ paymentId }) => {},
onError: ({ code, message }) => {}, // PAYMENT_FAILED | EXPIRED | NOT_FOUND
onCancel: ({ sessionId }) => {},
});
// Call unsubscribe() when the container is removed.The frame posts { source: "paymenthooks-checkout", type } messages with type one of ready, resize (height), payment.success (paymentId, status), payment.error (code, message) and payment.cancel. Messages are sent only to your page's origin, and only when that origin is allowed; the SDK accepts them only from the PaymentHooks origin and its own frame, and resizes the frame for you.
Direct DOM Render
The browser script's PaymentHooks.renderInline is not supported for production integrations: it collects raw card details on your page and does not report success reliably. Use the redirect integration or the iframe embed above, which keep card entry on PaymentHooks pages. (In @paymenthooks/sdk/browser, renderInline is the iframe embed described above.)
Payment Link Embed
Every payment link has a hosted page at https://paymenthooks.com/pay/:slug. Link or redirect to it; no checkout session or script is required. The script's paymentLink helper embeds it in an iframe (/pay/:slug?embed=true); like the iframe embed above, it renders only on origins allowed under Developers > Embedded Checkout.
<a href="https://paymenthooks.com/pay/pro-plan-monthly">Pay now</a>SDK API reference
Supported methods of the browser script:
PaymentHooks.init({ publishableKey, baseUrl? })
Store your configuration; call it first. Only phk_pub_ publishable keys are accepted: a phk_live_ secret key or any other value throws. baseUrl defaults to https://paymenthooks.com in @paymenthooks/sdk/browser, and to the origin the script was loaded from in the hosted paymenthooks.js. Set it to your custom checkout domain if you use one, since events are accepted only from that origin.
PaymentHooks.checkout({ sessionId, newWindow? })
Navigate to hosted checkout at /checkout/:sessionId, or open it in a popup window when newWindow is true. Throws if the browser blocks the popup.
PaymentHooks.renderCheckout({ sessionId, container, onReady?, onSuccess?, onError?, onCancel? })
Embed hosted checkout in an iframe (/checkout/:sessionId?embed=iframe). Requires the page origin to be allowed under Developers > Embedded Checkout; for any other origin the browser refuses the frame and no callback fires. onError codes: PAYMENT_FAILED, EXPIRED, NOT_FOUND. onCancel receives { sessionId }. Returns the iframe; call iframe.paymentHooksUnsubscribe() when you remove it.
PaymentHooks.paymentLink({ slug, container, onReady?, onSuccess?, onError?, onCancel? })
Embed a payment link (/pay/:slug?embed=true) in an iframe. It sends the same events as renderCheckout and has the same allowed-origin requirement. Returns the iframe.
PaymentHooks.renderInline({ sessionId, container, onReady?, onSuccess?, onError?, onCancel? })
npm package: embed hosted checkout in inline mode (/checkout/:sessionId?embed=inline) with the same callbacks. Returns the unsubscribe function. (The hosted paymenthooks.js renderInline instead draws a form in the page.)
PaymentHooks.reset()
npm package: clear the stored configuration, for tests or logout.
Node.js SDK 2.0 resources: payments (create, retrieve, list, update, status, refund, capture), refunds.list, customers (create, retrieve, list, update, with addresses and taxIds), subscriptions (create, retrieve, list, update, cancel, pause, resume, retry, previewProration, listInvoices, listPayments), subscriptionSchedules (create, list, retrieve, advance, cancel, release), disputes (list, retrieve, update, submitEvidence), events (list, retrieve), billingPortal (createToken, listTokens, revokeToken), embedSettings (retrieve, update), invoices (create, retrieve, list, update, send, markPaid), products and prices (create, retrieve, list, update, del), checkoutSessions (create, retrieve, list), paymentLinks (create, retrieve, list, update), routingRules (create, list, update, del), webhookEndpoints (create, list, update, rotateSecret), and webhookLogs (list, resend, replay). payments.create requires customerId; customers.create requires name and email. Fields are camelCase, as in the REST API. Errors throw AuthenticationError (401), PermissionError (403, e.g. INSUFFICIENT_SCOPE), NotFoundError, ConflictError (409), GoneError (410), UnprocessableError (422), InvalidRequestError, RateLimitError, ApiError, or ApiConnectionError, each with code, fields and err.is(code). For other languages, call the REST API directly as shown in Server SDKs.
Security
Publishable keys only in the browser
phk_pub_ keys are the only keys that may appear in client code. Never expose a phk_live_ secret key.
Card data isolation
With redirect checkout, embedded checkout and payment links, card details are entered on PaymentHooks pages, never on yours.
Exact embed origins
Only origins you list can frame checkout. Remove an origin and pages on it stop loading checkout on the next request.
PCI scope
Keeping card entry on hosted pages keeps card data off your servers, which reduces your PCI DSS scope.