Skip to main content
Before following these steps, please configure your payment methods.
Use this guide to integrate Pesaswap SDK to your React app. You can use the demo app as a reference with your Pesaswap credentials to test the setup.

1. Setup the Server

1.1 Follow the Server Setup Section

Follow the Server Setup section for backend configuration.

2. Build Checkout Page on the Client

2.1 Install the hyper-js and react-hyper-js Libraries

Install the packages and import them into your code:
npm install @Pesaswap-/hyper-js
npm install @Pesaswap-/react-hyper-js

2.2 Add Hyper to Your React App

Use hyper-js to ensure that you stay PCI compliant by sending payment details directly to the Pesaswap server:
import React, { useState, useEffect } from "react";
import { loadHyper } from "@Pesaswap-/hyper-js";
import { HyperElements } from "@Pesaswap-/react-hyper-js";

2.3 Load hyper-js

Call loadHyper with your publishable API keys to configure the library. To get a publishable key, please find it here:
const hyperPromise = loadHyper("YOUR_PUBLISHABLE_KEY", {
  customBackendUrl: "YOUR_BACKEND_URL",
  // You can configure this as an endpoint for all the API calls such as session, payments, confirm call.
});

2.4 Fetch the Payment and Initialize HyperElements

Immediately make a request to the endpoint on your server to create a new Payment as soon as your checkout page loads. The clientSecret returned by your endpoint is used to complete the payment:
useEffect(() => {
  // Create PaymentIntent as soon as the page loads
  fetch("/create-payment", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ items: [{ id: "xl-tshirt" }], country: "US" }),
  })
    .then((res) => res.json())
    .then((data) => setClientSecret(data.clientSecret));
}, []);

2.5 Initialize HyperElements

Pass the promise from loadHyper to the HyperElements component. This allows the child components to access the Hyper service via the HyperElements parent component. Additionally, pass the client secret as options to the HyperElements component:
<div className="App">
  {clientSecret && (
    <HyperElements options={options} hyper={hyperPromise}>
      <CheckoutForm />
    </HyperElements>
  )}
</div>

2.6 Setup the State (Optional)

Initialize a state to keep track of payment, display errors, and control the user interface:
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);

2.7 Store a Reference to Hyper

Access the hyper-js library in your CheckoutForm component by using the useHyper() and useWidgets() hooks. If you need to access Widgets via a class component, use the WidgetsConsumer instead. You can find the API for these methods in the documentation:
const hyper = useHyper();
const widgets = useWidgets();

3. Complete the Checkout on the Client

// Key Features of Pesaswap's Express Checkout
// Fast Performance: One-click payment at checkout enables a smooth and frictionless payment experience for customers.
// Multiple Payment Options: Supports Apple Pay, PayPal, Klarna, and Google Pay, giving customers a variety of payment choices on top of the speed in checkout.
// Easy Integration: Our SDK can be easily integrated with web applications.

// Benefits of Pesaswap's Express Checkout Feature
// Better User Experience: One-click payment makes shopping easier, leading to more sales and fewer abandoned carts.
// Time Savings: Speeds up the checkout process, saving time for both customers and merchants.
// Great for Mobile: Optimized for mobile shopping with Apple Pay, PayPal, and Google Pay integration for quick purchases on smartphones.
// Collect billing and shipping details directly from Apple Pay, Klarna, Google Pay, and PayPal.

// 3.1 Add the ExpressCheckout
// The Express Checkout Element gives you a single integration for accepting payments through one-click payment buttons. 
// Supported payment methods include Apple Pay, Google Pay, and PayPal.
// Add the ExpressCheckout to your checkout. This embeds an iframe that displays configured payment method types 
// supported by the browser available for the Payment, allowing your customer to select a payment method.

// Define paymentElementOptions:
var expressCheckoutOptions = {
  wallets: {
    walletReturnUrl: "https://example.com/complete",
    // Mandatory parameter for Wallet Flows such as Google Pay, PayPal, and Apple Pay
  },
};

// Add Express Checkout Element
<ExpressCheckoutElement id="express-checkout" options={expressCheckoutOptions} />

3.2 Display Payment Status Message

When Pesaswap redirects the customer to the return_url, the payment_client_secret query parameter is appended by hyper-js. Use this to retrieve the Payment to determine what to show to your customer:
// Look for a parameter called `payment_intent_client_secret` in the URL which gives a payment ID, 
// which is then used to retrieve the status of the payment

const paymentID = new URLSearchParams(window.location.search).get(
  "payment_intent_client_secret"
);

if (!paymentID) {
  return;
}

hyper.retrievePaymentIntent(paymentID).then(({ paymentIntent }) => {
  switch (paymentIntent.status) {
    case "succeeded":
      setMessage("Payment succeeded!");
      break;
    case "processing":
      setMessage("Your payment is processing.");
      break;
    case "requires_payment_method":
      setMessage("Your payment was not successful, please try again.");
      break;
    default:
      setMessage("Something went wrong.");
      break;
  }
});
Please retrieve the payment status from the Pesaswap backend to get the terminal status of the payment. Do not rely solely on the status returned by the SDK, as it may not always reflect the final state of the transaction.

4. Elements Events

Some events are emitted by payment elements. Listening to those events is the only way to communicate with these elements. All events have a payload object with the type of the Element that emitted the event as an elementType property. The following events are emitted by payment elements:
  • change
  • ready
  • focus
  • blur

4.1 Calling Elements Events

First create an instance of widgets using the getElement function. It will return null if no matching type is found:
// Create instance of widgets
var paymentElement = widgets.getElement("payment");

// Handle event
if (paymentElement) {
  // In place of "EVENT" use "change", "ready", "focus", etc.
  paymentElement.on("EVENT", callbackFn);
}

4.2 “change” Event

The “change” event will be triggered when the value changes in the Payment element:
paymentElement.on("change", function (event) {
  // YOUR CODE HERE
});
The callback function will be fired when the event is triggered. When called, it will be passed an event object with the following properties:
{
  elementType: 'payment',   // The type of element that emitted this event.
  complete: false,          // If all required fields are complete
  empty: false,             // If the value is empty.
  value: { type: "card" },  // Current selected payment method like "card", "klarna", etc.
}

4.3 “ready” Event

The “ready” event will be triggered when the payment element is fully rendered and can accept “focus” event calls. The callback for the ready event will be triggered with the following event object:
{
  ready: boolean,   // true when payment element is fully rendered
}

4.4 “focus” and “blur” Events

Focus and blur events are triggered when the respective event is triggered in the payment element. The callback for these events will be triggered with the following event object:
// Event object for focus event
{
  focus: boolean,   // true when focused on payment element
}

// Event object for blur event
{
  blur: boolean,
}

5. Additional Callback Handling for Wallet Payment Process

This document outlines the details and functionality of optional callbacks onPaymentButtonClick and onPaymentComplete that can be provided by merchants during the payment process. These callbacks allow merchants to hook into the payment flow at key stages and handle specific actions or events before continuing the normal flow.
  • onPaymentButtonClick:** This callback is triggered immediately after the user clicks any wallet button.
  • onPaymentComplete:** This callback is triggered after the payment is completed, just before the SDK redirects to the walletReturnUrl provided. It allows the merchant to handle actions post-payment. If not provided, the SDK’s default flow will proceed.
Redirection Handling : The onPaymentComplete callback should handle redirection or any steps needed after payment, as the SDK no longer does this automatically. You must ensure to implement the necessary redirection logic.
Fallback : If no callbacks are provided by the merchant, the SDK will continue with its default behavior, including automatic redirection after payment completion.
The task within onPaymentButtonClick must be completed within 1 second. If an asynchronous callback is used, it must resolve within this time to avoid Apple Pay payment failures.

Example Usage for React Integration

<PaymentElement
  id="payment-element"
  options={options}
  onPaymentButtonClick={() => {
    console.log("This is a SYNC CLICK");
    // Add any custom logic for when the payment button is clicked, such as logging or tracking
  }}
  onPaymentComplete={() => {
    console.log("OnPaymentComplete");
    // Add any custom post-payment logic here, such as redirection or displaying a success message
  }}
/>

Congratulations!

Now that you have integrated the Pesaswap SDK on your app, you can customize the payment elements to blend with the rest of your app.