Sign in

Developer Tools

InlineJS

View as Markdown

In a nutshell

Paystack's browser JavaScript library for accepting payments in web apps.

Copy linkIntroduction

InlineJS is Paystack’s Javascript library that offers a simple, secure, and convenient payment flow for web applications. It provides methods for initiating different types of payments e.g one time, recurring, split etc. and handle payment state, all with a few lines of code.

For a step-by-step guide to opening Paystack Popup with InlineJS, see Popup.

Copy linkBrowser support

Paystack InlineJS is designed to support all recent versions of major browsers. The library is compiled to ES5 and polyfilled to ensure it can work on as many devices as possible.

We don't support outdated browsers like IE9 nor browsers that disable the use of Javascript, like Opera mini.

  • We require TLS 1.2 to be supported by the browser
  • We support Chrome and Safari on all platforms
  • We support Firefox on desktop platforms
  • We support the Android native browser on Android 4.4 and later

Opera Mini support

We don't support Opera Mini because Javascript is disabled in it. However, we support the Opera browser, except in super saver mode where JavaScript is disabled as well.

Copy linkInstallation

Paystack InlineJS can be included in your app via CDN, NPM or Yarn:

<script src="https://js.paystack.co/v2/inline.js"></script>
npm i @paystack/inline-js
yarn add @paystack/inline-js

If you used NPM or Yarn, ensure you import the library as shown below:

const popup = new PaystackPop();
import Paystack from '@paystack/inline-js';

const popup = new Paystack()

Copy linkPaystack object

The Paystack object gives access to the methods and interfaces available in InlineJS. It exposes methods, alongside configuration options that can help you accept payment seamlessly in your web app. The methods exposed by the Paystack object include:

  1. checkout(options): This is an asynchronous method used to create a transaction.
  2. newTransaction(options): This is a synchronous method used to create a transaction.
  3. resumeTransaction(accessCode): With this method, you can initiate a transaction from your backend using the initialize endpoint, then complete the transaction in the frontend without redirecting.
  4. cancelTransaction(id): Sometimes, it might take a while to load a transaction. In such a situation, this method can be used to cancel the transaction.
  5. preloadTransaction(options): This method is used to load a transaction in the background such that when the user is about to checkout, the Popup loads instantly.
  6. paymentRequest(options): This is best suited for handling a custom user experience when your users can make a payment from their wallet (for example Apple Pay or Google Pay)

Wallet support

paymentRequest() supports Apple Pay, and Google Pay for businesses in South Africa. Both wallets are also available in the card section of Checkout through checkout(), with no extra work on your part.

Copy linkCallbacks

The Paystack object also exposes callbacks that can be used to monitor certain states during the lifecycle of a transaction.

Copy linkonLoad

This is called when the transaction is successfully loaded and the customer can see the Popup. It returns an object with the following parameters:

OptionTypeDescription
idStringThis is the transaction id
accessCodeStringThis is a unique payment code used for creating the payment link and loading the Popup
customerObjectThe details of the customer making the payment
onLoad: (response) => {
  // Transaction has loaded
  // You can parse the transaction object if you need to.
}

Copy linkonSuccess

This is called when the customer successfully completes a transaction. It returns an instance of a transaction object:

OptionTypeDescription
referenceStringThis is the unique payment reference that can be used for reconciliation
transStringThis is the transaction id (for backward compatibility)
statusStringThe final state of the transaction
messageStringComplimentary note of the transaction status
transactionStringThis is the transaction id
trxrefStringThis is the unique payment reference that can be used for reconciliation (for backward compatibility)
onSuccess: (transaction) => {
  // Post payment flow can go here
}

Copy linkonElementsMount

This is called once mounting has finished for every wallet. It returns an object reporting each wallet, { applePay: Boolean, googlePay: Boolean }, or null when mounting failed. A wallet reports false when the customer's device or browser can't pay with it.

onElementsMount: (elements) => { // { applePay: Boolean, googlePay: Boolean } or null
  if (elements) {
    console.log("Successfully mounted elements: ", JSON.stringify(elements));
  } else {
    console.log('Could not load elements');
  }
}

Copy linkonCancel

This is called when the transaction is cancelled. It returns no response.

onCancel: () => {
  console.log("User cancelled")
}

Copy linkonError

This is called when there is an issue loading the transaction.

onError: (error) => {
  console.log("Error: ", error.message);
}

Copy linkTransaction request

With Paystack, a transaction can be initiated for different scenarios such as:

  • One-time payment
  • Split payment
  • Multi-split payment
  • Subscriptions

InlineJS provide parameters and methods to to create the different types of transaction. The table below shows the general options that be used when creating a transaction:

OptionTypeRequiredDescription
keyStringTrueYour public key, from Developers → API configuration on your Paystack Dashboard
amountNumberTrueThe amount of the transaction in the lowest denomination of your currency
emailStringTrueThe customer's email address
currencyStringFalseThe currency of the transaction, such as ZAR
firstNameStringFalseThe customer's first name
lastNameStringFalseThe customer's last name
phoneStringFalseThe customer's phone number
customerCodeStringFalseA valid Paystack customer code. If provided, this overrides all the customer information above
channelsArrayFalseAn array of payment channels to use. Available channels are ['card', 'bank', 'ussd', 'qr', 'eft', 'mobile_money', 'bank_transfer', 'apple_pay', 'google_pay']. google_pay is for businesses in South Africa and must be passed alongside card
metadataObjectFalseA valid object of extra information that you want to be saved to the transaction.
referenceStringFalseUnique case sensitive transaction reference. Only -, ., = and alphanumeric characters allowed.

Copy linkOne-time transaction

The most basic way to use InlineJS is to accept payment for a one-off transaction. Generally, the payment is non-recurring and requires no special configuration. We provide two methods to accept one-time payments:

  1. newTransaction(options)
  2. checkout(options)

Copy linknewTransaction(options)

This is a synchronous method used to create a transaction. It’s best suited for cases where using an asynchronous flow isn’t necessary. It takes all the general transaction request options and can be used as shown below:

const popup = new Paystack()

popup.newTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 23400,
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})

Copy linkcheckout(options)

Similar to its counterpart but for an asynchronous flow. It takes all the general transaction request options and can be used as shown below:

const popup = new Paystack()

popup.checkout({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 23400,
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})

Copy linkPayment request

Payment requests are used for handling wallet payments such as Apple Pay and Google Pay. It's used to create a custom experience by making the wallet option more prominent on your website. For example, you can have the wallet buttons and another button to load the checkout.

Both wallets mount into the same container, and each one is offered only where a charge could succeed. Use the channels option to control which wallets a transaction offers. Google Pay is available to businesses in South Africa. It needs google_pay passed alongside card, and your Google Pay merchant details saved on the Dashboard. See Google Pay for the full setup.

Copy linkpaymentRequest(options)

The paymentRequest method the following options in addition to the general option:

OptionTypeRequiredDescription
containerStringTrueID of div to mount the payment request button
loadPaystackCheckoutButtonStringFalseID of button to open checkout form
stylesObjectFalseCSS style for the wallet button

The styles object takes the following options:

OptionTypeRequiredDescription
themeStringFalseOption to customize the button background and text color. Available options are dark | light
applePayObjectFalseStyles for the Apple Pay button
googlePayObjectFalseStyles for the Google Pay button. South Africa only

The applePay object takes the following options:

OptionTypeRequiredDescription
widthStringFalseSpecify the width of the button
heightStringFalseSpecify the height of the button
borderRadiusStringFalseSpecify the radius of the button edges
typeStringFalseThis determines the text that shows on the button
localeStringFalseSet the language of the button

The googlePay object takes the following options. Google Pay is available to businesses in South Africa.

OptionTypeRequiredDescription
widthStringFalseSpecify the width of the button
heightStringFalseSpecify the height of the button
borderRadiusString | NumberFalseSpecify the radius of the button edges. Takes the same shape as applePay.borderRadius, so '3px' and 3 both work. Defaults to '3px'
buttonTypeStringFalseThis determines the text that shows on the button. Defaults to pay
buttonColorStringFalseSet the button color independently of theme, which it otherwise follows
buttonSizeModeStringFalseHow the button fills the space it's given. Defaults to fill

Google Pay button styling

Google requires its own SDK to draw the Google Pay button, so googlePay isn't freeform CSS the way applePay is. Apart from width, height and borderRadius, every key is passed through to Google's createButton, so anything it accepts works here. That includes Google's own buttonRadius, which takes a bare number and applies when you don't pass borderRadius.

<!-- Payment request buttons, styles and event listeners will be injected to this div -->
<div id="payment-request-buttons"></div>
<button id="pay-button">More payment options</button>
const popup = new Paystack()

const onElementsMount = (elements) => {
  if (elements && (elements.applePay || elements.googlePay)) {
    document.querySelector("#pay-button").innerText = "More Payment Options";
  }
}

try {
  await popup.paymentRequest({
    key: 'pk_domain_xxxxxx',
    email: '[email protected]',
    amount: 10000,
    currency: 'ZAR',
    channels: ['card', 'apple_pay', 'google_pay'],
    container: 'payment-request-buttons',
    loadPaystackCheckoutButton: 'pay-button',
    styles: {
      theme: 'dark',
      orientation: 'horizontal',
      applePay: {
        width: '100%',
        height: '50px',
        borderRadius: '3px',
        type: 'plain',
        locale: 'en'
      },
      googlePay: {
        width: '100%',
        height: '50px',
        borderRadius: '3px',
        buttonType: 'plain',
        buttonColor: 'black',
        buttonSizeMode: 'fill'
      }
    },
    onElementsMount,
  });
} catch (error) {
  console.log("Error: ", error.message);
}

Copy linkResume transaction

Resuming a transaction lets you initiate it on your server and complete it in the browser. This flow provides both the security of server initialization and the convenience of the user experience in the browser. To get started, make a POST request from your backend to the Initialize Transaction endpoint:

POSTapi.paystack.co/transaction/initialize

curl https://api.paystack.co/transaction/initialize \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "amount": 500000
  }' \
  -X POST
const https = require("https");

const params = JSON.stringify({
  "email": "[email protected]",
  "amount": 500000
});

const options = {
  hostname: "api.paystack.co",
  port: 443,
  path: "/transaction/initialize",
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
};

const req = https.request(options, (res) => {
  let data = "";
  res.on("data", (chunk) => {
    data += chunk;
  });
  res.on("end", () => {
    console.log(res.statusCode, JSON.parse(data));
  });
});

req.on("error", (error) => {
  console.error(error);
});

req.write(params);
req.end();
<?php
$fields = [
  "email" => "[email protected]",
  "amount" => 500000,
];

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/transaction/initialize",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($fields),
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . getenv("PAYSTACK_SECRET_KEY"),
    "Content-Type: application/json",
    "Cache-Control: no-cache",
  ),
));
$response = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . " " . $response;
?>
{
  "status": true,
  "message": "Authorization URL created",
  "data": {
    "authorization_url": "https://checkout.paystack.com/nkdks46nymizns7",
    "access_code": "nkdks46nymizns7",
    "reference": "nms6uvr1pl"
  }
}

In the data object of the response returned, you need to save the access_code and send it to your frontend.

Secret key safeguarding

Don't make an API request to the Initialize Transaction endpoint directly on your mobile app because it requires your secret key. Your secret key should only be used on your server where stronger security measures can be put in place.

Copy linkresumeTransaction(accessCode)

In your frontend, you can use this access_code to complete the payment without leaving your site.

OptionTypeRequiredDescription
accessCodeStringTrueAccess code returned from the transaction initialization
const popup = new Paystack()

popup.resumeTransaction(access_code)

The resumeTransaction method triggers the checkout in the browser, allowing the user to choose their preferred payment channel to complete the transaction.

Copy linkSplit transaction

Sometimes you need to share a transaction with another business or entity. To do this you can create a subaccount and pass the subaccoutCode from the response when setting up payment:

const popup = new Paystack()

popup.newTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 45000,
  subaccountCode: 'ACCT_dskvlw3y3dsvkmt',
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})

The table below shows the parameters that can be used to config split payments:

OptionTypeRequiredDescription
subaccountCodeStringTrueA valid Paystack subaccount code for example ACCT_8f4s1eq7ml6rlzj
bearerStringFalseThis is used to specific the account that bears the Paystack charges. Values can be account or subaccount (defaults to account).
transactionChargeNumberFalseA flat fee (in the smallest denomination of your currency) the main account should take. This overrides the split percentage set when the subaccount was created.

Copy linkMulti-split transaction

Multi-split payment is used to share a single transaction with multiple partners. Based on your use-case, the split can be created ahead of time via the API or dynamically during the transaction initiation.

If you are certain of your split configuration ahead of time, you can create the split and pass the split_code when setting up the transaction:

const popup = new Paystack()

popup.newTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 98540,
  split_code: 'SPL_RYUUL4u1hP',
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})
OptionTypeRequiredDescription
split_codeStringTrueA valid Paystack split code with configuration for how payment should be split with partners

Otherwise, you might want to create the split on the fly by passing the split object in the transaction request:

const popup = new Paystack()

popup.newTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 35650,
  currency: 'ZAR',
  split: {
    name: 'Order 1042 split',
    type: 'percentage',
    currency: 'ZAR',
    bearer_type: 'account',
    subaccounts: [
      {
        subaccount: 'ACCT_dskvlw3y3dsvkmt',
        share: 30
      },
      {
        subaccount: 'ACCT_eg4sob4590pq9vb',
        share: 20
      }
    ]
  },
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})
OptionTypeRequiredDescription
nameStringTrueName of the split
typeStringTrueTakes either flat or percentage to indicate if you want a fixed or variable share
currencyStringTrueCurrency of the split, such as ZAR
subaccountsArrayTrueTakes an array of subaccount objects used to specify the account and share of each account
bearer_typeStringFalseThe bearer of the transaction fee: all, all-proportional, account or subaccount. Set it explicitly
bearer_subaccountStringFalseSubaccount code of the bearer. Required if bearer_type is subaccount

Copy linkSubscriptions

Subscription allows you process recurring billing for your customers. The first time you are setting up payments, you can add the following parameters that tells us to continuously charge the customer:

OptionTypeRequiredDescription
planIntervalStringTrueInterval for the plan. Valid intervals are daily, weekly, monthly, annually
subscriptionLimitNumberFalseThe number of times to charge for this subscription
subscriptionStartDateStringFalseThe start date for the subscription (after the first charge)
const popup = new Paystack()

popup.newTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 20000,
  planInterval: 'weekly',
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})

Subscription amount

The amount specified in the request will be used subsequently for the subscription.

Alternatively, you can create a plan via the API or dashboard and pass the planCode in the transaction request:

const popup = new Paystack()

popup.newTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 40000,
  planCode: 'PLN_l6aglbqzebn32c6',
  onSuccess: (transaction) => {
    console.log(transaction);
  },
  onLoad: (response) => {
    console.log("onLoad: ", response);
  },
  onCancel: () => {
    console.log("onCancel");
  },
  onError: (error) => {
    console.log("Error: ", error.message);
  }
})
OptionTypeRequiredDescription
planCodeStringTrueA valid Paystack plan code for example PLN_cujsmvoyq2209ws
subscriptionCountNumberFalseThe number of subscriptions to create for this plan

Plan amount precedence

While amount is a required parameter, the amount used to create the plan takes precedence when subscribing to a plan.

Copy linkPreload transaction

Preloading a transaction is similar to creating a new transaction but with a little twist. Rather than waiting till the final moment to make a transaction request, you can load the transaction ahead of time.

This method loads a transaction on the Popup without opening it. It returns a function that can be used to open the Popup at a later time. This allows the Popup to load instantly at the point the user is ready to make a payment.

Copy linkpreloadTransaction(options)

This method takes all the general options of a transaction request:

<button id="make-payment">Make Payment</button>
const popup = new Paystack()

const loadPopup = popup.preloadTransaction({
  key: 'pk_domain_xxxxxx',
  email: '[email protected]',
  amount: 10000,
  currency: 'ZAR'
});

document.querySelector("#make-payment").onclick = loadPopup;

Copy linkCancel transaction

There are situations where you want to build a logic to cancel a transaction. The cancelTransaction method allows you to cancel a transaction and hide the checkout iFrame.

Copy linkcancelTransaction(id)

OptionTypeRequiredDescription
idStringTrueTransaction ID of the payment to cancel
const popup = new Paystack()

const transaction = popup.newTransaction({
  key: 'pk_domain_xxxxx', // Replace with your public key
  email: "[email protected]",
  amount: 10000,
  onLoad: (transaction) => {
    window.clearInterval(redirectTimer);
  }
});

let timeElapsed = 0;
const timeLimit = 2;
const redirectURL = 'https://your.redirecturl.com';
const redirectTimer = setInterval(() => {
  timeElapsed += 1;
  if (timeElapsed === timeLimit) {
    popup.cancelTransaction(transaction.id);
    window.location.href = redirectURL;
  }
}, 1000);
Was this page helpful?