Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@paystack/inline-js

Package Overview
Dependencies
Maintainers
0
Versions
143
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@paystack/inline-js

Client-side library to load the Paystack checkout form

  • 2.20.0-dev.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.4K
decreased by-10.12%
Maintainers
0
Weekly downloads
 
Created
Source

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="customer@email.com"
    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

NameTypeDescription
data-button-textStringThis overrides the default button action text. Default is "Pay {Amount}".
data-button-variantnormal or lightYou can either render the normal green button or a white button. Default is normal
data-button-wordmark-variantnormal or lightYou 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: 'demo@paystack.com',
  amount: 10000,
  onSuccess
});

The PaystackPop Object

Properties

NameDescriptionResponse Type
idAutogenerated id for the Popup instanceString
backgroundDivA placeholder div that shows a loading indicator when the main checkout iFrame is loadingdomElement
checkoutIframeThe iframe where the payment happensdomElement
preCheckoutModalA div for an wallet payments i.e Apple pay pre checkout experiencedomElement | null
paymentRequestContainerThe div container for wallet payment buttons i.e Apple PaydomElement | 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

OptionRequiredTypeDescription
keyTrueStringYour Paystack public key. You can find this on your dashboard in Settings > API Keys & Webhooks
amountTrueNumberThe amount of the transaction in kobo
currencyFalseStringThe currency of the transaction. Available options in PaystackPop.CURRENCIES object
emailTrueStringThe email address of the customer
firstNameFalseStringThe first name of the customer
lastNameFalseStringThe last name of the customer
phoneFalseStringThe phone number of the customer
customerCodeFalseStringA valid Paystack customer code. If provided, this overrides all the customer information above
channelsFalseArrayAn array of payment channels to use. By default, all options available in in PaystackPop.CHANNELS are used
paymentRequestFalseStringA valid Paystack payment request id
paymentPageFalseStringA valid Paystack payment page id
metadataFalseObjectA 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
referenceFalseStringUnique case sensitive transaction reference. Only -,., = and alphanumeric characters allowed.

Configuration Options for Callbacks

Event NameDescriptionResponse Properties
onErrorCalled when the transaction was not successfully loaded{ message: error message from API }
onCancelCalled when the customer cancels the transaction
onLoadCalled when the transaction is successful loaded and the customer can see the checkout form{ id: transaction id from API, customer: customer object from API, accessCode: transaction access code }
onSuccessCalled when the customer successfully completes a transaction{ id: transaction id from API, reference: transaction reference, message: message from API }

Configuration Options for Split Payments

OptionRequiredTypeDescription
subaccountCodeFalseStringA valid Paystack subaccount code e.g. ACCT_8f4s1eq7ml6rlzj
split_codeFalseStringA valid Paystack split code e.g. SPL_qQsdYLXddd
bearerFalseNumberWho bears Paystack charges? account or subaccount (defaults to account).
transactionChargeFalseStringA 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

OptionRequiredTypeDescription
planCodeFalseStringA valid Paystack plan code e.g. PLN_cujsmvoyq2209ws
subscriptionCountFalseNumberThe number of subscriptions to create for this plan

Configuration Options for Creating a New Subscription

OptionRequiredTypeDescription
planIntervalFalseStringInterval for the plan. Valid intervals are hourly, daily, weekly, monthly, annually
subscriptionLimitFalseNumberThe number of times to charge for this subscription
subscriptionStartDateFalseStringThe 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: 'demo@paystack.com',
  amount: 10000,
  metadata: {
    custom_fields: [{
      display_name: 'Cart ID',
      variable_name: 'cart_id',
      value: '8393',
    }],
  },
};

PaystackPop.resumeTransaction({options})

This method resumes a transaction using the access code created on your server with the Paystack API.

Configuration Options

OptionRequiredTypeDescription
accessCodeTrueStringAccess code created on the API via the transaction/initialize endpoint

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

OptionRequiredTypeDescription
id or transactionObjectTrueString or PopupTransactionID 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: 'demo@paystack.com',
  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: 'testuser@paystack.com',
    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: "testuser@paystack.com",
  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

OptionRequiredTypeDescription
containerTrueStringID of div to mount the payment request button
loadPaystackCheckoutButtonFalseStringID of button to open checkout form
stylesFalseObject{
    theme: 'dark' or 'light',
    applePay: {
        width: '100%',
        height: '50px'
        borderRadius: '3px',
        type: 'plain',
        locale: 'en'
    }
}

Configuration Options for Callbacks

Event nameDescriptionResponse properties
onElementsMountCalled 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: 'testuser@paystack.com',
      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: 'demo@paystack.com',
  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

NameDescriptionResponse Type
statusStatus of the transactionString
null - fetching transaction
error - transaction error
abandoned - user has closed the page
auth - external authentication in progress
failed - payment failed
success - payment was completed
pending - payment was completed; pending confirmation
idTransaction id, if loadedString
errorsList of transaction errors, if anyArray
responseAPI response from last charge attemptObject
checkoutUrlCheckout url if transaction is loadedString

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.

Keywords

FAQs

Package last updated on 10 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc