@paystack/inline-js
v2.22.1
Published
Client-side library to load the Paystack checkout form
Downloads
16,329
Readme
Public Docs
Documentation for Paystack Inline
Paystack Inline is a Javascript library that loads the Paystack Checkout form. This offers a simple, secure and convenient payment flow for web and mobile and can be integrated in a few lines of code. It makes it possible for you to start and end the payment flow on the same page, avoiding redirect fatigue.
Easy
The easiest way to use Paystack Inline is to add your transactions parameters to a script tag in a form. When the transaction is successful, it will call the action on the form.
<form action="/process" method="POST" >
<script
src="https://js.paystack.co/v2/inline.js"
data-key="pk_test_221221122121"
data-email="[email protected]"
data-amount="10000"
data-first-name="Opemipo"
data-last-name="Aikomo"
>
</script>
</form>
Transaction parameters should be passed as dashed data attributes. To see a list of all transaction parameters, click here. You can also pass additional attributes for styling
Configuration Options for Button Styling
| Name | Type | Description | | ---------------------------- | --------------- | -------------------------------------------------------------------------------------------- | | data-button-text | String | This overrides the default button action text. Default is "Pay {Amount}". | | data-button-variant | normal or light | You can either render the normal green button or a white button. Default is normal | | data-button-wordmark-variant | normal or light | You can also render a white version of the "Secured by Paystack" wordmark. Default is normal |
Custom
To set up your custom implementation of Popup, include the javascript directly on your site
<script src="https://js.paystack.co/v2/inline.js">
or import from npm
import PaystackPop from '@paystack/inline-js';
Quickstart
Start a new Paystack transaction and show a message when it is successful
const paystackInstance = new PaystackPop();
const onSuccess = transaction => alert(`Succesful! Ref: ${transaction.reference}`);
paystackInstance.newTransaction({
key: 'pk_test_TYooMQauvdEDq54NiTphI7jx',
email: '[email protected]',
amount: 10000,
onSuccess
});
The PaystackPop Object
Properties
| Name | Description | Response Type |
| ----------------------- | ----------------------------------------------------------------------------------------- | ------------------ |
| id | Autogenerated id for the Popup instance | String
|
| backgroundDiv | A placeholder div that shows a loading indicator when the main checkout iFrame is loading | domElement
|
| checkoutIframe | The iframe where the payment happens | domElement
|
| preCheckoutModal | A div for an wallet payments i.e Apple pay pre checkout experience | domElement
| null
|
| paymentRequestContainer | The div container for wallet payment buttons i.e Apple Pay | domElement
| null
|
Object Methods
- PaystackPop.isLoaded()
- PaystackPop.newTransaction()
- PaystackPop.resumeTransaction()
- PaystackPop.cancelTransaction()
- PaystackPop.preloadTransaction()
- PaystackPop.checkout()
- PaystackPop.paymentRequest()
PaystackPop.isLoaded()
This method checks if PaystackPop has downloaded and set up the checkout form. It returns true
or false
.
PaystackPop.newTransaction({options})
This method starts a new transaction on the checkout form.
General Configuration Options
| Option | Required | Type | Description |
| -------------- | -------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| key | True | String
| Your Paystack public key. You can find this on your dashboard in Settings > API Keys & Webhooks |
| amount | True | Number
| The amount of the transaction in kobo |
| currency | False | String
| The currency of the transaction. Available options in PaystackPop.CURRENCIES object |
| email | True | String
| The email address of the customer |
| firstName | False | String
| The first name of the customer |
| lastName | False | String
| The last name of the customer |
| phone | False | String
| The phone number of the customer |
| customerCode | False | String
| A valid Paystack customer code. If provided, this overrides all the customer information above |
| channels | False | Array
| An array of payment channels to use. By default, all options available in in PaystackPop.CHANNELS are used |
| paymentRequest | False | String
| A valid Paystack payment request id |
| paymentPage | False | String
| A valid Paystack payment page id |
| metadata | False | Object | A valid object of extra information that you want to be saved to the transaction. To show this on the dashboard, see Seeing your metadata on the dashboard |
| reference | False | String
| Unique case sensitive transaction reference. Only -,.
, = and alphanumeric characters allowed. |
Configuration Options for Callbacks
| Function Name | Description | Function Parameters | Function Parameter Definitions |
| -------------------------- | ----------------------------------------------------| ---------------------------------------------------------- | ------------------------------ |
| onError | Called when the transaction was not successfully loaded | { message: string }
| message
: Message from API |
| onCancel | Called when the customer cancels the transaction | undefined
| N/A |
| onLoad | Called when the transaction is successfully loaded and the customer can see the checkout form | { id: number, customer: Object, accessCode: string }
| id
: Transaction ID from API customer
: Customer object from API accessCode
: Transaction access code |
| onSuccess | Called when the customer successfully completes a transaction | { id: number, reference: string, message: string }
| id
: Transaction ID from API message
: Message from API reference
: Transaction reference |
Configuration Options for Split Payments
| Option | Required | Type | Description |
| ----------------------- | -------------- | ---------------| ----------------------------------------------------------------------------------- |
| subaccountCode | False | String
| A valid Paystack subaccount code e.g. ACCT_8f4s1eq7ml6rlzj
|
| split_code | False | String
| A valid Paystack split code e.g. SPL_qQsdYLXddd
|
| bearer | False | Number
| Who bears Paystack charges? account
or subaccount
(defaults to account
). |
| transactionCharge | False | String
| A flat fee (in kobo) to charge the subaccount for this transaction. This overrides the split percentage set when the subaccount was created. |
Configuration Options for Subscribing to an Existing Plan
| Option | Required | Type | Description |
| ----------------------- | -------------- | ---------------| ------------------------------------------------------- |
| planCode | False | String
| A valid Paystack plan code e.g. PLN_cujsmvoyq2209ws
|
| subscriptionCount | False | Number
| The number of subscriptions to create for this plan |
Configuration Options for Creating a New Subscription
| Option | Required | Type | Description |
| ----------------------- | -------------- | ---------------| ----------------------------------------------------------------------------------- |
| planInterval | False | String
| Interval for the plan. Valid intervals are hourly
, daily
, weekly
, monthly
, annually
|
| subscriptionLimit | False | Number
| The number of times to charge for this subscription |
| subscriptionStartDate | False | String
| The start date for the subscription (after the first charge) |
Method Response
This method returns a PopupTransaction Instance
Tip: Seeing your metadata on the dashboard
You can add any information you want to save to the transaction in your metadata. However, for the information to be visible on your Paystack dashboard, the metadata has to include the custom_fields
property, an array of objects containing display_name
, variable_name
, and value
.
const parameters = {
key: 'pk_test_TYooMQauvdEDq54NiTphI7jx',
email: '[email protected]',
amount: 10000,
metadata: {
custom_fields: [{
display_name: 'Cart ID',
variable_name: 'cart_id',
value: '8393',
}],
},
};
PaystackPop.resumeTransaction(accessCode, callbacks)
This method resumes a transaction using the access code created on your server with the Paystack API.
Access Code Parameter
| Type | Description |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| String
| Access code created on the API via the transaction/initialize endpoint |
Callback Definitions
| Function Name | Description | Callback Parameters | Callback Parameter Definitions |
| -------------------------- | ----------------------------------------------------| ---------------------------------------------------------- | ------------------------------ |
| onError | Called when the transaction was not successfully loaded | { message: string }
| message
: Message from API |
| onCancel | Called when the customer cancels the transaction | undefined
| N/A |
| onLoad | Called when the transaction is successfully loaded and the customer can see the checkout form | { id: number, customer: Object, accessCode: string }
| id
: Transaction ID from API customer
: Customer object from API accessCode
: Transaction access code |
| onSuccess | Called when the customer successfully completes a transaction | { id: number, reference: string, message: string }
| id
: Transaction ID from API message
: Message from API reference
: Transaction reference |
Method Response
This method returns a PopupTransaction Instance
Tip: Reduced Abandonment Rates
When you call PaystackPop.newTransaction()
, it first checks if there is any abandoned transaction attempted with the same parameters. If there is one, it resumes that transaction instead of creating a new one.
PaystackPop.cancelTransaction(id or transactionObject)
Use this to cancel a transaction and hide the checkout iFrame.
Configuration Options
| Option | Required | Type | Description |
| ----------------------------- | -------------- | -------------------------------| ---------------------------------------------------- |
| id or transactionObject | True | String
or PopupTransaction
| ID or transaction to cancel |
For Example
Cancel Popup and use Paystack Redirect if the transaction doesn't load after 10 seconds.
const paystackInstance = new PaystackPop();
const transaction = paystackInstance.newTransaction({
key: 'pk_test_TYooMQauvdEDq54NiTphI7jx',
email: '[email protected]',
amount: 10000,
onLoad() {
window.clearInterval(redirectTimer);
},
});
let timeElapsed = 0;
const timeLimit = 10;
const redirectURL = 'https://link/to/your/server';
const redirectTimer = setInterval(() => {
timeElapsed += 1;
if (timeElapsed === timeLimit) {
paystackPop.cancelTransaction(transaction);
window.location.href = redirectURL;
}
}, 1000);
PaystackPop.preloadTransaction({options})
This method loads a transaction on the checkout form without opening it. It returns a function that can be used to open the checkout form at a later time.
Configuration Options
All General and Custom configuration options that are accepted by PaystackPop.newTransaction
Method Response
This method returns a function to open the checkout form
For Example
Load the transaction for a checkout form and enable a button on the page to open the checkout form when a user clicks it
const paystackPop = new PaystackPop();
try {
const loadPopup = paystackPop.preloadTransaction({
key: config.publicLiveKey,
email: '[email protected]',
amount: 10000,
currency: "NGN"
});
document.querySelector("#pay-with-paystack").onclick = loadPopup;
} catch (error) {
}
PaystackPop.checkout({options})
This method loads a transaction on the checkout form but shows a pre checkout modal before loading the form if a wallet payment e.g Apple Pay is supported.
Configuration Options
All General and Custom configuration options that are accepted by PopupTransaction Instance
Method Response
This method returns a Promise which resolves to a PopupTransaction Instance
For Example
const myPopup = new PaystackPop();
const baseParameters = {
key: config.publicLiveKey,
email: "[email protected]",
channels: ["card", "apple_pay"],
};
const onSuccess = (response) => {
alert("success. transaction ref is " + response.reference);
};
const onLoad = (response) => {
console.log(`Successfully loaded transaction: ${response.id}`);
};
const onCancel = (response) => {
console.log("Transaction cancelled");
};
const onError = (error) => {
console.log(`Error occured: ${error.message}`);
};
const callbacks = {
onError,
onLoad,
onSuccess,
onCancel,
};
async function checkout(amount) {
try {
const parameters = { ...baseParameters, ...callbacks, amount };
document.querySelector("#pay-button").disabled = true;
document.querySelector("#pay-button").innerHTML = "Please wait...";
const transaction = await myPopup.checkout(parameters);
document.querySelector("#pay-button").disabled = false;
document.querySelector("#pay-button").innerHTML = "Pay";
} catch (e) {
console.log(e);
}
}
PaystackPop.paymentRequest({options})
This method mounts a wallet payment button e.g Apple pay on a provided div and also provides the option to allow a provided button open the checkout form.
General Configuration Options
All General and Custom configuration options that are accepted by PaystackPop.newTransaction
Configuration Options
| Option | Required | Type | Description |
| ----------------------------- | -------------- | --------------------| ---------------------------------------------------- |
| container | True | String
| ID of div to mount the payment request button |
| loadPaystackCheckoutButton | False | String
| ID of button to open checkout form |
| styles | False | Object
| { theme: 'dark' or 'light', applePay: { width: '100%', height: '50px' borderRadius: '3px', type: 'plain', locale: 'en' } } |
Configuration Options for Callbacks
| Event name | Description | Response properties |
| ---------------------------- | -------------------------------------------------------- | -----------------------------------|
| onElementsMount | Called when the payment request button has been mounted | { applePay: true }
or null
|
Method Response
This method returns a Promise which resolves to a PopupTransaction Instance
For Example
Mount a payment button and change the text of the button to open the checkout form if the apple pay button mounts
<div id="payment-request-buttons"></div>
<button id="pay-button">Pay</button>
const paystackPop = new PaystackPop();
const onElementsMount = (elements) => {
if (elements && elements.applePay) {
document.querySelector("#pay-button").innerText = "More Payment Options";
}
}
async function loadApplePayButton() {
try {
await paystackPop.paymentRequest({
key: config.publicLiveKey,
email: '[email protected]',
amount: 10000,
currency: "NGN",
container: 'payment-request-buttons',
loadPaystackCheckoutButton: 'pay-button',
styles: {
theme: 'dark',
applePay: {
width: '100%',
height: '50px',
borderRadius: '3px',
type: 'plain',
locale: 'en'
}
},
onElementsMount,
});
} catch(error) {
}
}
loadApplePayButton()
The PopupTransaction Object
PaystackPop.newTransaction()
and PaystackPop.resumeTransaction()
both return an instance of PopupTransaction
.
const paystackInstance = new PaystackPop();
const transaction = paystackInstance.newTransaction({
key: 'pk_test_TYooMQauvdEDq54NiTphI7jx',
email: '[email protected]',
amount: 10000,
});
typeof transaction === PopupTransaction; // true
PopupTransaction.getStatus()
This method returns all available transaction information. This is populated throughout the lifecycle of the transaction.
Method Response
| Name | Description | Response Type |
| ----------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| status | Status of the transaction | String
null
- fetching transactionerror
- transaction errorabandoned
- user has closed the pageauth
- external authentication in progressfailed
- payment failedsuccess
- payment was completedpending
- payment was completed; pending confirmation |
| id | Transaction id, if loaded | String
|
| errors | List of transaction errors, if any | Array
|
| response | API response from last charge attempt | Object
|
| checkoutUrl | Checkout url if transaction is loaded | String
| |
Browser Support
Paystack Inline is designed to support all recent versions of major browsers. The distributed file (https://js.paystack.co/v2/inline.js) is compiled to ES5 and poly-filled to ensure it can work on as many devices as possible. We do not support outdated browsers like IE9 nor browsers that disable the use of Javascript, like Opera mini*.
- We support Chrome and Safari on all platforms and Firefox on desktop platforms.
- We support the Android native browser on Android 4.4 and later.
- We require TLS 1.2 to be supported by the browser.
If you have an issue with Paystack Inline on a specific browser, kindly reach out to us so we can quickly resolve any issues.
- We don't support Opera Mini because Javascript is disabled in it. We support the Opera browser however, except in super saver mode where JS is disabled as well.