@payshen/sdk
v0.10.1
Published
TypeScript SDK for Payshen payment orchestration: route card, wallet and bank payments across Stripe, Adyen and 20+ PSPs with failover, webhooks and refunds.
Maintainers
Readme
@payshen/sdk: TypeScript SDK for Payshen payment orchestration
Route every payment to the provider most likely to approve it, fail over safely, and keep one API across Stripe, Adyen and 20+ payment providers.
@payshen/sdk is the official server-side client for the Payshen API. Payshen is a payment orchestration platform: your payments run on your own provider accounts, under your own contracts, and Payshen decides which connection takes each one, tries another when that is safe, and tells you why. Payshen never holds or moves your money: providers settle to you directly.
Why Payshen
- One integration, many providers. Card, wallet and bank payments through Stripe, Adyen, Checkout.com, Nuvei, Mollie and the rest of the provider directory, with the same calls, statuses and webhooks for all of them.
- Higher approval, explained. Rules, scoring and safe failover pick the connection for each payment, and every answer carries the routing trace: who was eligible, who was excluded and why.
- Money you can reconcile. Captures, voids and refunds are confirmed by the provider before they count; fees come in as
fee_amount(charged) andexpected_fee(your pricing rules), so a wrong fee is visible.
Install
npm i @payshen/sdk
# or
pnpm add @payshen/sdk
yarn add @payshen/sdk
bun add @payshen/sdkZero dependencies, ESM + CommonJS + type declarations, Node 18+ and every runtime with fetch and WebCrypto.
Quickstart (5 minutes)
Get a test key (ps_test_…) under Developers → API keys in the Payshen dashboard. Test keys never reach a live provider account.
1. Create a payment and send the customer to the hosted page
import { Payshen } from "@payshen/sdk";
const client = new Payshen(process.env.PAYSHEN_API_KEY!); // ps_test_ = sandbox, ps_live_ = production
const created = await client.payments.create({
amount: 12000, // minor units: EUR 120.00
currency: "EUR",
country: "DE",
method: "card",
reference: "order-1042",
return_url: "https://shop.example/order/1042/done",
});
if (created.next_action?.type === "REDIRECT") {
// Send the customer to created.next_action.url: the provider's own page takes the card.
}2. Learn the outcome from a signed webhook
import { claimWebhookEvent, memoryWebhookEventStore } from "@payshen/sdk";
const store = memoryWebhookEventStore(); // development only; use your database in production (see "The store")
export async function POST(req: Request) {
const raw = await req.text(); // verify against the raw body
const event = await claimWebhookEvent({
secret: process.env.PAYSHEN_WEBHOOK_SECRET!,
header: req.headers.get("x-payshen-signature"),
body: raw,
store,
});
if (event?.type === "payment.authorized") {
// reserve the order; capture when you ship
}
return new Response(null, { status: 204 });
}3. Capture, refund, and read the fees
await client.payments.capture(created.id, { amount: 12000 });
await client.payments.refund(created.id, { amount: 2000 }); // partial refund
const payment = await client.payments.get(created.id);
payment.fee_amount; // what the provider charged; 0 until it reports
payment.expected_fee; // what your pricing rules say it should costThat is the whole loop. The sections below cover embedded checkout, idempotency, pagination, errors and every webhook rule.
Features
- Payments: create (hosted redirect or embedded), get, list with cursors, async iteration, timeline events
- Capture (full or partial), void, refund (full or partial), with provider-confirmed pending states
- Idempotency on every POST, generated when you don't pass one, so retries never double-charge
- Automatic retries for transient failures only, with timeouts and
AbortSignalcancellation - Webhook verification (timing-safe HMAC, replay window) and at-most-once handling via
claimWebhookEvent - Typed webhook catalogue (
WEBHOOK_EVENT_TYPES) and typed errors (PayshenErrorwithcode,status,requestId) - Routing trace and exclusion reasons on every payment (
debug: true) - Partner API for white-label platforms (
client.merchants)
Runtime support
| Runtime | Supported |
| --- | --- |
| Node.js 18, 20, 22, 24 | Yes |
| Bun, Deno | Yes |
| Vercel Edge, Cloudflare Workers | Yes |
| Browsers | No: this client needs your secret key. Use @payshen/checkout in the browser. |
Links
- SDK guide
- API reference and the OpenAPI 3.1 contract
- Developer changelog and CHANGELOG.md
@payshen/checkout: the browser package for embedded checkout- Support: [email protected]
Security. Your
ps_live_/ps_test_key is a secret: keep it on your server. Never ship it to a browser or a mobile app; in the browser, use@payshen/checkoutwith the payment's short-livedclient_secret.
Built and maintained by Sodasoft LLC.
The full reference
The full REST contract is published as OpenAPI 3.1 at
/api/v1/openapi.json - no
account needed, so you can import it into Postman or generate a client before
you sign up. This SDK covers that contract in full, apart from two kinds of
endpoint it leaves out on purpose:
- the provider-facing inbound webhooks, which your payment providers call rather than you;
- the embedded checkout's
confirmandcomplete, which are browser calls authenticated by the sessionclient_secret. This client authenticates with your secret API key, which must never be needed to finish a customer's payment. Those two are in@payshen/checkout.
Zero-dependency client for the Payshen routing & orchestration API.
Runs on Node 18+, Bun, Deno, Vercel Edge, Cloudflare Workers - anywhere
fetch and WebCrypto exist.
import { Payshen } from "@payshen/sdk";
const client = new Payshen("ps_test_…"); // ps_test_ = sandbox, ps_live_ = production
const created = await client.payments.create({
amount: 12000, // minor units (€120.00)
currency: "EUR",
country: "DE",
method: "card",
reference: "order-1042",
});
console.log(created.status, created.next_action?.type); // e.g. "CAPTURED", "NONE"
if (created.simulated) {
// A simulation decided it (sandbox): no money moved. Never ship against it.
}created.payment_id is the id every other call takes (the same as id).
Hosted flow (recommended) - keep card data off your stack entirely
Pass a return_url and Payshen answers with next_action.REDIRECT: you
send the customer to a hosted page, the provider handles the sensitive part,
and the outcome comes back on your return_url and your webhook. No card
data ever touches you - or Payshen.
// 1) Your server - create the payment
const created = await client.payments.create({
amount: 12000, currency: "EUR", country: "DE", method: "card",
reference: "order-1042",
return_url: "https://merchant.example/order/confirmed",
});
// 2) Send the customer along
if (created.next_action?.type === "REDIRECT") {
redirect(created.next_action.url!); // sandbox: a Payshen-hosted simulator page
}
// 3) Reconcile after the webhook (or on the return_url)
const payment = await client.payments.get(created.id);
console.log(payment.status); // "CAPTURED" | "DECLINED" | "CANCELLED" | ...Statuses are the unified UPPERCASE set: CREATED, PENDING, REQUIRES_ACTION,
AUTHORIZED, CAPTURED, DECLINED, FAILED, UNKNOWN, CANCELLED, REFUNDED,
PARTIALLY_REFUNDED, CHARGEBACK, SETTLED. Declines always carry both the
normalized decline_category and the raw provider code.
UNKNOWN (since 0.4.0) means the provider may have executed the operation and
the platform could not tell - a timeout after the request was sent, or a
connection lost mid-answer. It appears after a capture or a void whose
provider call did not answer, and (since 2026-09-15) on the synchronous branch
of a create whose charge got no usable answer, with a payment.unknown
webhook; no other provider is tried after a timeout or an unknown result.
Payshen asks the provider about it every 30 minutes and moves it to the status
the provider states; what the provider cannot answer goes to Payshen
operations, who settle it from the provider's own record. Treat it as in
flight, exactly like PENDING: show "processing", wait for the webhook or poll
payments.get, and never render it as a decline, repeat the capture or void,
or start a second payment for the same order.
simulated: true on a payment means a simulation decided it (the sandbox
acquirer simulator or the hosted sandbox page): no provider was asked and no
money moved. Never fulfil an order against it. A live (ps_live_) payment is
never answered by a simulation: a connection only a simulation could answer is
excluded from routing (LIVE_PROVIDER_UNAVAILABLE), and when nothing else can
take the payment it is refused 409 routing_failed.
Embedded checkout - your page, the provider's card fields
Create with ui: "embedded" (and a return_url) on your server, and hand
collector and client_secret to @payshen/checkout
in the browser. It mounts the routed provider's own fields, confirms, and when
the card issuer asks for 3-D Secure it runs the challenge and asks Payshen for
the outcome. That payment is REQUIRES_ACTION until the customer finishes,
not DECLINED.
const session = await client.payments.create({
amount: 5000, currency: "EUR", country: "DE", method: "card",
ui: "embedded", return_url: "https://merchant.example/checkout/return",
});
// return { id: session.id, client_secret: session.client_secret,
// status: session.status, collector: session.collector } to the browserYour server learns the outcome from the payment.* webhook, or
payments.get. It never confirms the payment itself.
Capture, void, refund
await client.payments.capture(id, { amount: 12000 }); // partial or full
await client.payments.void(id); // before capture
await client.payments.refund(id, {}); // omit amount = full refundAll three accept { idempotencyKey } - reuse the same key to retry safely. A
live key requires one; the client always sends one (yours, or a generated one
reused across its own retries). They answer a PaymentOperationResult: the
status and money figures after the operation (captured_amount,
refunded_amount, refund_pending_amount, ...). Read the whole payment with
payments.get.
When the provider only accepted it. Some providers (Adyen, for one)
answer "received" and confirm a moment later. A capture or void then answers
with the payment PENDING; it becomes CAPTURED or CANCELLED when the
provider confirms, and you get payment.captured or payment.voided. A
refund throws PayshenError with code: "refund_pending" (409): it is
accepted, not refunded yet, and must not be sent again under a new key. The
same idempotencyKey answers the final result once the provider confirms, and
you get payment.refunded or payment.refund_failed.
Two refusals where nothing was sent and nothing changed:
409 simulated_payment (a live payment a simulation answered, which no
provider holds) and 503 provider_unavailable (the payment's provider cannot
be reached from this deployment; a new attempt is safe once the connection is
fixed).
Packaging and versioning
npm i @payshen/sdkZero dependencies. Ships ESM, CommonJS and type declarations, and needs only a
global fetch, so it runs on Node 18+, Bun, Deno and edge runtimes without a
bundler plugin.
import { Payshen } from "@payshen/sdk";Versioning: the REST API is frozen at v1 and this package follows semver
against it. While the SDK is on 0.x a minor version may still change the
client's own shape; the HTTP contract underneath it will not.
Configuration
new Payshen(apiKey, {
baseUrl: "https://www.payshen.com", // default
timeoutMs: 20_000, // per attempt; default 20s
maxRetries: 3, // transient failures only
fetch: customFetch, // optional dependency injection
});Payments - safe retries
import { randomUUID } from "node:crypto";
const payment = await client.payments.create(
{ amount: 12000, currency: "EUR", country: "DE", method: "card" },
{ idempotencyKey: randomUUID() }, // re-sent on retries → no double routing
);payment.routing (on a create's outcome) carries the decision trace: path,
mode, the matched rule (null when none matched and the default order was
used: priority over every eligible connection, oldest first), every
candidate's predicted approval, cost and latency, and the actual attempt order
including failover. Send debug: true to also get routing.excluded: every
connection removed before routing, with a RoutingExclusionCode such as
CURRENCY_NOT_SUPPORTED or ENVIRONMENT_MISMATCH. When nothing could take the
payment, the 409 routing_failed error carries the same list on
err.excluded.
Payments - pagination, detail, events
// First page (50 newest), scoped to the key's environment.
const first = await client.payments.list({ limit: 50 });
// Walk older history with the cursor.
let cursor = first.nextCursor;
while (cursor) {
const page = await client.payments.list({ limit: 100, before: cursor });
await handle(page.data);
cursor = page.nextCursor;
}
// Or stream every payment as an async iterator.
for await (const p of client.payments.iter({ status: "CAPTURED" })) {
await handle(p);
}
// Timeline for one payment, and the org-wide event feed (filterable by type).
const events = await client.payments.events("9b2e6c2a-…");
const feed = await client.events.list({ limit: 100, type: "payment.captured" });Each page has nextCursor (null on the last page) and hasMore.
Webhooks - verify the signature
Payshen signs every webhook delivery with a Stripe-style header:
X-Payshen-Signature: t=<unix>,v1=<hmac>. Always verify before trusting
the body.
import { claimWebhookEvent } from "@payshen/sdk";
export async function POST(req: Request) {
const raw = await req.text(); // verify against the *raw* body, not a parsed object
const event = await claimWebhookEvent({
secret: process.env.PAYSHEN_WEBHOOK_SECRET!,
header: req.headers.get("x-payshen-signature"),
body: raw,
store, // yours - see below
});
if (!event) return new Response(null, { status: 204 }); // already handled
await fulfil(event);
return new Response(null, { status: 204 });
}event.type is one of WEBHOOK_EVENT_TYPES (payment.authorized,
payment.captured, payment.refunded, dispute.opened, ... and
webhook.test, which you get only from Send test event in the dashboard). New
types may be added within v1, so give your switch a default branch. Each
type and its fields: https://www.payshen.com/developers/reference#webhook-events.
Delivery: at least once, not in order
- At least once. An event your endpoint does not take (a timeout, or any
answer other than 2xx, 400, 410 or 422) is sent again, under the same
id, with growing gaps for about 28 hours before it is given up. The same event arriving twice is normal. - Your dedupe window must be longer than that. Keep processed event ids for more than 28 hours (a few days is safe); a store that forgets sooner lets a late retry of an old event through as new.
- No ordering guarantee. A retried
payment.authorizedcan arrive afterpayment.captured. Decide by the event'screatedtime and the status it carries, or read the payment, never by arrival order. - 410, 400 and 422 are final.
410says you do not want that event;400and422say it cannot be processed. They are not retried.
The store
store is one method, and it is claim rather than the seen + remember
pair that first suggests itself. That pair looks equivalent and is not: between
the read and the write, a second delivery of the same event reads false as
well, and both handlers proceed. Retries make that likely rather than rare - a
slow endpoint is exactly the one we retry, so the second delivery arrives while
the first is still running.
The database you already have does the whole thing in one statement:
const store = {
async claim(eventId: string) {
const { rowCount } = await db.query(
`INSERT INTO processed_webhook_events (id) VALUES ($1)
ON CONFLICT (id) DO NOTHING`,
[eventId],
);
return rowCount === 1; // 1 = we claimed it, 0 = somebody already had it
},
};Redis is SET id 1 NX and the same reading of the reply. For tests and local
development there is memoryWebhookEventStore(), which is explicitly not for
production - it forgets on restart and is not shared between instances.
One caveat, because it decides correctness. claimWebhookEvent claims
before your work runs. If the process dies in between, the event is marked
handled and never was. Where that matters - anything that moves money - do the
claim and the work in one transaction of your own and let the commit decide
both, using parseWebhookEvent to verify and hand you the event.
The verifier uses timing-safe HMAC comparison and rejects timestamps older than
5 minutes (configurable via toleranceSeconds).
A signature does not stop a replay. It proves the payload came from us and is recent; it says nothing about how many times you have seen it. The identical delivery replayed inside the tolerance window verifies every time, by design - that is what makes the deduplication above your job rather than ours. An SDK with no storage cannot know what "already processed" means for your system.
Amounts
Every amount is an integer in the currency's minor unit, and the scale follows the currency rather than always being hundredths:
await client.payments.create({ amount: 5000, currency: "EUR", country: "DE" }); // EUR 50.00
await client.payments.create({ amount: 5000, currency: "JPY", country: "JP" }); // JPY 5,000
await client.payments.create({ amount: 5000, currency: "KWD", country: "KW" }); // KWD 5.000EUR and USD have two decimals, JPY and KRW have none, KWD and BHD have three.
If you format amounts yourself, take the exponent from Intl:
const digits = new Intl.NumberFormat("en", { style: "currency", currency })
.resolvedOptions().minimumFractionDigits;
const major = minor / 10 ** digits;Environments
A ps_test_ key reads and writes sandbox data only, a ps_live_ key production
only. The partition is complete: a test key cannot retrieve a production
payment, sandbox outcomes never train live routing (they teach the sandbox's own
routing, kept apart), and they are excluded
when you filter reporting to live. Idempotency keys are scoped per environment
too, so the same key in sandbox and in production are independent.
White-label partners
Only for workspaces flagged as partners; everything else answers 403
not_a_partner.
const merchants = await client.merchants.list();
// Provisioning requires a LIVE key - a test key answers 403 live_key_required.
const merchant = await client.merchants.create({
name: "Acme Ltd",
owner_email: "[email protected]",
plan: "core",
});Re-inviting an owner who already has a pending invitation answers 409
already_invited rather than creating a second workspace, so retrying after a
timeout is safe.
Errors
All API failures throw a PayshenError subclass - handle the ones you care
about, let the rest bubble.
import {
PayshenAuthError,
PayshenValidationError,
PayshenRateLimitError,
PayshenNetworkError,
PayshenError,
} from "@payshen/sdk";
try {
await client.payments.create(input);
} catch (err) {
if (err instanceof PayshenAuthError) // 401/403 - rotate the key, or give it the scope
else if (err instanceof PayshenValidationError) // 422 - fix the request
else if (err instanceof PayshenRateLimitError) // 429 - back off; .retryAfterSeconds is set
else if (err instanceof PayshenNetworkError) // DNS/timeout/abort after retries
else if (err instanceof PayshenError) // anything else with status/code
throw err;
}err.code is the server's stable code (typed PayshenErrorCode, which lists
every code the API documents for these calls); switch on it, never on the
message. insufficient_scope (403) means the key is restricted to scopes
(set under Developers → API keys) and this call needs one it lacks; the
message names it. A service that only reads payments, or only refunds, can
use a key restricted to payments:read or refunds:write. A PayshenValidationError carries the server's own 422 code
(validation_error, idempotency_key_reuse, invalid_amount,
no_eligible_method, ...).
The client automatically retries 408 / 425 / 429 / 5xx and network
failures with exponential backoff (250ms base, capped at 4s, with jitter),
always under the same Idempotency-Key. 429 retries honour the
Retry-After header when the server sends one. It does not retry an answer
the API says a retry cannot change, and returns it at once:
payment_result_unknown, capture_result_unknown, void_result_unknown,
refund_result_unknown, state_unconfirmed and state_conflict (the
provider may have acted: do not retry under a new key either; Payshen settles
it from the provider's record), psp_error (the provider refused),
provider_unavailable and merchant_limit.
Cancellation
Pass an AbortSignal to cancel an in-flight request - it composes with the
SDK's own per-request timeout.
const ac = new AbortController();
setTimeout(() => ac.abort(), 2_000);
await client.payments.create(input, { signal: ac.signal });Changes
See CHANGELOG.md.
License
MIT - see LICENSE.
