@alexasomba/paystack-node

中文文档
1.12.0发布于 2026/10/10MITTypeScriptES Module构建来源已验证近 30 天下载 4173

The most comprehensive Node.js SDK for Paystack - Complete, Type-safe, and Spec-compliant with full OpenAPI coverage and webhook verification.

原始使用文档
文档目录51 节
  1. Features
  2. Install
  3. Agent Skills
  4. Quick Start
  5. API Basics
  6. Authentication & Environments
  7. Advanced Configuration
  8. Stable Type Exports
  9. Webhooks
  10. Handling Pagination
  11. Pagination
  12. Error Handling
  13. Errors
  14. Coverage
  15. Modules
  16. Module Examples
  17. Transactions
  18. Verify Payments (Transaction verification)
  19. Charges
  20. Bulk Charges
  21. Subaccounts
  22. Transaction Splits
  23. Terminal
  24. Virtual Terminal
  25. Customers
  26. Direct Debit
  27. Dedicated Virtual Accounts
  28. Apple Pay
  29. Plans
  30. Subscriptions
  31. Transfer Recipients
  32. Transfers
  33. Transfers Control (OTP settings; under Transfers)
  34. Balance
  35. Payment Requests (Invoices)
  36. Verification (Resolve Account / Validate Account / Resolve …
  37. Products
  38. Storefronts
  39. Orders
  40. Payment Pages
  41. Settlements
  42. Integration
  43. Control Panel (Payment session timeout; under Integration)
  44. Refunds
  45. Disputes
  46. Banks
  47. Miscellaneous
  48. Related SDKs
  49. Used By
  50. Source
  51. License

@alexasomba/paystack-node

npm version license bundle size

TypeScript-first Paystack API client for Node.js, generated from the official Paystack OpenAPI spec.

Features

  • Spec-driven Accuracy: Generated directly from the Paystack OpenAPI specification.
  • 100% Type-safe: Full TypeScript support with generated types for every endpoint, request, and response.
  • Smart Retries: Automatic retries for transient failures with exponential backoff and jitter.
  • Retry-After Compliance: Automatically respects Paystack Retry-After headers on rate limit responses.
  • Sophisticated Idempotency: Built-in support for manual, static, or automatic UUID-based idempotency keys on POST requests.
  • Detailed Error Handling: PaystackError preserves Paystack code, type, meta, request ID, HTTP status, and the raw response body.
  • Webhook Verification: Timing-safe webhook signature verification helper included.

Install

pnpm add @alexasomba/paystack-node

Agent Skills

This package ships TanStack Intent skills for agent-assisted Paystack integration:

npx @tanstack/intent@latest list
npx @tanstack/intent@latest install --map
npx @tanstack/intent@latest load @alexasomba/paystack-node#paystack-node-api-operations

Useful skills include paystack-node-client-setup, paystack-node-api-operations, paystack-node-operation-discovery, paystack-node-typed-payloads, paystack-node-responses-errors, paystack-node-retries-idempotency, paystack-node-transport-testing, and paystack-node-webhooks.

Authenticate requests with your Paystack secret key:

process.env.PAYSTACK_SECRET_KEY = "sk_test_...";

Quick Start

import { createPaystack, assertOk } from "@alexasomba/paystack-node";

const paystack = createPaystack({
  secretKey: process.env.PAYSTACK_SECRET_KEY!,
  idempotencyKey: "auto",
});

const result = await paystack.transaction_initialize({
  body: {
    email: "[email protected]",
    amount: 5000,
  },
});

const data = assertOk(result);
console.log(data.authorization_url);

assertOk returns the successful Paystack payload and throws a structured PaystackError for non-2xx responses or { status: false } envelopes.

API Basics

  • Base URL: https://api.paystack.co
  • HTTPS is required for all requests.
  • Requests and responses are JSON-based.
  • Most successful responses follow the status, message, data, and optional meta envelope described in Paystack-API/0a-Introduction.md.
  • Amounts are usually sent in currency subunits such as kobo, pesewas, or cents. Check the module docs for currency-specific rules.

Authentication & Environments

  • Server-side SDKs should use your secret key (sk_test_* or sk_live_*).
  • Browser SDKs should use only your public key (pk_test_* or pk_live_*).
  • Send server-side API credentials as Authorization: Bearer YOUR_SECRET_KEY.
  • Test and live modes use different keys and isolated environments.
  • Rotate keys if they are exposed, and never commit secret keys to source control.
  • If you enable IP whitelisting in Paystack, requests from non-whitelisted IPs will be blocked.

Advanced Configuration

The createPaystack helper accepts PaystackClientOptions:

const paystack = createPaystack({
  secretKey: "sk_...",
  timeoutMs: 30_000,
  retry: {
    retries: 3,
    minDelayMs: 500,
    retryOnStatuses: [429, 500, 503],
  },
  idempotencyKey: "auto",
  headers: {
    "X-My-App": "v1.0.0",
  },
});

Stable Type Exports

This SDK exports stable grouped client slices and curated request/query/response aliases so downstream integrations do not need to reconstruct types from ReturnType<typeof createPaystack>, paths, or operations.

import {
  createPaystack,
  type Paystack,
  type PaystackTransactionClient,
  type PaystackSubscriptionClient,
  type TransactionInitializePayload,
  type TransactionChargeAuthorizationPayload,
  type SubscriptionCreatePayload,
  type SubscriptionListQueryParams,
  type RefundCreatePayload,
} from "@alexasomba/paystack-node";

const paystack: Paystack = createPaystack({
  secretKey: process.env.PAYSTACK_SECRET_KEY!,
});

const transactionClient: PaystackTransactionClient = paystack.transaction;
const subscriptionClient: PaystackSubscriptionClient = paystack.subscription;

const tx: TransactionInitializePayload = {
  email: "[email protected]",
  amount: 5000,
};

const chargeAuthorization: TransactionChargeAuthorizationPayload = {
  email: "[email protected]",
  amount: 2500,
  authorization_code: "AUTH_123",
};

const subscriptionCreate: SubscriptionCreatePayload = {
  customer: "CUS_123",
  plan: "PLN_123",
};

const subscriptionList: SubscriptionListQueryParams = {
  customer: 123,
};

const refundCreate: RefundCreatePayload = {
  transaction: "TRX_123",
  amount: 1000,
};

Notable aliases include transaction initialize / charge authorization / verify; subscription create / list / disable / enable / fetch / manage link / manage email; customer fetch / create / update; plan list / create / update / fetch; product list / create / update / fetch; dispute list / fetch; refund create / fetch; payment request create / fetch; terminal send-event; and verification helpers for account resolution, account validation, and card BIN lookup.

Client slices include PaystackTransactionClient, PaystackCustomerClient, PaystackSubscriptionClient, PaystackPlanClient, PaystackProductClient, PaystackDisputeClient, and PaystackRefundClient.

Grouped methods reflect supported generated OpenAPI operations. Unsupported helpers such as subscription.update are intentionally not part of the public SDK surface.

Webhooks

Use the webhook helper when validating server-to-server events from Paystack. Pass the raw request body, not a parsed JSON object.

import { verifyPaystackWebhookSignature } from "@alexasomba/paystack-node/webhooks";

const isValid = verifyPaystackWebhookSignature({
  rawBody: req.body,
  signature: req.headers["x-paystack-signature"],
  secret: process.env.PAYSTACK_SECRET_KEY!,
});

Handling Pagination

List endpoints expose pagination controls through query params like perPage, page, next, and previous. Response headers are still available when you need manual pagination control.

Pagination

  • Paystack supports both offset pagination and cursor pagination.
  • Offset pagination uses page and perPage.
  • Cursor pagination uses use_cursor=true plus next or previous cursors returned in meta.
  • Cursor pagination is especially useful for large or frequently changing datasets.
  • The exact meta shape varies by endpoint and pagination mode.
const result = await paystack.customer_list({ query: { perPage: 20 } });
const customers = assertOk(result);
const total = result.response.headers.get("x-total-count");

Error Handling

import { toPaystackApiError } from "@alexasomba/paystack-node";

const result = await paystack.transaction_initialize({/* ... */});
const error = toPaystackApiError(result);

if (error) {
  console.error(`Status ${error.status}: ${error.message}`);
  console.error(`Paystack code: ${error.code}`);
  console.error(`Paystack type: ${error.type}`);
  console.error(`Paystack Request ID: ${error.requestId}`);
  console.error(error.raw);
}

Use error.code and error.type for branching on validation, processor, and API failures. The requestId is useful when correlating logs or escalating an issue with Paystack support, while error.raw / error.body keeps the original response envelope available for diagnostics.

Errors

  • Paystack uses conventional HTTP status codes such as 200, 201, 400, 401, 404, and 5xx.
  • Error responses typically include status, message, type, code, and optional diagnostic meta information.
  • Error types described in Paystack-API/0d-Errors.md include api_error, validation_error, and processor_error.
  • For charge and verify flows, always inspect the returned response body and status fields, not just the HTTP code.

Coverage

This SDK is generated from the SDK spec in this monorepo and currently tracks the full set of generated typed operations for the Paystack-API-aligned contract.

Modules

For this SDK, these schema families are exposed through generated TypeScript types in src/openapi-types.ts and operation helpers in src/operations.ts.

ModuleSchema / model family
TransactionsTransaction*
Verify Payments (Transaction verification)VerifyResponse / TransactionFetchResponse
ChargesCharge*
Bulk ChargesBulkCharge*
SubaccountsSubaccount*
Transaction SplitsSplit*
TerminalTerminal*
Virtual TerminalVirtualTerminal*
CustomersCustomer*
Direct DebitDirectDebit*
Dedicated Virtual AccountsDedicatedNuban* / DedicatedVirtualAccount*
Apple PayApplePay*
PlansPlan*
SubscriptionsSubscription*
Transfer RecipientsTransferRecipient*
TransfersTransfer*
Transfers Control (OTP settings; under Transfers)TransferEnable* / TransferDisable* / TransferFinalize*
BalanceBalance*
Payment Requests (Invoices)PaymentRequest*
Verification (Resolve Account / Validate Account / Resolve Card BIN)Verification*
ProductsProduct*
StorefrontsStorefront*
OrdersOrder*
Payment PagesPage*
SettlementsSettlement*
IntegrationIntegration*
Control Panel (Payment session timeout; under Integration)ControlPanel*
RefundsRefund*
DisputesDispute*
BanksBank*
MiscellaneousMiscellaneous* / Currency

Module Examples

These are intentionally short examples. Use them as entry points, then expand the request bodies with the typed fields exposed by your editor and src/openapi-types.ts.

Transactions

const tx = await paystack.transaction_initialize({
  body: { email: "[email protected]", amount: 5000 },
});

Verify Payments (Transaction verification)

const verified = await paystack.transaction_verify({
  params: { path: { reference: "ref_123" } },
});

Charges

await paystack.charge_create({
  body: {
    email: "[email protected]",
    amount: 5000,
    bank: { code: "057", account_number: "0001234567" },
  },
});

Bulk Charges

await paystack.bulkCharge_initiate({
  body: [{ authorization: "AUTH_xxx", amount: 5000, reference: "bulk-ref-1" }],
});

Subaccounts

await paystack.subaccount_create({
  body: {
    business_name: "Acme Stores",
    settlement_bank: "057",
    account_number: "0001234567",
    percentage_charge: 10,
  },
});

Transaction Splits

await paystack.split_create({
  body: { name: "Main split", type: "percentage", currency: "NGN", subaccounts: [] },
});

Terminal

const terminals = await paystack.terminal_list();

Virtual Terminal

await paystack.virtualTerminal_create({
  body: { name: "Web checkout terminal" },
});

Customers

await paystack.customer_create({
  body: { email: "[email protected]", first_name: "Ada", last_name: "Lovelace" },
});

Direct Debit

await paystack.directdebit_initialize({
  body: { email: "[email protected]", amount: 5000, bank_code: "057" },
});

Dedicated Virtual Accounts

await paystack.dedicatedAccount_assign({
  body: { customer: 12345, preferred_bank: "wema-bank" },
});

Apple Pay

await paystack.applePay_registerDomain({
  body: { domainName: "example.com" },
});

Plans

await paystack.plan_create({
  body: { name: "Starter", amount: 500000, interval: "monthly" },
});

Subscriptions

await paystack.subscription_create({
  body: { customer: "CUS_xxx", plan: "PLN_xxx" },
});

Transfer Recipients

await paystack.transferrecipient_create({
  body: {
    type: "nuban",
    name: "Ada Lovelace",
    account_number: "0001234567",
    bank_code: "057",
    currency: "NGN",
  },
});

Transfers

await paystack.transfer_create({
  body: { source: "balance", amount: 5000, recipient: "RCP_xxx", reason: "Vendor payout" },
});

Transfers Control (OTP settings; under Transfers)

await paystack.transfer_enableOtp();

Balance

const balance = await paystack.balance_fetch();

Payment Requests (Invoices)

await paystack.paymentRequest_create({
  body: { customer: "CUS_xxx", amount: 5000, description: "Consulting invoice" },
});

Verification (Resolve Account / Validate Account / Resolve Card BIN)

await paystack.bank_resolveAccountNumber({
  params: { query: { account_number: "0001234567", bank_code: "057" } },
});

Products

await paystack.product_create({
  body: { name: "T-shirt", description: "Cotton tee", price: 5000, currency: "NGN" },
});

Storefronts

const storefronts = await paystack.storefront_list();

Orders

await paystack.order_create({
  body: { customer: "CUS_xxx", items: [] },
});

Payment Pages

await paystack.page_create({
  body: { name: "Event Ticket", amount: 5000, description: "Landing page for ticket sales" },
});

Settlements

const settlements = await paystack.settlement_list();

Integration

const timeout = await paystack.integration_fetchPaymentSessionTimeout();

Control Panel (Payment session timeout; under Integration)

await paystack.integration_updatePaymentSessionTimeout({
  body: { timeout: 20 },
});

Refunds

await paystack.refund_create({
  body: { transaction: 123456789, amount: 5000 },
});

Disputes

const disputes = await paystack.dispute_list();

Banks

const banks = await paystack.bank_list({ params: { query: { country: "nigeria" } } });

Miscellaneous

const countries = await paystack.miscellaneous_listCountries();

Used By

Source

License

MIT

版本与发布记录

@alexasomba/paystack-node 共发布 24 个版本,首次发布于 2025/12/15;过去 12 个月发布了 24 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.12.0latest2026/10/1027 天前
1.11.12026/10/1027 天前
1.11.02026/10/1027 天前
1.10.92026/10/0927 天前
1.10.82026/06/234 个月前
1.10.72026/06/015 个月前

关于 @alexasomba/paystack-node 的常见问题

@alexasomba/paystack-node 是什么?

The most comprehensive Node.js SDK for Paystack - Complete, Type-safe, and Spec-compliant with full OpenAPI coverage and webhook verification.

如何安装 @alexasomba/paystack-node?

在项目目录运行 npm install @alexasomba/paystack-node,或使用 pnpm add / yarn add / bun add。

@alexasomba/paystack-node 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@alexasomba/paystack-node 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@alexasomba/paystack-node 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@alexasomba/paystack-node 可以商用吗?

@alexasomba/paystack-node 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@alexasomba/paystack-node 的下载量有多少?

根据 npm 官方下载统计,@alexasomba/paystack-node 在 2026/10/06 – 2026/11/04 这 30 天内被下载 4,173 次,日均约 139 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@alexasomba/paystack-node 还在维护吗?

最新版本 1.12.0 发布于 2026/10/10(27 天前);至今共发布 24 个版本,其中过去 12 个月发布了 24 个;首次发布于 2025/12/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。