> ## Documentation Index
> Fetch the complete documentation index at: https://docs.switch.vaultera.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Node and React

**Before following these steps, please configure your payment methods.**

Use this guide to integrate Vaultera Switch SDK to your React app.

You can use the "Try out" in our dashboard as a reference with your Vaultera Switch credentials to test the setup.

## 1. Setup the Server

### 1.1 Follow the Server Setup Section

Follow the Server Setup section for backend configuration.

## 2. Build Checkout Page on the Client

### 2.1 Install the switch-js and react-switch-js Libraries

Install the packages and import them into your code:

```bash theme={"system"}
npm install @vaultera-tech/switch-js
npm install @vaultera-tech/react-switch-js
```

### 2.2 Add Vaultera Switch to Your React App

Use switch-js to ensure that you stay PCI compliant by sending payment details directly to the Vaultera Switch server:

```javascript theme={"system"}
import React, { useState, useEffect } from "react";
import { loadSwitch } from "@vaultera-co/react-js";
import { SwitchElements } from "@vaultera-co/react-switch-js";
```

### 2.3 Load switch-js

Call `loadSwitch` with your publishable API keys to configure the library. To get a publishable key, please find it [here](https://app.test.switch.vaultera.co/dashboard/developer-api-keys):
For the backend url you can use `https://api.switch.vaultera.co` for test environment

```javascript theme={"system"}
const switchPromise = loadSwitch("YOUR_PUBLISHABLE_KEY", {
  customBackendUrl: "YOUR_BACKEND_URL",
});
```

### 2.4 Fetch the Payment and Initialize SwitchElements

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:

```javascript theme={"system"}
useEffect(() => {
  // Create PaymentIntent as soon as the page loads
  fetch("/create-payment-intent", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ items: [{ id: "xl-tshirt" }], country: "US" }),
  })
    .then((res) => res.json())
    .then((data) => setClientSecret(data.clientSecret));
}, []);
```

### 2.5 Initialize SwitchElements

Pass the promise from `loadSwitch` to the `SwitchElements` component. This allows the child components to access the Switch service via the `SwitchElements` parent component. Additionally, pass the client secret as options to the `SwitchElement` component:

```javascript theme={"system"}
<div
  style={{
    width: "480px",
  }}
  >
  <h2>Vaultera Switch Unified Checkout</h2>
  {clientSecret && switchPromise && (
    <SwitchElements switch_promise={switchPromise} options={{ clientSecret }}>
      <CheckoutForm />
    </SwitchElements>
  )}
</div>
```

### 2.6 Setup the State (Optional)

Initialize a state to keep track of payment, display errors, and control the user interface:

```javascript theme={"system"}
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
```

### 2.7 Store a Reference to Switch

Access the switch-js library in your `CheckoutForm` component by using the `useSwitch()` and `useElements()` hooks.

```javascript theme={"system"}
const vaultera_switch = useSwitch();
const elements = useElements();
```

### 3. Add the unified checkout

Add the UnifiedCheckout to your Checkout.
This embeds an iframe with a dynamic form that displays configured payment method types available for the Payment, allowing your customer to select a payment method. The form automatically collects the associated payment details for the selected payment method type.

(Optional) Define paymentElementOptions:

```javascript theme={"system"}
var unifiedCheckoutOptions = {
  wallets: {
    walletReturnUrl: "https://example.com/complete",
    //Mandatory parameter for Wallet Flows such as Googlepay, Paypal and Applepay
  },
};
```

```html theme={"system"}
<form id="payment-form" onSubmit={handleSubmit}>
  <PaymentElement id="payment-element" />
  <button disabled={isProcessing || !vaultera_switch || !elements} id="submit">
    <span id="button-text">
      {isProcessing ? "Processing ... " : "Pay now"}
    </span>
  </button>
  {/* Show any error or success messages */}
  {message && <div id="payment-message">{message}</div>}
</form>
```

### 3.1 Complete the payment and handle errors

Call confirmPayment(), passing along the UnifiedCheckout and a return\_url to indicate where Switch should redirect the user after they complete the payment.
For payments that require additional authentication, Vaultera Switch sdk 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.

If there are any immediate errors (for example, some fields are missing), switch-js returns an error. Show that error message to your customer so they can try again.

```javascript theme={"system"}
const handleSubmit = async (e) => {
e.preventDefault();

if (!vaultera_switch || !elements) {
  return;
}

setIsProcessing(true);

const { error, status } = await vaultera_switch.confirmPayment({
  elements,
  confirmParams: {
    // Make sure to change this to your payment completion page
    return_url: "https://example.com/complete",
  },
  redirect: "always",
});

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);
}
setIsLoading(false);
```
