@enviabledev/paystack-api
v1.0.32
Published
A type-safe Paystack API library for Node.js
Maintainers
Readme
@enviabledev/paystack-api
A 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.
Table of Contents
Features
- 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
Installation
npm install @enviabledev/paystack-apiGetting Started
To get started, initialize the client with your Paystack secret key.
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');API Reference
This library provides access to all Paystack API resources through the paystackClient object.
Bulk Charge
Handles batch processing of charges.
paystackClient.bulkCharge.create(payload): Initiates a new bulk charge- Payload:
CreateBulkChargePayload- An object with a charges property, which is an array of objects containing authorization (string), amount (number), and optional reference (string)
- Payload:
paystackClient.bulkCharge.list(params): Lists bulk charge batches- Params:
ListBulkChargesParams(optional) for pagination (perPage, page) and filtering (status, from, to)
- Params:
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 batch- ID: The batch ID or code (string)
- Params:
ListBulkChargeChargesParams(optional) for pagination and filtering
paystackClient.bulkCharge.pause(batchCode): Pauses a running bulk charge batchpaystackClient.bulkCharge.resume(batchCode): Resumes a paused bulk charge batch
Charge
Handles tokenization and charging of payment instruments.
paystackClient.charge.tokenize(payload): Creates a reusable token from card details- Payload:
TokenizePayloadwith email and a card object (number, cvv, expiry_month, expiry_year)
- Payload:
paystackClient.charge.charge(payload): Initiates a new charge- Payload:
ChargePayloadwith email, amount, and payment details (e.g., authorization_code, pin, bank)
- Payload:
paystackClient.charge.submitPin(payload): Submits a PIN to continue a charge- Payload:
SubmitPinPayloadwith pin and reference
- Payload:
paystackClient.charge.submitOtp(payload): Submits an OTP to complete a charge- Payload:
SubmitOtpPayloadwith otp and reference
- Payload:
paystackClient.charge.submitPhone(payload): Submits a phone number to continue a charge- Payload:
SubmitPhonePayloadwith phone and reference
- Payload:
paystackClient.charge.submitBirthday(payload): Submits a birthday to continue a charge- Payload:
SubmitBirthdayPayloadwith birthday (YYYY-MM-DD) and reference
- Payload:
paystackClient.charge.submitAddress(payload): Submits an address to continue a charge- Payload:
SubmitAddressPayloadwith reference, address, city, state, and zip_code
- Payload:
paystackClient.charge.checkCharge(reference): Checks the status of a pending charge
Control Panel
Manages integration settings.
paystackClient.controlPanel.getSessionTimeout(): Gets the payment session timeout for your integrationpaystackClient.controlPanel.updateSessionTimeout(payload): Updates the payment session timeout- Payload:
UpdateSessionTimeoutPayloadwith timeout in seconds
- Payload:
Customer
Manages customer information.
paystackClient.customer.create(payload): Creates a new customer- Payload:
CreateCustomerPayloadcontaining email, and optional first_name, last_name, phone, metadata
- Payload:
paystackClient.customer.list(params): Lists customers- Params:
ListCustomersParams(optional) for pagination and filtering
- Params:
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 details- Payload:
UpdateCustomerPayload
- Payload:
paystackClient.customer.validate(id, payload): Validates a customer's identity- Payload:
ValidateCustomerPayload
- Payload:
paystackClient.customer.setRiskAction(payload): Whitelists or blacklists a customer- Payload:
SetRiskActionPayloadwith customer (code or email) and risk_action ('allow' or 'deny')
- Payload:
paystackClient.customer.deactivateAuthorization(payload): Deactivates a customer's authorization- Payload:
DeactivateAuthorizationPayloadwith authorization_code
- Payload:
Dedicated NUBAN
Manages dedicated virtual bank accounts.
paystackClient.nuban.create(payload): Creates a dedicated virtual account- Payload:
CreateNubanPayloadfor a new or existing customer
- Payload:
paystackClient.nuban.list(params): Lists dedicated virtual accounts- Params:
ListNubansParams(optional) for filtering
- Params:
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 transfers- Params:
RequeryNubanParamswith account_number, provider_slug, and date
- Params:
paystackClient.nuban.deactivate(id): Deactivates a dedicated virtual accountpaystackClient.nuban.removeSplit(payload): Removes a split configuration from a dedicated account- Payload:
RemoveNubanSplitPayloadwith account_number
- Payload:
paystackClient.nuban.listAvailableProviders(): Gets a list of available providers for dedicated accounts
Miscellaneous
Accesses miscellaneous data like banks and countries.
paystackClient.misc.listBanks(params): Gets a list of all supported banks- Params:
ListBanksParams(optional) for filtering by country, currency, etc.
- Params:
paystackClient.misc.listCountries(): Gets a list of all supported countriespaystackClient.misc.listStates(params): Gets a list of states for a country- Params:
ListStatesParamswith country code
- Params:
Payment Page
Manages hosted payment pages.
paystackClient.paymentPage.create(payload): Creates a new payment page- Payload:
CreatePaymentPagePayloadwith name and other optional fields
- Payload:
paystackClient.paymentPage.list(params): Lists payment pages- Params:
ListPaymentPagesParams(optional) for pagination and date range filtering
- Params:
paystackClient.paymentPage.get(id): Retrieves a payment page- ID: The page ID or slug (string)
paystackClient.paymentPage.update(id, payload): Updates a payment page- Payload:
UpdatePaymentPagePayload
- Payload:
paystackClient.paymentPage.checkSlugAvailability(slug): Checks if a URL slug is availablepaystackClient.paymentPage.addProducts(id, payload): Adds products to a payment page- ID: The page ID (number)
- Payload:
AddProductsToPaymentPagePayloadwith an array of product IDs
Payment Request
Manages professional invoices.
paystackClient.paymentRequest.create(payload): Creates a new payment request (invoice)- Payload:
CreatePaymentRequestPayloadwith customer, amount, and due_date
- Payload:
paystackClient.paymentRequest.list(params): Lists payment requests- Params:
ListPaymentRequestsParams(optional) for filtering
- Params:
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 requestpaystackClient.paymentRequest.notify(id): Sends a notification reminder for a payment requestpaystackClient.paymentRequest.getTotals(): Gets total payment request volume and paid countpaystackClient.paymentRequest.finalize(id): Finalizes a draft payment requestpaystackClient.paymentRequest.update(id, payload): Updates a payment request- Payload:
UpdatePaymentRequestPayload
- Payload:
paystackClient.paymentRequest.archive(id): Archives a payment request
Plan
Manages subscription plans.
paystackClient.plan.create(payload): Creates a new subscription plan- Payload:
CreatePlanPayloadwith name, amount, and interval
- Payload:
paystackClient.plan.list(params): Lists subscription plans- Params:
ListPlansParams(optional) for filtering
- Params:
paystackClient.plan.get(id): Retrieves a subscription plan- ID: The plan ID or code (string)
paystackClient.plan.update(id, payload): Updates a subscription plan- Payload:
UpdatePlanPayload
- Payload:
Refund
Manages refunds for transactions.
paystackClient.refund.create(payload): Initiates a refund for a transaction- Payload:
CreateRefundPayloadwith transaction reference and optional amount
- Payload:
paystackClient.refund.list(params): Lists refunds- Params:
ListRefundsParams(optional) for filtering
- Params:
paystackClient.refund.get(id): Retrieves a single refund- ID: The refund ID (number)
Settlement
Retrieves settlement information.
paystackClient.settlement.list(params): Lists settlements made to your bank accounts- Params:
ListSettlementsParams(optional) for filtering
- Params:
paystackClient.settlement.getTransactions(id, params): Gets transactions associated with a settlement- ID: The settlement ID (number)
- Params:
ListSettlementTransactionsParams(optional)
Subaccount
Manages subaccounts for split payments.
paystackClient.subaccount.create(payload): Creates a new subaccount- Payload:
CreateSubaccountPayloadwith business_name, settlement_bank, account_number, and percentage_charge
- Payload:
paystackClient.subaccount.list(params): Lists subaccounts- Params:
ListSubaccountsParams(optional)
- Params:
paystackClient.subaccount.get(id): Retrieves a subaccount- ID: The subaccount ID or code (string)
paystackClient.subaccount.update(id, payload): Updates a subaccount- Payload:
UpdateSubaccountPayload
- Payload:
Subscription
Manages customer subscriptions.
paystackClient.subscription.create(payload): Creates a new subscription- Payload:
CreateSubscriptionPayloadwith customer and plan
- Payload:
paystackClient.subscription.list(params): Lists subscriptions- Params:
ListSubscriptionsParams(optional) for filtering by customer or plan
- Params:
paystackClient.subscription.get(id): Retrieves a subscription- ID: The subscription ID or code (string)
paystackClient.subscription.enable(payload): Enables a subscription- Payload:
ToggleSubscriptionPayloadwith code and token
- Payload:
paystackClient.subscription.disable(payload): Disables a subscription- Payload:
ToggleSubscriptionPayloadwith code and token
- Payload:
paystackClient.subscription.generateManageLink(code): Generates a link to manage a subscriptionpaystackClient.subscription.sendManageEmail(code): Sends a subscription management email
Transaction
Manages financial transactions.
paystackClient.transaction.initialize(payload): Initializes a new transaction- Payload:
InitializeTransactionPayloadwith email and amount
- Payload:
paystackClient.transaction.verify(reference): Verifies the status of a transactionpaystackClient.transaction.list(params): Lists transactions- Params:
ListTransactionsParams(optional) for pagination and filtering
- Params:
paystackClient.transaction.get(id): Retrieves a transaction- ID: The transaction ID (number)
paystackClient.transaction.chargeAuthorization(payload): Charges a customer using a saved authorization- Payload:
ChargeAuthorizationPayloadwith email, amount, and authorization_code
- Payload:
paystackClient.transaction.viewTimeline(id): Gets the timeline of a transaction- ID: The transaction ID or reference (string)
paystackClient.transaction.totals(params): Gets transaction totals- Params:
ListTransactionsParams(optional) for date range filtering
- Params:
paystackClient.transaction.export(params): Exports a list of transactions- Params:
ListTransactionsParams(optional) for filtering
- Params:
Transfer
Manages money transfers to bank accounts.
paystackClient.transfer.create(payload): Initiates a new transfer- Payload:
CreateTransferPayloadwith source, amount, and recipient
- Payload:
paystackClient.transfer.list(params): Lists transfers- Params:
ListTransfersParams(optional)
- Params:
paystackClient.transfer.get(idOrCode): Retrieves a transferpaystackClient.transfer.finalize(payload): Finalizes a transfer that requires an OTP- Payload:
FinalizeTransferPayloadwith transfer_code and otp
- Payload:
paystackClient.transfer.bulk(payload): Initiates a bulk transfer- Payload:
BulkTransferPayload
- Payload:
paystackClient.transfer.verify(reference): Verifies the status of a transfer
Transfer Control
Manages transfer settings and balance.
paystackClient.transferControl.checkBalance(): Checks the available balance on your integrationpaystackClient.transferControl.getBalanceLedger(): Gets the balance ledger for your integrationpaystackClient.transferControl.resendOtp(payload): Resends an OTP for a transfer- Payload:
ResendOtpPayloadwith transfer_code and reason
- Payload:
paystackClient.transferControl.disableOtp(): Disables the OTP requirement for transferspaystackClient.transferControl.finalizeDisableOtp(payload): Finalizes the process of disabling OTP- Payload:
FinalizeDisableOtpPayloadwith otp
- Payload:
paystackClient.transferControl.enableOtp(): Enables the OTP requirement for transfers
Transfer Recipient
Manages transfer recipients.
paystackClient.transferRecipient.create(payload): Creates a new transfer recipient- Payload:
CreateTransferRecipientPayloadwith type and name
- Payload:
paystackClient.transferRecipient.createBulk(payload): Creates multiple transfer recipients in bulk- Payload:
CreateBulkTransferRecipientsPayload
- Payload:
paystackClient.transferRecipient.list(params): Lists transfer recipients- Params:
ListTransferRecipientsParams(optional)
- Params:
paystackClient.transferRecipient.get(idOrCode): Retrieves a transfer recipientpaystackClient.transferRecipient.update(idOrCode, payload): Updates a transfer recipient- Payload:
UpdateTransferRecipientPayload
- Payload:
paystackClient.transferRecipient.remove(idOrCode): Deletes a transfer recipient
Verification
Verifies customer and payment details.
paystackClient.verification.resolveAccount(payload): Resolves a bank account to get the account holder's name- Payload:
ResolveAccountPayloadwith account_number and bank_code
- Payload:
paystackClient.verification.validateAccount(payload): Validates a bank account- Payload:
ValidateAccountPayload
- 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)
Helpers
Handling Webhooks
The library provides an Express middleware to securely handle incoming webhook events. It verifies the Paystack signature and emits an event.
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'));Fee Calculator
The FeeHelper class calculates the total amount to charge a customer to cover Paystack's processing fees.
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)Error Handling
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.
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}`);
console.error(`Status Code: ${error.statusCode}`);
if (error.statusCode === 404) {
console.log("This customer could not be found.");
}
} else if (error instanceof NetworkError) {
console.error(`Network Error: ${error.message}`);
// You could implement retry logic here
} else {
console.error(`An unexpected error occurred:`, error);
}
}
}
getCustomer();Contributing
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
License
MIT
