@paystack/inline-js
Advanced tools
Comparing version 2.18.1 to 2.18.2
{ | ||
"name": "@paystack/inline-js", | ||
"version": "2.18.1", | ||
"version": "2.18.2", | ||
"description": "Client-side library to load the Paystack checkout form", | ||
@@ -5,0 +5,0 @@ "main": "lib/inline.js", |
450
README.md
@@ -1,53 +0,451 @@ | ||
# Inline JS | ||
Public Docs | ||
=== | ||
# Documentation for Paystack Inline | ||
This is the client-side JS library for loading the Paystack checkout form. It makes it easy to accept payments from a web application and to create custom, secure payment experiences for merchant apps and websites. | ||
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. | ||
# Quick start | ||
# Easy | ||
### Requirements | ||
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. | ||
```html | ||
<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> | ||
``` | ||
node >= 18.0.0 | ||
npm >= 10.0.0 | ||
Transaction parameters should be passed as dashed data attributes. To see a list of all transaction parameters, [click here](#general-configuration-options). 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 | ||
```html | ||
<script src="https://js.paystack.co/v2/inline.js"> | ||
``` | ||
### Setup | ||
or import from npm | ||
Clone this repository | ||
```js | ||
import PaystackPop from '@paystack/inline-js'; | ||
``` | ||
git clone https://github.com/PaystackHQ/inline-js.git | ||
## Quickstart | ||
Install dependencies with: | ||
Start a new Paystack transaction and show a message when it is successful | ||
npm install | ||
```js | ||
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 | ||
}); | ||
``` | ||
# Local development | ||
--- | ||
To test Inline JS locally, run the command; | ||
# 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](#tip-seeing-your-metadata-on-the-dashboard) | | ||
| reference | False | `String` | Unique case sensitive transaction reference. Only -,`.`, = and alphanumeric characters allowed. | | ||
### Configuration Options for Callbacks | ||
| Event Name | Description | Response Properties | | ||
| -------------------- | ----------------------------------------------------| ---------------------------------------------------------- | | ||
| onError | Called when the transaction was not successfully loaded | `{ message: error message from API }` | | ||
| onCancel | Called when the customer cancels the transaction | | | ||
| onLoad | Called 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 }` | | ||
| onSuccess | Called when the customer successfully completes a transaction | `{ id: transaction id from API, reference: transaction reference, message: message from API }` | | ||
### 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](#the-popuptransaction-object) | ||
--- | ||
## 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`. | ||
```js | ||
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', | ||
}], | ||
}, | ||
}; | ||
``` | ||
npm run dev | ||
--- | ||
# PaystackPop.resumeTransaction({options}) | ||
This method resumes a transaction using the access code created on your server with [the Paystack API](https://developers.paystack.co/v1.0/reference#initialize-a-transaction). | ||
### Configuration Options | ||
| Option | Required | Type | Description | | ||
| ----------------------------- | -------------- | --------------------| ----------------------------------------------------------------------------- | | ||
| accessCode | True | `String` | Access code created on the API via the [transaction/initialize](https://paystack.com/docs/#initialize-a-transaction) endpoint | | ||
## Method Response | ||
This method returns a [PopupTransaction Instance](#the-popuptransaction-object) | ||
## 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. | ||
```js | ||
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); | ||
``` | ||
This spins up a `http-server` serving the `dev` folder and you can then visit the different `HTML` files in that folder to test various APIs and payment flows. | ||
--- | ||
### Testing | ||
# PaystackPop.preloadTransaction({options}) | ||
This project uses [Jest](https://jestjs.io/) for unit testing. To run all tests, use the command; | ||
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](https://www.notion.so/Documentation-for-Paystack-Inline-d6e595c0277d413db73b9a0d81a9c16c) | ||
## 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 | ||
```js | ||
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) { | ||
} | ||
``` | ||
npm test | ||
--- | ||
# 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](#the-popuptransaction-object) | ||
## Method Response | ||
This method returns a Promise which resolves to a [PopupTransaction Instance](#the-popuptransaction-object) | ||
## For Example | ||
```js | ||
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); | ||
} | ||
} | ||
``` | ||
# Deployment | ||
--- | ||
Inline JS is deployed to: | ||
# PaystackPop.paymentRequest({options}) | ||
- Staging: [https://js-studio.paystack.co/v2/inline.js](https://js-studio.paystack.co/v2/inline.js) | ||
- Production: [https://js.paystack.co/v2/inline.js](https://js.paystack.co/v2/inline.js) | ||
- npm: [@paystack/inline-js](https://www.npmjs.com/package/@paystack/inline-js) | ||
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. | ||
# Documents | ||
## General Configuration Options | ||
- [Development](./DEV_DOCS.md) | ||
- [Public](./PUBLIC_DOCS.md) | ||
All General and Custom configuration options that are accepted by [PaystackPop.newTransaction](https://www.notion.so/Documentation-for-Paystack-Inline-d6e595c0277d413db73b9a0d81a9c16c) | ||
### 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` | { <br> theme: 'dark' or 'light', <br> applePay: { <br> width: '100%', <br> height: '50px' <br> borderRadius: '3px', <br> type: 'plain', <br> locale: 'en' <br> } <br>} | | ||
### 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](#the-popuptransaction-object) | ||
## For Example | ||
Mount a payment button and change the text of the button to open the checkout form if the apple pay button mounts | ||
```html | ||
<div id="payment-request-buttons"></div> | ||
<button id="pay-button">Pay</button> | ||
``` | ||
```js | ||
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`. | ||
```js | ||
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 | ||
| Name | Description | Response Type | | ||
| ----------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| status | Status of the transaction | `String`<br>`null` - fetching transaction<br>`error` - transaction error<br>`abandoned` - user has closed the page<br>`auth` - external authentication in progress<br>`failed` - payment failed<br>`success` - payment was completed<br>`pending` - payment was completed; pending confirmation<br> | | ||
| 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](https://js.paystack.co/v2/popup.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. |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
343289
451