ChargX Documentation

React SDK

React SDK documentation

Welcome to ChargX payment gateway React SDK documentation - set of clearly defined methods of communication between clients Web apps and payment gateway. It provides a React hook to simplify integrating ChargX payments into your React application.

Before you start

Follow Getting Started guide how to create an Account and obtain API key.

Install SDK

# via npm
npm install @chargx/sdk

# or via yarn
yarn add @chargx/sdk

Usage

Import and Initialize Hook

import {
  usePayment,
  type AuthData,
  type PretransactResponse,
} from "@chargx/sdk";

const {
  pretransact,
  load,
  transact,
  dispatchData,
  checkCustomerLoyaltyPoints,
  scriptLoaded,
  scriptError,
} = usePayment("your-publishable-key-here", "https://api.chargx.io");

2. Init lib on Component Mount

Call this once on mount to retrieve authData and determine the environment. Store authData in your component state for later use:

const [authData, setAuthData] = useState<AuthData | undefined>();

useEffect(() => {
  pretransact().then((response: PretransactResponse) => {
    setAuthData(response.authData);
    load(response.isProduction ? "PRODUCTION" : "SANDBOX");
  });
}, []);
  • authData is required for dispatchData
  • isProduction is used to load the appropriate script version

3. Submit Payment

Call dispatchData() and transact() inside your form submission handler:

const cardData = {
  cardNumber: "4111111111111111",
  cardCode: "123",
  month: "12",
  year: "29",
};

const billingAddress =  {
  street: "...",
  unit: "...",
  city: "...",
  state: "...",
  zipCode: "...",
  countryCode: "...",
  phone: "...",
};

const orderId = "order id from your app" // for logging purpose

const handleSubmit = async () => {
  try {
    const response = await dispatchData({
      cardData,
      authData: authData as AuthData,
    });

    const opaqueData = response.opaqueData ? {
        dataDescriptor: response.opaqueData.dataDescriptor,
        dataValue: response.opaqueData.dataValue,
      } : { token: response.token };

    await transact({
      currency: "USD",
      amount: amount,
      type: "fiat",
      opaqueData,
      customer: {
        name: cardholderName,
        email,
      },
      deductLoyaltyPoints: pointsToDeduct,
      billingAddress, // optionally pass builling address
      orderId  // optionally pass order id from your system
    });

    console.log("Payment successful!");
  } catch (dispatchErrors) {
    console.error("dispatchErrors", dispatchErrors);
  }
};

4. Check Customer Loyalty Points (Optional)

Call this when the customer enters their email, e.g. on blur of the email input field:

const fetchLoyaltyPoints = async (email: string) => {
  const loyaltyPoints = await checkCustomerLoyaltyPoints({ email });
};


await transact({
  ...
  deductLoyaltyPoints: loyaltyPoints,
});