📃
Developer Docs
  • Overview
  • Integration Options
  • Webhooks
    • Build a webhook endpoint
    • Check signature
  • Getting Started
    • 1. Creating User Accounts
    • 2. User Account Types & Permissions
    • 3. Generate Access Tokens
    • 4. Choose Integration Options
    • 5. Securing Embedded UIs
      • 5a. Securing Embedded UIs Using HMAC (deprecated)
    • 6. Loading the frontend library
      • 6a. Preloading PayEngine Web-Component in SPA
    • 7. Custom styling the Web-Components
    • 8. Handling Callbacks from Web-Components
    • 9. Available Web-Components
    • 10. Available Webhooks
  • Merchant Onboarding
    • Overview
    • Integration Options
    • Onboarding/Payments Application Workflow
    • Embedded Onboarding UI
    • Merchant onboarding APIs
    • Partner's Onboarding UI
    • Merchant Lifecycle
    • Onboarding to Partner Relationships
  • Processing Payments
    • Introduction
      • Transaction Flow and Status
    • SecureFields JS
      • SecureFields Bank Account
      • Using tokens
    • Credit Card Form
    • Connect with Plaid
    • Connect Mailgun
    • 3D Secure
    • Payments API
    • Searching Transactions
    • Registering a cloud connected device
    • Apple Pay
      • Apple Pay in your native app
    • Google Payâ„¢
    • Level 2 and Level 3 Data
    • Fraud Prevention
    • Reporting
    • PCI Compliance
    • Address Verification Service (AVS) Check
    • Hosted Payments
    • Tap to Pay
  • Card Account Updater
  • ORCHESTRATION SYSTEM
    • Orchestration Overview
    • Onboarding Orchestration
    • Transactions Orchestration
    • Omnicommerce Orchestration
    • Merchant Servicing
    • Universal Reporting
  • TOKENIZATION
    • Automatic Network Tokenization
    • Token Migration Process
  • DISPUTE MANAGEMENT
    • Retrieval Requests & Chargebacks
  • Certification
    • Partner Certification
  • Data Sharing
    • Secure Data Sharing with PayEngine
  • eCommerce Integration
    • PayEngine Payment Gateway for WooCommerce
Powered by GitBook
On this page
  • Obtaining a new Merchant Session
  • Load PayEngine Library
  • Logout - Revoke Access Token
  1. Getting Started

5. Securing Embedded UIs

PayEngine offers a comprehensive framework designed to ensure the security of its web components. This framework encompasses a wide range of security measures. By addressing security at multiple levels, PayEngine aims to protect sensitive data and maintain the integrity of its web applications

PayEngine uses MerchantSession to enable embedded web components to access merchant data and allow merchants to interact with that.

Obtaining a new Merchant Session

This example illustrates a server-side implementation for obtaining a secure session using the partner's private key.

It's crucial to highlight that the private key should never be exposed to the client-side and must remain securely stored for server-to-server communications only. By implementing this approach, partners ensure that the access token acquisition process is both secure and compliant with best practices for protecting sensitive credentials. This setup helps maintain the integrity of interactions between the partner's web application, through the partner backend application to PayEngine's services.

const axios = require('axios');
const express = require('express');
const app = express();

// Replace with your actual API endpoint and any necessary authentication
const API_ENDPOINT = 'https://<PAYENGINE_HOST>/api/merchant'; // Example endpoint
const API_KEY = 'your_api_key'; // PayEngine API Key
const MERCHANT_ID = 'your_merchant_id'; // PayEngine assigned Merchant ID

app.post('/accessToken', async (req, res) => {
  try {
    const data = {
      expires_in: 900,
      // Setting scope to 'readonly' restricts actions like hiding the Refund button in the transaction widget
      scope: 'readonly' // Optional.
    };
    
    const apiURL = `${API_ENDPOINT}/${MERCHANT_ID}/sessions`;
    
    const response = await axios.post(apiURL, data, {
      headers: {
        'Content-Type': 'application/json', 
        'Authorization': `Basic ${API_KEY}`, 
      },
    });

    // ... code to store session in the backend
    
    res.json({
      access_token: response.data.access_token,
      expires_in: response.data.expires_in
    });
  } catch (error) {
    // ERROR HANDLING AND RETRYING
  }
});

Note: Setting the scope parameter to 'readonly' restricts certain actions in the embedded widgets, such as hiding the Refund button in the Transactions widget, disabling the Export button etc.

Load PayEngine Library

To access the latest PayEngine tokenization features and APIs, please update to PayEngine@1.0.6 or higher. This update provides essential improvements and ensures compatibility with our latest security standards.

When PayEngine library needs the access token, it will use the fetchAccessToken to ask the host application to make a server side call and obtain the access token. It is important to note that PayEngine will call fetchAccessToken whenever access token is needed or when it needs to be refreshed.

This example demonstrates how to implement client-side code using PayEngine's public key and fetchAccessToken callback, ensuring that sensitive private key data remains secure and never exposed to the client side.

import { useEffect } from "react";
import { loadPayengine } from "payengine";


const MyComponent = () => {

  const fetchAccessToken = async () => {
    const response = await fetch('/accessToken', { method: "POST" });
    if (!response.ok) {
      //Handle error as per your app's design
      return undefined;
    } else {
      const jsonResponse = await response.json();
      return jsonResponse;
    }
  }
    
  useEffect(() => {
      // Load Payengine on first render only
      loadPayengine({
        publicKey: config.PAYENGINE_PUBLIC_KEY, 
        fetchAccessToken: fetchAccessToken 
      }).then((pe) => {
          console.log(pe)
      });  
  }, []);
  
  return (
    <>
      <pay-engine 
        type="boarding" 
        merchant-id="<payengine_merchant_id>" 
      </pay-engine>        
    </>
  )   
}

Specify your onload callback function. This function will get called when all the dependencies have loaded.

<script type="text/javascript">
  var onloadCallback = function() {
    alert("PayEngine is ready!");
  };
</script>

Insert the JavaScript resource, setting the onload parameter to the name of your onload callback function

<script src="<PAYENGINE_SCRIPT_URL>?key=<PAYENGNE_PUBLIC_KEY>&onload=onloadCallback"
    async defer>
</script>

Implement fetchAccessToken method to obtain a new access token

Full sample code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PayEngine WebComponent</title>
    <script type="text/javascript">
      const fetchAccessToken = async () => {
        const response = await fetch('/accessToken', { method: "POST" });
        if (!response.ok) {
          //Handle error as per your app's design
          return undefined;
        } else {
          const response = await response.json();
          return response;
        }
      }
      
      function onloadCallback() {
        console.log("PayEngine is ready!");
        PayEngine.fetchAccessToken = fetchAccessToken
      }
    </script>
    <script src="https://console.payengine.dev/js/1.0.0/embed.js?key=<YOUR-PUBLIC-KEY>&onload=onloadCallback"></script>
  </head>

  <body>
    <h1>Mechant Onboarding</h1>
    <pay-engine merchant-id="<YOUR-MERCHANT-ID>" type="boarding"></pay-engine>
  </body>
</html>

Logout - Revoke Access Token

While access tokens automatically expire, it's crucial to immediately invalidate them when a user's session ends on the server. Relying solely on token expiration creates a security vulnerability and a suboptimal user experience.

This section provides an example of both client-side and server-side implementations for partners

For immediate session revocation on logout, we recommend implementing client-side access token revocation.

To invalidate the access token on the client side, call the following method in your JavaScript code.

PayEngine.logout()

This ensures that the user's session is terminated, preventing further authenticated requests until they log in again.

You can call the API endpoint to revoke the access token. However, since you are not expected to store the access token for later revocation, it is recommended to use the client-side method instead.

const axios = require('axios');
const express = require('express');
const app = express();

// Replace with your actual API endpoint and any necessary authentication
const API_ENDPOINT = 'https://<PAYENGINE_HOST>/api/merchant'; // Example endpoint
const API_KEY = 'your_api_key'; // PayEngine API Key
const MERCHANT_ID = 'your_merchant_id'; // PayEngine assigned Merchant ID

app.delete('/accessToken/:accessToken', async (req, res) => {
  try {
    const apiURL = `${API_ENDPOINT}/${MERCHANT_ID}/sessions/${req.params.accessToken}`;
    const response = await axios.delete(apiURL, {
      headers: {
        'Content-Type': 'application/json', 
        'Authorization': `Basic ${API_KEY}`, 
      },
    });

    // ... code to clean up backend data
    
    res.json({
      // Aappropriate response as your app's requirements 
    });
  } catch (error) {
    // ERROR HANDLING AND RETRYING
  }
});

Previous4. Choose Integration OptionsNext5a. Securing Embedded UIs Using HMAC (deprecated)

Last updated 13 days ago