Skip to content

React integration

Add the Cardencer checkout to a React app with the HyperElements provider, the PaymentElement component and the useHyper hook.

This guide builds a checkout page in React. It uses the React bindings of the Cardencer web SDK, installed from npm below, and loads the SDK itself from sdk.cardencer.com.

Before you start, set up your server so that POST /create-payment returns a clientSecret.

1. Install the React bindings#

bash
npm install @juspay-tech/react-hyper-js

2. Load the SDK#

Create a small helper that loads the Cardencer loader once and returns the SDK instance. Call it at the top level of your app (outside components) so the SDK starts loading before the customer reaches checkout.

const LOADER = "https://sdk.cardencer.com/web/0.131.0/v1/HyperLoader.js";

export function loadCardencer({ publishableKey, profileId, backendUrl }) {
  return new Promise((resolve, reject) => {
    const init = () => resolve(window.Hyper({ publishableKey, profileId }, backendUrl ? { customBackendUrl: backendUrl } : {}));
    if (window.Hyper) return init();
    const script = document.createElement("script");
    script.src = LOADER;
    script.async = true;
    script.onload = init;
    script.onerror = () => reject(new Error("Cardencer SDK failed to load"));
    document.head.appendChild(script);
  });
}

For Apple Pay, the loader must run in the top-level window. Do not load it inside an iframe only.

3. Fetch the payment and wrap your form#

Create the payment as soon as the checkout page loads, then pass the clientSecret and the SDK promise to HyperElements. Every component inside it can use the SDK.

import { useEffect, useState } from "react";
import { HyperElements } from "@juspay-tech/react-hyper-js";
import { hyperPromise } from "./App";
import CheckoutForm from "./CheckoutForm";

export default function Checkout() {
  const [clientSecret, setClientSecret] = useState(null);

  useEffect(() => {
    fetch("/create-payment", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ orderId: "58211" }),
    })
      .then((res) => res.json())
      .then((data) => setClientSecret(data.clientSecret));
  }, []);

  if (!clientSecret) return null;
  return (
    <HyperElements hyper={hyperPromise} options={{ clientSecret, appearance: { theme: "default" } }}>
      <CheckoutForm />
    </HyperElements>
  );
}

4. Render the payment form and confirm#

PaymentElement renders the secure form. useHyper() returns the SDK and useWidgets() the mounted elements; pass both to confirmPayment().

import { useState } from "react";
import { PaymentElement, useHyper, useWidgets } from "@juspay-tech/react-hyper-js";

export default function CheckoutForm() {
  const hyper = useHyper();
  const widgets = useWidgets();
  const [message, setMessage] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!hyper || !widgets) return;
    setIsLoading(true);
    setMessage(null);

    const { error, status } = await hyper.confirmPayment({
      elements: widgets,
      confirmParams: { return_url: "https://example.com/checkout/complete" },
      redirect: "if_required",
    });

    if (error) setMessage(error.message ?? "Your payment could not be completed. Please try again.");
    else if (status === "succeeded" || status === "processing") window.location.assign("/checkout/complete");
    setIsLoading(false);
  };

  return (
    <form onSubmit={handleSubmit}>
      <PaymentElement
        id="payment-element"
        options={{ layout: "tabs", wallets: { walletReturnUrl: "https://example.com/checkout/complete" } }}
      />
      <button disabled={isLoading || !hyper}>{isLoading ? "Processing…" : "Pay now"}</button>
      {message && <p role="alert">{message}</p>}
    </form>
  );
}

If the card needs 3D Secure, the SDK shows the challenge and, depending on the bank, redirects to your return_url. Declines and validation errors come back in error.

5. Show the result on the return page#

The SDK appends payment_intent_client_secret to your return_url. Read it to display the outcome:

import { useEffect, useState } from "react";
import { useHyper } from "@juspay-tech/react-hyper-js";

export default function Complete() {
  const hyper = useHyper();
  const [status, setStatus] = useState(null);

  useEffect(() => {
    const clientSecret = new URLSearchParams(window.location.search).get("payment_intent_client_secret");
    if (!hyper || !clientSecret) return;
    hyper.retrievePaymentIntent(clientSecret).then(({ paymentIntent }) => setStatus(paymentIntent.status));
  }, [hyper]);

  if (status === "succeeded") return <p>Payment succeeded. Thank you!</p>;
  if (status === "processing") return <p>Your payment is processing.</p>;
  if (status) return <p>Your payment was not successful. Please try another card.</p>;
  return null;
}

Render Complete inside the same HyperElements provider so useHyper() is available.

Do not fulfil orders from the browser status. Wait for the payment_succeeded webhook or retrieve the payment from your server.

Element events#

Pass handlers to PaymentElement to react to the form state:

jsx
<PaymentElement
  id="payment-element"
  options={options}
  onReady={() => setReady(true)}
  onChange={(event) => setComplete(event.complete)}
/>

The change event payload looks like { elementType: "payment", complete: false, empty: false, value: { type: "card" } }.

Wallet callbacks#

For Apple Pay and Google Pay you can hook into the flow:

  • onPaymentButtonClick runs right after the customer taps a wallet button. It must finish within 1 second, or Apple Pay fails.
  • onPaymentComplete runs after the payment completes, before the redirect to walletReturnUrl. If you provide it, you handle the redirect yourself.
jsx
<PaymentElement
  id="payment-element"
  options={options}
  onPaymentButtonClick={() => analytics.track("wallet_clicked")}
  onPaymentComplete={() => window.location.assign("/checkout/complete")}
/>

Test it#

Use 4242 4242 4242 4242 and 4000 0038 0000 0446 (3D Secure). See Sandbox & test cards.

Next: customise the form.