@alexasomba/paystack-inline

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

A strongly-typed, Promise-based TypeScript wrapper for Paystack Popup (inline.js).

原始使用文档
文档目录29 节
  1. Features
  2. Installation
  3. Agent Skills
  4. Quick Start
  5. 1. Initialize from your server (required)
  6. 2. Resume the transaction in the browser
  7. API Reference
  8. loadPaystack()
  9. popup.resumeTransaction(accessCode, callbacks?)
  10. popup.newTransaction(options)
  11. popup.preloadTransaction(options) → () => void
  12. popup.checkout(options) → Promise<PopupTransaction>
  13. popup.cancelTransaction(idOrTransaction)
  14. popup.paymentRequest(options) → Promise<PopupTransaction>
  15. Callbacks
  16. Subscriptions
  17. Split Payments
  18. Framework Examples
  19. React
  20. Next.js (App Router)
  21. Vue 3
  22. Svelte / SvelteKit
  23. TypeScript Reference
  24. PopupTransactionStatus
  25. Complete Payment Flow
  26. Security Notes
  27. Related Resources
  28. Source
  29. License

@alexasomba/paystack-inline

A strongly-typed, Promise-based TypeScript wrapper for the Paystack Popup (inline.js). Gives you full IDE autocomplete and type safety, while securely deferring all the heavy lifting — iframe rendering, WebSockets, Apple Pay sessions, PCI compliance — to Paystack's official CDN.

Why not bundle inline.js directly?
Paystack ships security and fraud-detection patches silently via their CDN. By dynamically loading the script at runtime, your users always get the latest, most secure version — without you having to cut a new release.


Features

  • ✅ Zero dependencies — no npm bloat, 0.91 kB gzipped
  • ✅ Full TypeScript types for every option, callback, and response
  • ✅ All documented and undocumented aliases from inline.js included
  • ✅ loadPaystack() promise prevents race conditions and double-loading
  • ✅ Supports: Cards, Bank, USSD, Mobile Money, Bank Transfer, QR, Apple Pay, Subscriptions, Splits
  • ✅ Works with React, Vue, Svelte, Next.js, SvelteKit, plain HTML — any frontend

Installation

npm install @alexasomba/paystack-inline
# or
pnpm add @alexasomba/paystack-inline
# or
yarn add @alexasomba/paystack-inline

Agent Skills

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

npx @tanstack/intent@latest list
npx @tanstack/intent@latest install --map
npx @tanstack/intent@latest load @alexasomba/paystack-inline#paystack-inline-checkout

Useful skills include paystack-inline-checkout, paystack-inline-server-verify, paystack-inline-popup-options, and paystack-inline-popup-lifecycle.


Quick Start

1. Initialize from your server (required)

Never call Paystack's API from the browser — your secret key would be exposed. Initialize on your backend and pass the access_code to the frontend:

curl https://api.paystack.co/transaction/initialize \
  -H "Authorization: Bearer YOUR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "email": "[email protected]", "amount": "500000" }' \
  -X POST

The response contains data.access_code. Send this to your frontend.

2. Resume the transaction in the browser

import { loadPaystack } from "@alexasomba/paystack-inline";

const PaystackPop = await loadPaystack();
const popup = new PaystackPop();

popup.resumeTransaction(accessCode, {
  onSuccess: (response) => {
    console.log("Payment successful!", response.reference);
    // Verify on your server before delivering value
  },
  onCancel: () => {
    console.log("User cancelled payment");
  },
});

Always verify server-side after onSuccess. Never deliver value based solely on a client callback — confirm with the Verify Transaction endpoint.


API Reference

loadPaystack()

Dynamically injects https://js.paystack.co/v2/inline.js into the page and resolves with the PaystackPop constructor. Safe to call multiple times — only one script tag is ever created.

import { loadPaystack } from "@alexasomba/paystack-inline";

const PaystackPop = await loadPaystack();
const popup = new PaystackPop();

Throws if called outside a browser (e.g. server-side rendering). Wrap in a browser check if needed:

if (typeof window !== "undefined") {
  const PaystackPop = await loadPaystack();
}

popup.resumeTransaction(accessCode, callbacks?)

The recommended checkout flow. Initialize on your server, then resume on the client.

popup.resumeTransaction("br6cgmvflhn3qtd", {
  onSuccess: (res) => console.log(res.reference),
  onCancel: () => console.log("cancelled"),
  onError: (err) => console.error(err.message),
});

popup.newTransaction(options)

Start a transaction directly from the frontend using your public key.

[!WARNING] The amount must be in the lowest currency denomination (e.g. kobo for NGN, pesewas for GHS). 500000 = ₦5,000.

const transaction = popup.newTransaction({
  key: "pk_test_xxxxxxxxx",
  email: "[email protected]",
  amount: 500000,
  currency: "NGN",
  reference: "unique-ref-" + Date.now(),
  onSuccess: (response) => {
    console.log("Transaction ref:", response.reference);
  },
  onCancel: () => {
    console.log("Checkout closed");
  },
});

Core Options

OptionTypeRequiredDescription
keystring✅Your Paystack public key (pk_...)
emailstring✅Customer's email address
amountnumber✅Amount in the lowest currency unit (e.g. kobo)
currencystring—Currency code: NGN, GHS, ZAR, KES, USD
referencestring—Unique transaction reference. Auto-generated if unset
labelstring—Customer name shown on the checkout
channelsstring[]—Limit channels: ["card", "bank", "ussd", "mobile_money", "bank_transfer", "qr", "eft"]
metadataobject—Arbitrary key-value data attached to the transaction
languagestring—Force checkout language (en, fr, pt, etc.)

Customer Options

OptionTypeDescription
firstNamestringPre-fill customer first name
lastNamestringPre-fill customer last name
phonestringCustomer phone number
customerCodestringExisting Paystack customer code

popup.preloadTransaction(options) → () => void

Pre-fetches the checkout iframe in the background for a snappy UX. Returns a function to open the pre-loaded popup.

const open = popup.preloadTransaction({
  key: "pk_test_xxxxxxx",
  email: "[email protected]",
  amount: 100000,
  onSuccess: (res) => verifyOnServer(res.reference),
});

// Later, when user clicks "Pay":
document.getElementById("pay-btn").addEventListener("click", open);

popup.checkout(options) → Promise<PopupTransaction>

Promise-based checkout. Resolves with the PopupTransaction object when the popup opens.

const transaction = await popup.checkout({
  key: "pk_test_xxxxxxx",
  email: "[email protected]",
  amount: 200000,
  onSuccess: (res) => console.log(res),
});

// Check status at any time:
console.log(transaction.getStatus());

popup.cancelTransaction(idOrTransaction)

Programmatically close an open transaction.

const tx = popup.newTransaction({ ... });
// ... later
popup.cancelTransaction(tx); // or popup.cancelTransaction(tx.id)

popup.paymentRequest(options) → Promise<PopupTransaction>

Renders an embedded payment element (Apple Pay button, wallet button) into a DOM container. Perfect for custom checkout UIs.

const payment = await popup.paymentRequest({
  key: "pk_test_xxxxxxx",
  email: "[email protected]",
  amount: 500000,
  container: "#payment-request-container", // CSS selector or element ID
  onSuccess: (res) => console.log(res),
  onElementsMount: (elements) => {
    console.log("Payment elements mounted:", elements);
  },
  styles: {
    theme: "dark",
    applePay: {
      width: "100%",
      height: "48px",
      borderRadius: "8px",
      type: "buy", // "plain" | "buy" | "donate"
      locale: "en-US",
    },
  },
});

paymentRequest Options

OptionTypeDescription
containerstring✅ CSS selector or element ID of the mount target
loadPaystackCheckoutButtonstringSelector for a custom button that opens the full Popup
styles.theme"dark" | "light"Apple Pay button theme
styles.applePay.typestringApple Pay button label: "plain", "buy", "donate"
styles.applePay.localestringApple Pay button locale
onElementsMountfunctionFires when the embedded elements appear in the DOM

Callbacks

All transaction methods accept the same callback interface:

CallbackSignatureDescription
onSuccess(res: { id, reference, message }) => voidPayment completed successfully
onError(err: { message: string }) => voidPayment failed with an error
onCancel() => voidUser closed the popup before completing
onClose() => voidPopup was closed (includes both cancel and success)
onLoad(res: { id, customer, accessCode }) => voidPopup fully loaded and ready
onBankTransferConfirmationPending() => voidBank transfer initiated, awaiting confirmation
callback(res: any) => voidLegacy v1 callback (use onSuccess instead)

Subscriptions

Charge customers on a recurring plan:

popup.newTransaction({
  key: "pk_test_xxxxxxx",
  email: "[email protected]",
  amount: 500000,
  plan: "PLN_xxxxxxxxx", // or planCode
  quantity: 1, // number of seats/plan units
  interval: "monthly", // or planInterval
  invoice_limit: 12, // stop after N billing cycles
  start_date: "2025-01-01T00:00:00Z",
  onSuccess: (res) => console.log(res),
});

Subscription Options

OptionTypeAliasesDescription
planCodestringplanPaystack plan code (PLN_...)
subscriptionCountnumberquantityNumber of subscriptions / seats
planIntervalstringintervalhourly, daily, weekly, monthly, annually
subscriptionLimitnumberinvoice_limitMax billing cycles before stopping
subscriptionStartDatestringstart_dateISO 8601 date for first charge

Split Payments

Route portions of a payment to subaccounts:

popup.newTransaction({
  key: "pk_test_xxxxxxx",
  email: "[email protected]",
  amount: 500000,
  subaccount: "ACCT_xxxxxxxxx", // or subaccountCode
  bearer: "account", // who bears transaction charges
  transaction_charge: 2000, // flat charge for the main account (kobo)
  onSuccess: (res) => console.log(res),
});

Split Options

OptionTypeAliasesDescription
subaccountCodestringsubaccountSubaccount code to split with
split_codestringReference a pre-configured split group
splitobjectInline split configuration object
connect_splitstring[]Array of connected account codes for multi-split
bearer"account" | "subaccount"Who absorbs the transaction fee
transactionChargestring | numbertransaction_chargeFlat fee (in kobo) retained by the main account

Framework Examples

React

import { loadPaystack } from "@alexasomba/paystack-inline";

function CheckoutButton({ accessCode }: { accessCode: string }) {
  const handlePay = async () => {
    const PaystackPop = await loadPaystack();
    const popup = new PaystackPop();

    popup.resumeTransaction(accessCode, {
      onSuccess: (response) => {
        // Call your API to verify + fulfill the order
        fetch("/api/verify", {
          method: "POST",
          body: JSON.stringify({ reference: response.reference }),
        });
      },
      onCancel: () => console.log("Payment cancelled"),
    });
  };

  return <button onClick={handlePay}>Pay Now</button>;
}

Next.js (App Router)

"use client"; // Required — loadPaystack() is browser-only

import { loadPaystack } from "@alexasomba/paystack-inline";

export default function PayButton({ accessCode }: { accessCode: string }) {
  const handlePay = async () => {
    const PaystackPop = await loadPaystack();
    const popup = new PaystackPop();
    popup.resumeTransaction(accessCode, {
      onSuccess: (res) => console.log(res.reference),
    });
  };

  return <button onClick={handlePay}>Complete Payment</button>;
}

Vue 3

<script setup lang="ts">
import { loadPaystack } from "@alexasomba/paystack-inline";

const props = defineProps<{ accessCode: string }>();

const handlePay = async () => {
  const PaystackPop = await loadPaystack();
  const popup = new PaystackPop();
  popup.resumeTransaction(props.accessCode, {
    onSuccess: (res) => console.log(res.reference),
  });
};
</script>

<template>
  <button @click="handlePay">Pay Now</button>
</template>

Svelte / SvelteKit

<script lang="ts">
  import { loadPaystack } from "@alexasomba/paystack-inline";

  export let accessCode: string;

  async function handlePay() {
    const PaystackPop = await loadPaystack();
    const popup = new PaystackPop();
    popup.resumeTransaction(accessCode, {
      onSuccess: (res) => console.log(res.reference),
    });
  }
</script>

<button on:click={handlePay}>Pay Now</button>

TypeScript Reference

All exported types are available for direct import:

import type {
  PaystackPopGeneralOptions,
  PaystackPopCallbacks,
  PaystackPopNewTransactionOptions,
  PaystackPopCheckoutOptions,
  PaystackPopPaymentRequestOptions,
  PaystackPopSplitOptions,
  PaystackPopSubscriptionOptions,
  PaystackPopInstance,
  PopupTransaction,
  PopupTransactionStatus,
} from "@alexasomba/paystack-inline";

PopupTransactionStatus

interface PopupTransactionStatus {
  status: "null" | "error" | "abandoned" | "auth" | "failed" | "success" | "pending";
  id?: string;
  errors?: any[];
  response?: any;
  checkoutUrl?: string;
}

Complete Payment Flow

┌─────────────────┐      POST /transaction/initialize      ┌─────────────────┐
│   Your Backend  │ ─────────────────────────────────────► │  Paystack API   │
│  (Secret Key)   │ ◄───────────────────────────────────── │                 │
└────────┬────────┘            { access_code }             └─────────────────┘
         │
         │  access_code
         ▼
┌─────────────────┐       loadPaystack() + resumeTransaction()
│   Your Frontend │ ─────────────────────────────────────► Paystack Popup UI
│  (Public Key)   │ ◄─────────────── onSuccess({ reference }) ──────────────
└────────┬────────┘
         │
         │  Verify reference on YOUR server (never trust client callbacks alone)
         ▼
┌─────────────────┐      GET /transaction/verify/:reference
│   Your Backend  │ ─────────────────────────────────────► Paystack API
│                 │ ◄─────────────── { status: "success" } ─────────────────
└─────────────────┘
         │
         │  Deliver value to customer ✅

Security Notes

  • Never use your Secret Key on the frontend. Use only your Public Key (pk_...).
  • Always verify transactions server-side before delivering value — the onSuccess callback can be spoofed.
  • The script at https://js.paystack.co/v2/inline.js is loaded over HTTPS and served with integrity-safe headers by Paystack's CDN.


Source


License

MIT © alexasomba

版本与发布记录

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

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

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

@alexasomba/paystack-inline 是什么?

A strongly-typed, Promise-based TypeScript wrapper for Paystack Popup (inline.js).

如何安装 @alexasomba/paystack-inline?

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

@alexasomba/paystack-inline 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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

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

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