A type-safe Paystack API library for Node.js
npm install @enviabledev/paystack-apiA modern, fully-typed, and efficient Node.js library for interacting with the Paystack API. Built with TypeScript, it provides a clean, class-based interface to all Paystack resources, complete with robust error handling and helper utilities. This library is developed and maintained by Enviable Transport Services Software Developemnt Team.
- Features
- Installation
- Getting Started
- API Reference
- Bulk Charge
- Charge
- Control Panel
- Customer
- Dedicated NUBAN
- Miscellaneous
- Payment Page
- Payment Request
- Plan
- Refund
- Settlement
- Subaccount
- Subscription
- Transaction
- Transfer
- Transfer Control
- Transfer Recipient
- Verification
- Helpers
- Handling Webhooks
- Fee Calculator
- Error Handling
- Contributing
- License
- Complete API Coverage: All Paystack API endpoints are mapped to intuitive methods
- Fully-Typed: Written in TypeScript to provide static typing and autocompletion for all payloads and responses
- Modern Syntax: Uses async/await for clean, readable, and non-blocking asynchronous code
- Robust Error Handling: Provides custom error classes to easily distinguish between API errors, network issues, and other exceptions
- Helpful Utilities: Includes helpers for webhook signature verification and fee calculation
``bash`
npm install @enviabledev/paystack-api
To get started, initialize the client with your Paystack secret key.
`javascript
import paystack from '@enviabledev/paystack-api';
// Initialize the client with your secret key
const paystackClient = paystack('YOUR_PAYSTACK_SECRET_KEY');
// Example: Verify a transaction
async function verifyTransaction(reference) {
try {
const response = await paystackClient.transaction.verify(reference);
console.log(response.data.status); // e.g., 'success'
console.log(response.data.customer.email);
} catch (error) {
console.error(error);
}
}
verifyTransaction('your_transaction_reference');
`
This library provides access to all Paystack API resources through the paystackClient object.
Handles batch processing of charges.
- paystackClient.bulkCharge.create(payload): Initiates a new bulk chargeCreateBulkChargePayload
- Payload: - An object with a charges property, which is an array of objects containing authorization (string), amount (number), and optional reference (string)
- paystackClient.bulkCharge.list(params): Lists bulk charge batchesListBulkChargesParams
- Params: (optional) for pagination (perPage, page) and filtering (status, from, to)
- paystackClient.bulkCharge.get(id): Retrieves a single bulk charge batch
- ID: The batch ID or code (string)
- paystackClient.bulkCharge.getCharges(id, params): Retrieves all charges within a batchListBulkChargeChargesParams
- ID: The batch ID or code (string)
- Params: (optional) for pagination and filtering
- paystackClient.bulkCharge.pause(batchCode): Pauses a running bulk charge batch
- paystackClient.bulkCharge.resume(batchCode): Resumes a paused bulk charge batch
Handles tokenization and charging of payment instruments.
- paystackClient.charge.tokenize(payload): Creates a reusable token from card detailsTokenizePayload
- Payload: with email and a card object (number, cvv, expiry_month, expiry_year)
- paystackClient.charge.charge(payload): Initiates a new chargeChargePayload
- Payload: with email, amount, and payment details (e.g., authorization_code, pin, bank)
- paystackClient.charge.submitPin(payload): Submits a PIN to continue a chargeSubmitPinPayload
- Payload: with pin and reference
- paystackClient.charge.submitOtp(payload): Submits an OTP to complete a chargeSubmitOtpPayload
- Payload: with otp and reference
- paystackClient.charge.submitPhone(payload): Submits a phone number to continue a chargeSubmitPhonePayload
- Payload: with phone and reference
- paystackClient.charge.submitBirthday(payload): Submits a birthday to continue a chargeSubmitBirthdayPayload
- Payload: with birthday (YYYY-MM-DD) and reference
- paystackClient.charge.submitAddress(payload): Submits an address to continue a chargeSubmitAddressPayload
- Payload: with reference, address, city, state, and zip_code
- paystackClient.charge.checkCharge(reference): Checks the status of a pending charge
Manages integration settings.
- paystackClient.controlPanel.getSessionTimeout(): Gets the payment session timeout for your integration
- paystackClient.controlPanel.updateSessionTimeout(payload): Updates the payment session timeoutUpdateSessionTimeoutPayload
- Payload: with timeout in seconds
Manages customer information.
- paystackClient.customer.create(payload): Creates a new customerCreateCustomerPayload
- Payload: containing email, and optional first_name, last_name, phone, metadata
- paystackClient.customer.list(params): Lists customersListCustomersParams
- Params: (optional) for pagination and filtering
- paystackClient.customer.get(id): Retrieves a customer's details
- ID: The customer's ID or email (string)
- paystackClient.customer.update(id, payload): Updates a customer's detailsUpdateCustomerPayload
- Payload:
- paystackClient.customer.validate(id, payload): Validates a customer's identityValidateCustomerPayload
- Payload:
- paystackClient.customer.setRiskAction(payload): Whitelists or blacklists a customerSetRiskActionPayload
- Payload: with customer (code or email) and risk_action ('allow' or 'deny')
- paystackClient.customer.deactivateAuthorization(payload): Deactivates a customer's authorizationDeactivateAuthorizationPayload
- Payload: with authorization_code
Manages dedicated virtual bank accounts.
- paystackClient.nuban.create(payload): Creates a dedicated virtual accountCreateNubanPayload
- Payload: for a new or existing customer
- paystackClient.nuban.list(params): Lists dedicated virtual accountsListNubansParams
- Params: (optional) for filtering
- paystackClient.nuban.get(id): Retrieves a single dedicated virtual account
- ID: The dedicated account ID (number)
- paystackClient.nuban.requery(params): Requeries a dedicated virtual account to check for transfersRequeryNubanParams
- Params: with account_number, provider_slug, and date
- paystackClient.nuban.deactivate(id): Deactivates a dedicated virtual account
- paystackClient.nuban.removeSplit(payload): Removes a split configuration from a dedicated accountRemoveNubanSplitPayload
- Payload: with account_number
- paystackClient.nuban.listAvailableProviders(): Gets a list of available providers for dedicated accounts
Accesses miscellaneous data like banks and countries.
- paystackClient.misc.listBanks(params): Gets a list of all supported banksListBanksParams
- Params: (optional) for filtering by country, currency, etc.
- paystackClient.misc.listCountries(): Gets a list of all supported countries
- paystackClient.misc.listStates(params): Gets a list of states for a countryListStatesParams
- Params: with country code
Manages hosted payment pages.
- paystackClient.paymentPage.create(payload): Creates a new payment pageCreatePaymentPagePayload
- Payload: with name and other optional fields
- paystackClient.paymentPage.list(params): Lists payment pagesListPaymentPagesParams
- Params: (optional) for pagination and date range filtering
- paystackClient.paymentPage.get(id): Retrieves a payment page
- ID: The page ID or slug (string)
- paystackClient.paymentPage.update(id, payload): Updates a payment pageUpdatePaymentPagePayload
- Payload:
- paystackClient.paymentPage.checkSlugAvailability(slug): Checks if a URL slug is available
- paystackClient.paymentPage.addProducts(id, payload): Adds products to a payment pageAddProductsToPaymentPagePayload
- ID: The page ID (number)
- Payload: with an array of product IDs
Manages professional invoices.
- paystackClient.paymentRequest.create(payload): Creates a new payment request (invoice)CreatePaymentRequestPayload
- Payload: with customer, amount, and due_date
- paystackClient.paymentRequest.list(params): Lists payment requestsListPaymentRequestsParams
- Params: (optional) for filtering
- paystackClient.paymentRequest.get(id): Retrieves a payment request
- ID: The payment request ID or code (string)
- paystackClient.paymentRequest.verify(code): Verifies the payment status of a payment request
- paystackClient.paymentRequest.notify(id): Sends a notification reminder for a payment request
- paystackClient.paymentRequest.getTotals(): Gets total payment request volume and paid count
- paystackClient.paymentRequest.finalize(id): Finalizes a draft payment request
- paystackClient.paymentRequest.update(id, payload): Updates a payment requestUpdatePaymentRequestPayload
- Payload:
- paystackClient.paymentRequest.archive(id): Archives a payment request
Manages subscription plans.
- paystackClient.plan.create(payload): Creates a new subscription planCreatePlanPayload
- Payload: with name, amount, and interval
- paystackClient.plan.list(params): Lists subscription plansListPlansParams
- Params: (optional) for filtering
- paystackClient.plan.get(id): Retrieves a subscription plan
- ID: The plan ID or code (string)
- paystackClient.plan.update(id, payload): Updates a subscription planUpdatePlanPayload
- Payload:
Manages refunds for transactions.
- paystackClient.refund.create(payload): Initiates a refund for a transactionCreateRefundPayload
- Payload: with transaction reference and optional amount
- paystackClient.refund.list(params): Lists refundsListRefundsParams
- Params: (optional) for filtering
- paystackClient.refund.get(id): Retrieves a single refund
- ID: The refund ID (number)
Retrieves settlement information.
- paystackClient.settlement.list(params): Lists settlements made to your bank accountsListSettlementsParams
- Params: (optional) for filtering
- paystackClient.settlement.getTransactions(id, params): Gets transactions associated with a settlementListSettlementTransactionsParams
- ID: The settlement ID (number)
- Params: (optional)
Manages subaccounts for split payments.
- paystackClient.subaccount.create(payload): Creates a new subaccountCreateSubaccountPayload
- Payload: with business_name, settlement_bank, account_number, and percentage_charge
- paystackClient.subaccount.list(params): Lists subaccountsListSubaccountsParams
- Params: (optional)
- paystackClient.subaccount.get(id): Retrieves a subaccount
- ID: The subaccount ID or code (string)
- paystackClient.subaccount.update(id, payload): Updates a subaccountUpdateSubaccountPayload
- Payload:
Manages customer subscriptions.
- paystackClient.subscription.create(payload): Creates a new subscriptionCreateSubscriptionPayload
- Payload: with customer and plan
- paystackClient.subscription.list(params): Lists subscriptionsListSubscriptionsParams
- Params: (optional) for filtering by customer or plan
- paystackClient.subscription.get(id): Retrieves a subscription
- ID: The subscription ID or code (string)
- paystackClient.subscription.enable(payload): Enables a subscriptionToggleSubscriptionPayload
- Payload: with code and token
- paystackClient.subscription.disable(payload): Disables a subscriptionToggleSubscriptionPayload
- Payload: with code and token
- paystackClient.subscription.generateManageLink(code): Generates a link to manage a subscription
- paystackClient.subscription.sendManageEmail(code): Sends a subscription management email
Manages financial transactions.
- paystackClient.transaction.initialize(payload): Initializes a new transactionInitializeTransactionPayload
- Payload: with email and amount
- paystackClient.transaction.verify(reference): Verifies the status of a transaction
- paystackClient.transaction.list(params): Lists transactionsListTransactionsParams
- Params: (optional) for pagination and filtering
- paystackClient.transaction.get(id): Retrieves a transaction
- ID: The transaction ID (number)
- paystackClient.transaction.chargeAuthorization(payload): Charges a customer using a saved authorizationChargeAuthorizationPayload
- Payload: with email, amount, and authorization_code
- paystackClient.transaction.viewTimeline(id): Gets the timeline of a transaction
- ID: The transaction ID or reference (string)
- paystackClient.transaction.totals(params): Gets transaction totalsListTransactionsParams
- Params: (optional) for date range filtering
- paystackClient.transaction.export(params): Exports a list of transactionsListTransactionsParams
- Params: (optional) for filtering
Manages money transfers to bank accounts.
- paystackClient.transfer.create(payload): Initiates a new transferCreateTransferPayload
- Payload: with source, amount, and recipient
- paystackClient.transfer.list(params): Lists transfersListTransfersParams
- Params: (optional)
- paystackClient.transfer.get(idOrCode): Retrieves a transfer
- paystackClient.transfer.finalize(payload): Finalizes a transfer that requires an OTPFinalizeTransferPayload
- Payload: with transfer_code and otp
- paystackClient.transfer.bulk(payload): Initiates a bulk transferBulkTransferPayload
- Payload:
- paystackClient.transfer.verify(reference): Verifies the status of a transfer
Manages transfer settings and balance.
- paystackClient.transferControl.checkBalance(): Checks the available balance on your integration
- paystackClient.transferControl.getBalanceLedger(): Gets the balance ledger for your integration
- paystackClient.transferControl.resendOtp(payload): Resends an OTP for a transferResendOtpPayload
- Payload: with transfer_code and reason
- paystackClient.transferControl.disableOtp(): Disables the OTP requirement for transfers
- paystackClient.transferControl.finalizeDisableOtp(payload): Finalizes the process of disabling OTPFinalizeDisableOtpPayload
- Payload: with otp
- paystackClient.transferControl.enableOtp(): Enables the OTP requirement for transfers
Manages transfer recipients.
- paystackClient.transferRecipient.create(payload): Creates a new transfer recipientCreateTransferRecipientPayload
- Payload: with type and name
- paystackClient.transferRecipient.createBulk(payload): Creates multiple transfer recipients in bulkCreateBulkTransferRecipientsPayload
- Payload:
- paystackClient.transferRecipient.list(params): Lists transfer recipientsListTransferRecipientsParams
- Params: (optional)
- paystackClient.transferRecipient.get(idOrCode): Retrieves a transfer recipient
- paystackClient.transferRecipient.update(idOrCode, payload): Updates a transfer recipientUpdateTransferRecipientPayload
- Payload:
- paystackClient.transferRecipient.remove(idOrCode): Deletes a transfer recipient
Verifies customer and payment details.
- paystackClient.verification.resolveAccount(payload): Resolves a bank account to get the account holder's nameResolveAccountPayload
- Payload: with account_number and bank_code
- paystackClient.verification.validateAccount(payload): Validates a bank accountValidateAccountPayload
- Payload:
- paystackClient.verification.resolveBin(bin): Gets information about a card's Bank Identification Number (BIN)
- BIN: The first 6 digits of the card number (string)
The library provides an Express middleware to securely handle incoming webhook events. It verifies the Paystack signature and emits an event.
`javascript
import express from 'express';
import paystack from '@enviabledev/paystack-api';
const app = express();
const paystackClient = paystack('YOUR_PAYSTACK_SECRET_KEY');
// Use the middleware to verify and parse webhooks
// IMPORTANT: This must be placed before any other body-parsing middleware like express.json()
app.post('/webhook', paystackClient.events.middleware);
// Listen for a specific event
paystackClient.events.on('charge.success', (data) => {
console.log('Charge successful!');
console.log(data); // The event data object
});
// Start your server
app.listen(3000, () => console.log('Server running on port 3000'));
`
The FeeHelper class calculates the total amount to charge a customer to cover Paystack's processing fees.
`javascript
import paystack from '@enviabledev/paystack-api';
const FeeHelper = paystack.feeHelper; // Get the FeeHelper class
// Use default Paystack fees
const feeCalculator = new FeeHelper();
// The amount you want to receive in kobo
const desiredAmountKobo = 10000; // ₦100.00
// The amount you need to charge the customer
const amountToCharge = feeCalculator.addFeesTo(desiredAmountKobo);
console.log(amountToCharge); // e.g., 10152 (₦101.52)
`
The library throws custom errors to help you handle different failure scenarios gracefully:
- PaystackAPIError: Thrown for errors from the Paystack API (e.g., invalid input, authentication failure). Contains statusCode and responseData.
- NetworkError: Thrown for network-related issues (e.g., timeouts, no connection).
- PaystackError: A base class for all library errors.
`javascript
import paystack from '@enviabledev/paystack-api';
const { PaystackAPIError, NetworkError } = paystack.errors;
const paystackClient = paystack('YOUR_SECRET_KEY');
async function getCustomer() {
try {
const customer = await paystackClient.customer.get('non_existent_id');
} catch (error) {
if (error instanceof PaystackAPIError) {
console.error(API Error: ${error.message});Status Code: ${error.statusCode}
console.error();Network Error: ${error.message}
if (error.statusCode === 404) {
console.log("This customer could not be found.");
}
} else if (error instanceof NetworkError) {
console.error();An unexpected error occurred:
// You could implement retry logic here
} else {
console.error(, error);
}
}
}
getCustomer();
``
This is a note to all team members, update the readme file when you make any changes to an endpoint or add a new endpoint
MIT