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

1. Setup the Server

Follow the Server Setup 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="vaultera-checkout">
    <!--Vaultera SDK injects the 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 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. In case 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();
  
  // Initialize Hyperloader.js
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = "https://sdk.staging.switch.vaultera.co";
 
  let switch; 
  script.onload = () => {
    switch = window.Switch("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 = switch.widgets({ appearance, clientSecret });
    
    const unifiedCheckoutOptions = {
      layout: "tabs",
      wallets: {
        walletReturnUrl: "https://example.com/complete",
        // Mandatory parameter for Wallet Flows such as Google Pay, PayPal, and Apple Pay
      },
    };
    
    const unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions);
    unifiedCheckout.mount("#unified-checkout");
  };
  
  document.body.appendChild(script);
}

2.3 Additional Callback Handling for Wallet Payment Process

This document outlines the details and functionality of optional callbacks onSDKHandleClick and completeDoThis 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 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 completeDoThis 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. Important: The task within onSDKHandleClick 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
});

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 Switch API. Call confirmPayment(), passing along the unifiedCheckout and a return_url to indicate where Switch should redirect the user after they complete the payment. Switch 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 (!switch || !widgets) {
    return;
  }
  setIsLoading(true);

  const { error, status } = await switch.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 Switch 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 switch.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;
  }
}
Important: Please retrieve the payment status from the vaultera switch 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.

Congratulations!

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

title : headless

Headless SDK

vaultera switch is designed to facilitate the integration and management of payment-related functionalities in a decoupled or headless architecture with flexibility to customize your checkout UI.

Customize the Payment Experience Using Headless Functions

1. Initialize the vaultera switch SDK

Initialize vaultera switch Headless SDK onto your app with your publishable key. To get a Publishable Key please find it here.

HTML + JavaScript

// Source Hyperloader on your HTML file using the <script /> tag
switch = Switch.init("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.
});

iOS

// iOS implementation example

Android

// Android implementation example

Flutter

// Flutter implementation example

React Native (Beta)

// React Native implementation example

2. Create a Payment Intent

Make a request to the endpoint on your server to create a new Payment. The clientSecret returned by your endpoint is used to initialize the payment session.
Make sure to never share your API key with your client application as this could potentially compromise your security

3. Initialize your Payment Session

Initialize a Payment Session by passing the clientSecret to the initPaymentSession

iOS

paymentSession?.initPaymentSession(paymentIntentClientSecret: paymentIntentClientSecret)

Android

// Android implementation example

JavaScript

// JavaScript implementation example

Flutter

// Flutter implementation example

React Native (Beta)

// React Native implementation example

Options (Required)

ParameterDescription
clientSecret (string)Required. Required to use as the identifier of the payment.

4. Craft a Customized Payments Experience

Using the paymentSession object, the default customer payment method data can be fetched, using which you can craft your own payments experience. The paymentSession object also exposes a confirmWithCustomerDefaultPaymentMethod function, using which you can confirm and handle the payment session.

iOS

private var handler: PaymentSessionHandler?
 
func initSavedPaymentMethodSessionCallback(handler: PaymentSessionHandler) -> Void {
    self.handler = handler
}
    
@objc func launchHeadless(_ sender: Any) {
    hyperViewModel.paymentSession?.getCustomerSavedPaymentMethods(initSavedPaymentMethodSessionCallback)
    getDefault.isEnabled = true
    getLast.isEnabled = true
    getData.isEnabled = true
}
    
@objc func getCustomerDefaultSavedPaymentMethodData(_ sender: Any) {
    let paymentMethod = self.handler?.getCustomerDefaultSavedPaymentMethodData()
}

Android

// Android implementation example

JavaScript

// JavaScript implementation example

Flutter

// Flutter implementation example

React Native (Beta)

// React Native implementation example

Payload for confirmWithCustomerDefaultPaymentMethod(payload)

Options (Required)

ParameterDescription
confirmParams (object)Parameters that will be passed on to the Switch API.
redirect (string)(web only) Can be either ‘always’ or ‘if_required’
By default, confirmWithCustomerDefaultPaymentMethod() will always redirect to your return_url after a successful confirmation. If you set redirect: “if_required”, then this method will only redirect if your user chooses a redirection-based payment method.

ConfirmParams Object

ParameterDescription
return_url (string)(web only) The url your customer will be directed to after they complete payment.