Built by

a11rew

Category

Payment

Version

2.0.0

Last updated

Nov 17, 2024, 15:15:00 PM2 months ago

About

Copy to clipboardmedusa-payment-paystack is a Medusa plugin that adds Paystack as a payment provider to Medusa ecommerce stores.

Setup

Prerequisites

Medusa Server

If you don’t have a Medusa server installed yet, you must follow the quickstart guide first.

Install the Paystack Plugin

In the root of your Medusa server (backend), run the following command to install the Paystack plugin:
yarn add medusa-payment-paystack

Configure the Paystack Plugin

Next, you need to enable the plugin in your Medusa server.
In Copy to clipboardmedusa-config.ts add the following to the Copy to clipboardplugins array:
module.exports = defineConfig({
projectConfig: {
databaseUrl: process.env.DATABASE_URL,
// ... other config
},
modules: [
// other modules
{
resolve: "@medusajs/medusa/payment",
options: {
providers: [
// other payment providers like stripe, paypal etc
{
resolve: "medusa-payment-paystack",
options: {
secret_key: <PAYSTACK_SECRET_KEY>,
} satisfies import("medusa-payment-paystack").PluginOptions,
},
],
},
},
],
});
The full list of configuration options you can pass to the plugin can be found in Config

Setup Webhooks

To ensure that Medusa is notified of successful payments, you need to set up webhooks in your Paystack dashboard. If you're installing this plugin for production use, this is a required step.
Go to your Paystack dashboard and navigate to the "API Keys & Webhooks" section.
Set the Webhook URL to Copy to clipboard<your-medusa-backend-url>/hooks/payment/paystack. Eg. Copy to clipboardhttps://your-medusa-backend.com/hooks/payment/paystack.

Admin Setup

This step is required for you to be able to use Paystack as a payment provider in your storefront.

Add Paystack to Regions

Refer to this documentation in the user guide to learn how to add a payment provider like Paystack to a region.

Storefront Setup

Follow Medusa's Storefront Development Checkout Flow guide using Copy to clipboardpp_paystack as the Copy to clipboardprovider_id to add Paystack to your checkout flow.

Email in Copy to clipboardinitiatePaymentSession context

Paystack requires the customer's email address to create a transaction.
You need to pass the customer's email address in the Copy to clipboardinitiatePaymentSession context to create a transaction.
If your storefront does not collect customer email addresses, you can provide a dummy email but be aware all transactions on your Paystack dashboard will be associated with that email address.
await initiatePaymentSession(cart, {
provider_id: selectedPaymentMethod,
context: {
email: cart.email,
},
});

Completing the Payment Flow

Copy to clipboardmedusa-payment-paystack returns an access code and authorization URL that you should use to complete the Paystack payment flow on the storefront.
Using the returned access code and authorization URL allows the plugin to confirm the status of the transaction on your backend, and then relay that information to Medusa.
Copy to clipboardmedusa-payment-paystack inserts the access code (Copy to clipboardpaystackTxAccessCode) and authorization URL (Copy to clipboardpaystackTxAuthorizationUrl) into the Copy to clipboardPaymentSession's data.
You can use the access code to resume the payment flow, or the authorization URL to redirect the customer to Paystack's hosted payment page.

Using Access Code

Extract the access code from the payment session's data:
const { paystackTxAccessCode } = paymentSession.data;
Provide this access code to the Copy to clipboardresumeTransaction method from Paystack's InlineJS library.
import Paystack from "@paystack/inline-js"
const PaystackPaymentButton = ({
session,
notReady,
}: {
session: HttpTypes.StorePaymentSession | undefined
notReady: boolean
}) => {
const paystackRef = useRef<Paystack | null>(null)
// If the session is not ready, we don't want to render the button
if (notReady || !session) return null
// Get the accessCode added to the session data by the Paystack plugin
const accessCode = session.data.paystackTxAccessCode
if (!accessCode) throw new Error("Transaction access code is not defined")
return (
<button
onClick={() => {
if (!paystackRef.current) {
paystackRef.current = new Paystack()
}
const paystack = paystackRef.current
paystack.resumeTransaction(accessCode, {
async onSuccess() {
// Call Medusa checkout complete here
await placeOrder()
},
onError(error: unknown) {
// Handle error
},
})
}}
>
Pay with Paystack
</button>
)
}

Using Authorization URL

As a pre-requisite, you must have configured a "Callback URL" in your Paystack dashboard. Follow this guide to set it up.
The callback URL can be a custom route on your Medusa backend, it can be a page in your storefront or a view in your mobile application. That route just needs to call the Medusa Complete Cart method.
Extract the authorization URL from the payment session's data:
const { paystackTxAuthorizationUrl } = session.data;
Redirect the customer to the authorization URL to complete the payment.
// Redirect the customer to Paystack's hosted payment page
window.open(paystackTxAuthorizationUrl, "_self");
Once the payment is successful, the customer will be redirected back to the callback URL. This page can then call the Medusa Complete Cart method to complete the checkout flow and show a success message to the customer.

Verify Payment

Call the Medusa Complete Cart method in the payment completion callback of your chosen flow as mentioned in Completing the Payment Flow above.
Copy to clipboardmedusa-payment-paystack will verify the transaction with Paystack and mark the cart as paid for in Medusa.
Even if the "Complete Cart" method is not called for any reason, with webhooks set up correctly, the transaction will still be marked as paid for in Medusa when the user pays for it.

Refund Payments

You can refund captured payments made with Paystack from the Admin dashboard.
Copy to clipboardmedusa-payment-paystack handles refunding the given amount using Paystack and marks the order in Medusa as refunded.
Partial refunds are also supported.

Configuration

NameTypeDefaultDescription
secret_keyCopy to clipboardstring-Your Paystack secret key. Should be in the format sk_test-... or sk_live-... Obtainable from the Paystack dashboard - Settings -> API Keys & Webhooks.
disable_retriesCopy to clipboardbooleanCopy to clipboardfalseDisable retries on network errors and 5xx errors on idempotent requests to Paystack. Generally, you should not disable retries, these errors are usually temporary but it can be useful for debugging.
debugCopy to clipboardbooleanCopy to clipboardfalseEnable debug mode for the plugin. If true, logs helpful debug information to the console. Logs are prefixed with "PS_P_Debug".

Examples

The Copy to clipboardexamples directory contains a simple Medusa server with the Paystack plugin installed and configured.
It also contains a storefront built with Next.js that uses the inline-js Paystack library to complete the payment flow.

Build your own plugins

Develop your own plugins with our API to speed up your processes.

Make your plugin available via npm for it to be shared in our Plugin Library with the broader Medusa community.