LogoLogo
Explore with DeepWikiJoin Slack CommunityContact Us
  • About Hyperswitch
    • Introduction
    • Payments Suite
    • Payments Modules
      • Cost Observability
      • Revenue Recovery
      • Vault
        • Server to Server Vault tokenization
        • Vault SDK Integration
      • Intelligent Routing
      • Reconciliation
        • Getting Started with Recon
      • Alternate Payment Method Widgets
        • Hyperwidget Integration Guide
    • Roadmap - Q2 2025
      • Previous Roadmap - Q1 2025
      • Previous Roadmap - Q4 2024
      • Previous Roadmap - Q3 2024
      • Previous Roadmap - Q2 2024
      • Previous roadmap - Q1 2024
      • Previous roadmap - Q4 2023
  • Use-Cases
    • For SaaS Businesses
    • For B2B SaaS Businesses
    • For E-Commerce Businesses
    • For Marketplace/Platforms
  • Explore Hyperswitch
    • Payment Orchestration
      • Accept Payments
        • Connectors
          • Activate Connector on Hyperswitch
          • Try a Payment
          • Available Connectors
            • ACI
            • Adyen
            • Airwallex
            • Authorizedotnet
            • Bambora
            • Bank of America
            • Billwerk
            • Bluesnap
            • Braintree
            • Checkout
            • Coinbase
            • Cybersource
              • Apple Pay
              • Google Pay
            • dLocal
            • Fiserv
            • GlobalPayments
            • GoCardless
            • Klarna
            • Mollie
            • MultiSafepay
            • Nuvei
            • OpenNode
            • Paypal
            • PayU
            • Prophetpay
            • Rapyd
            • Shift4
            • Stripe
            • TrustPay
            • Volt
            • Worldline
            • Worldpay
            • Zen
            • Netcetera
              • Authenticating Payments via Netcetera Through HyperSwitch SDK
        • Setup Payment Methods
          • Cards
          • Wallets
            • Apple Pay
              • Web Domain
              • iOS Application
            • Google Pay
            • PayPal
          • Pay Later
          • Banks
            • Bank Debits
            • Bank Redirects
            • Bank Transfers
            • Open Banking
          • Crypto
          • Test Credentials
        • Payment Links
          • Configurations
          • Create Payment Links
          • Secure Payment Links
          • Setup Custom Domain
        • Save a Payment Method
        • Manual Capture
        • Incremental Authorization
        • Tokenization & Card Vault
          • Network Tokenisation
        • Supported Payment Workflows
        • Co-badged Cards
        • Webhooks
      • Process Payouts
        • Getting Started with Payouts
        • Using Saved Payment Methods
        • Smart Router for Payouts
        • Smart Retries in Payout
        • Payout Links
      • Smart Routing
        • Rule Based Routing
        • Volume Based Routing
        • Default Fallback Routing
      • Smart Retries
        • 3DS Step-up Retries
      • 3DS / Strong Customer Authentication
        • Setting up 3DS Decision Manager
        • Native 3DS Authentication
        • External Authentication for 3DS
      • Fraud & Risk Management
        • Activating FRM in Hyperswitch
        • Fraud Blocklist
      • Subscriptions
        • PG Agnostic Card Forwarding
        • Zero Amount Authorization
      • Split Payments
        • Stripe Split Payments
        • Adyen Split Payments
        • Xendit Split Payments
    • Checkout Experience
      • Customizable and Native Integrations
        • Web
          • Node And React
          • Customization
          • Error Codes
          • Node and HTML
          • Vanilla JS and REST API Integration
        • Android
          • Kotlin with Node Backend
          • Customization
          • Features
        • iOS
          • Swift with Node Backend
          • Customization
          • Features
        • React Native
          • React Native with Node Backend
          • Card Widget
          • Customization
        • Flutter
          • Flutter with Node Backend
          • Customization
        • Headless SDK
        • Server Setup
      • Click To Pay
        • Visa Click to Pay: V1 to V2 Migration
      • Payment Methods Management
    • Payment Operations
      • Managing Accounts and Profiles
        • ⚙️Control Centre Account setup
        • Hyperswitch Account Structure
      • Manage Your Team
      • Analytics & operations
        • Exporting payments data
      • Disputes / Chargebacks
      • Surcharge
        • Surcharge Setup guide
      • Multi-Tenancy
      • Data migration
        • Import data to Hyperswitch
        • Export data from Hyperswitch
    • Security and Compliance
      • PCI Compliance
      • Data Security
      • GDPR compliance
      • Identity and Access Management
    • E-commerce Platform Plugins by Hyperswitch
      • 🔌WooCommerce Plugin
        • Setup
        • Roadmap
        • Compatibility
        • FAQs
      • Saleor App
        • Setup
      • Automatic Tax calculation for Express Checkout wallets
  • Hyperswitch open source
    • Overview
      • Run Hyperswitch Locally Using Docker
        • Run Additional Services
      • Development Environment Setup
        • Backend
          • Configure and Run the Application
          • Try out APIs
        • SDK (Frontend)
        • Control Center
    • Deploy on AWS
      • Deploy on AWS using CloudFormation
      • Component-wise Deployment
        • Deploy app server
        • Deploy Control Center
        • Deploy web client
          • Production ready deployment
          • Integrate web client on your web app
          • Playground deployment for prototyping (optional)
        • Deploy Card Vault
          • Production ready deployment on AWS
          • Cloud setup guide
    • Deploy on Kubernetes
      • Deploy on GCP Using Helm Charts
      • Deploy on Azure Using Helm Charts
    • Exploration Guide
    • Account setup
      • Using Hyperswitch Control Center
      • Test a payment
      • Using postman
    • Troubleshooting
  • Testing Payments
  • Check list for Production
    • Going live
      • For SaaS Setup
      • For On-Prem Setup
        • Monitoring
        • PCI compliance
          • Get started
          • Completing the SAQ
        • Data Security
        • Updates
  • Learn more
    • API Reference
    • Connectors Supported
    • SDK Reference
      • React
      • JS
      • Custom Events
    • Hyperswitch architecture
      • Router
      • Storage
      • A Payments Switch with virtually zero overhead
    • Payment flows
    • Blog
  • Community Guidelines
Powered by GitBook

Compliance

  • Vulnerability Disclosure
  • PCI DSS 4.0
  • ISO 27001:2022

Community

  • Slack
  • Discord
  • GitHub Discussion
On this page
  • Demo App
  • 1. Setup the server
  • 2. Build checkout page on the client
  • 2.1 Define the payment form
  • 3. Complete payment on the client
  • 3.1 Handle the submit event and complete the payment
  • 3.2 Display a payment status message

Was this helpful?

  1. Explore Hyperswitch
  2. Checkout Experience
  3. Customizable and Native Integrations
  4. Web

Vanilla JS and REST API Integration

Integrate hyper SDK to any Web App using hyperswitch-node

Last updated 1 month ago

Was this helpful?

Before following these steps, please configure your payment methods . Use this guide to integrate hyperswitch SDK to you app with any framework. If you are using React framework please go through Integration to use a dedicated wrapper.

1. Setup the server

Follow the section.

2. Build checkout page on the client

2.1 Define the payment form

This step is recommended for the Unified Checkout for an enhanced user experience. In case you are integrating Express Checkout (mentioned later below), this step is not required.

Add one empty placeholder div to your checkout form for each Widget that you’ll mount. HyperLoader inserts an iframe into each div to securely collect the customer’s email address and payment information.

<form id="payment-form">
  <div id="unified-checkout">
   <!--HyperLoader injects the Unified Checkout-->
  </div>
  <button id="submit">
    <div class="spinner hidden" id="spinner"></div>
    <span id="button-text">Pay now</span>
  </button>
  <div id="payment-message" class="hidden"></div>
</form>

2.2 Fetch the Payment and create the Unified Checkout

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.

Important: Make sure to never share your API key with your client application as this could potentially compromise your payment flow

Following this, create a unifiedCheckout and mount it to the placeholder div in your payment form. This embeds an iframe with a dynamic form that displays configured payment method types available from the Payment, allowing your customer to select a payment method. The form automatically collects the associated payment details for the selected payment method type.

Incase, you want the SDK to be loaded on a particular event (like button click), you can call the initialize function on that event.

// Fetches a payment intent and captures the client secret
async function initialize() {
  const response = await fetch("/create-payment", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({currency: "USD",amount: 100}),
  });
  const { clientSecret } = await response.json();
  
  // Initialise Hyperloader.js
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = "https://beta.hyperswitch.io/v1/HyperLoader.js";
 
  let hyper; 
  script.onload = () => {
      hyper = window.Hyper("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.
      })
      const appearance = {
          theme: "midnight",
      };
      const widgets = hyper.widgets({ appearance, clientSecret });
      const unifiedCheckoutOptions = {
          layout: "tabs",
          wallets: {
              walletReturnUrl: "https://example.com/complete",
              //Mandatory parameter for Wallet Flows such as Googlepay, Paypal and Applepay
          },
      };
      const unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions);
      unifiedCheckout.mount("#unified-checkout");
  };
  document.body.appendChild(script);
}

2.3 Additional Callback Handling for Wallets Payment Process

This document outlines the details and functionality of an optional callback completeDoThis and onSDKHandleClick 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.

  • onSDKHandleClick: This callback is triggered immediately after the user clicks any wallet button.

  • completeDoThis: This callback is triggered after the payment is completed, just before the SDK redirects to 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 behaviour, 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

const unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions);
unifiedCheckout.mount("#unified-checkout");

unifiedCheckout.onSDKHandleClick(()=>{
  // Add any custom logic for when the payment button is clicked, such as logging or tracking
  console.log("On Click Wallets")
})

unifiedCheckout.on("completeDoThis",()=>{
  console.log("On Payment Complete")
  // Add any custom post-payment logic here, such as redirection or displaying a success message
})

2.2 Fetch the Payment and create the Express Checkout

The Express Checkout Element gives you a single integration for accepting payments through one-click payment buttons. Supported payment methods include ApplePay, GooglePay and PayPal.

Make a request to the endpoint on your server to create a new Payment. The clientSecret returned by your endpoint is used to complete the payment.

Important: Make sure to never share your API key with your client application as this could potentially compromise your payment flow

Create an expressCheckout and mount it to the placeholder div in your payment form. 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. The payment methods automatically collects the associated payment details for the selected payment method type.

// Fetches a payment intent and captures the client secret
async function initialize() {
  const response = await fetch("/create-payment", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({currency: "USD",amount: 100}),
  });
  const { clientSecret } = await response.json();
  
  // Initialise Hyperloader.js
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = "https://beta.hyperswitch.io/v1/HyperLoader.js";
 
  let hyper; 
  script.onload = () => {
      hyper = window.Hyper("YOUR_PUBLISHABLE_KEY")
      const appearance = {
          theme: "midnight",
      };
      const widgets = hyper.widgets({ appearance, clientSecret });
      const expressCheckoutOptions = {
          wallets: {
              walletReturnUrl: "https://example.com/complete",
              //Mandatory parameter for Wallet Flows such as Googlepay, Paypal and Applepay
          },
      };
      const expressCheckout = widgets.create("expressCheckout", expressCheckoutOptions);
      expressCheckout.mount("#express-checkout");
  };
  document.body.appendChild(script);
}

3. Complete payment on the client

3.1 Handle the submit event and complete the payment

Note: This step is not required for ExpressCheckout

Listen to the form’s submit event to know when to confirm the payment through the hyper API.

Call confirmPayment(), passing along the unifiedCheckout and a return_url to indicate where Hyper should redirect the user after they complete the payment. Hyper redirects the customer to an authentication page depending on the payment method. After the customer completes the authentication process, they’re redirected to the return_url.

async function handleSubmit(e) {
  setMessage("");
  e.preventDefault();

  if (!hyper || !widgets) {
    return;
  }
  setIsLoading(true);

  const { error, status } = await hyper.confirmPayment({
    widgets,
    confirmParams: {
      // Make sure to change this to your payment completion page
      return_url: "https://example.com/complete",
    },
    redirect: "always", // if you wish to redirect always, otherwise it is defaulted to "if_required"
  });

  if (error) {
    if (error.type === "card_error" || error.type === "validation_error") {
      setMessage(error.message);
    } else {
      if (error.message) {
        setMessage(error.message);
      } else {
        setMessage("An unexpected error occurred.");
      }
    }
  }
  if (status) {
    handlePaymentStatus(status); //handle payment status
  }
  setIsLoading(false);
}

Also if there are any immediate errors (for example, your customer’s card is declined), HyperLoader returns an error. Show that error message to your customer so they can try again.

3.2 Display a payment status message

When Hyper redirects the customer to the return_url, the payment_intent_client_secret query parameter is appended by HyperLoader. Use this to retrieve the Payment to determine what to show to your customer.

// Fetches the payment status after payment submission
async function checkStatus() {
  const clientSecret = new URLSearchParams(window.location.search).get(
    "payment_intent_client_secret"
  );

  if (!clientSecret) {
    return;
  }

  const { payment } = await hyper.retrievePayment(clientSecret);

  switch (payment.status) {
    case "succeeded":
      showMessage("Payment succeeded!");
      break;
    case "processing":
      showMessage("Your payment is processing.");
      break;
    case "requires_payment_method":
      showMessage("Your payment was not successful, please try again.");
      break;
    default:
      showMessage("Something went wrong.");
      break;
  }
}

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

here
React
Demo App
Server Setup