> ## Documentation Index
> Fetch the complete documentation index at: https://developers.trycents.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Add new payment Workflow

All Cents apps use Stripe to manage payments.
We do not store card data in our system, as it is managed by Stripe.

This guide will walk you through the process of securely collecting
a customer's card details and adding them as a new payment method using Dispatch API and Stripe.js.

#### Overview of the Flow

Example with React application

<Steps>
  *Frontend (React)*: Load [Stripe.js](https://www.npmjs.com/package/@stripe/stripe-js) and use Stripe Elements to create a secure card input form.

  <Step>
    *Frontend (React)*: On form submission, use Stripe's createPaymentMethod method to convert the card details into a secure token (pm\_...).
  </Step>

  <Step>
    *Frontend (React)*: Send this token and the card type to Dispatch API endpoint:
    [POST /customers/payment-methods](/api-reference/endpoint/customer/addPaymentMethod)
  </Step>

  <Step>
    *Backend (Dispatch API)*: We receive the token, use it with our Stripe backend SDK to verify a Payment Method and attach it to the customer in our system.
  </Step>
</Steps>

#### Prerequisites

You have Publishable Key for Stripe library provided by Cents

### Step 1. Install Stripe.js

You need to install the **[@stripe/stripe-js](https://www.npmjs.com/package/@stripe/stripe-js)** and **[@stripe/react-stripe-js](https://www.npmjs.com/package/@stripe/react-stripe-js)** libraries, which provide React-friendly hooks and components for Stripe Elements.

```bash theme={null}
npm install @stripe/stripe-js @stripe/react-stripe-js
```

### Step 2. Create the Stripe Instance and Context Provider

In your form component or a top-level component, create a Stripe promise and provide it to your application using the Elements provider.
Put to the function **loadStripe** the KEY **publishable-key-here** that was provided by CENTS

```jsx theme={null}
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';

const stripePromise = loadStripe('publishable-key-here'); // this key is managed by CENTS

function App() {
  return (
    <Elements stripe={stripePromise}>
      <YourPaymentForm />
    </Elements>
  );
}
```

### Step 3: Build the "Add Card" Form Component

```jsx theme={null}
// PaymentForm.js
import React, { useState } from 'react';
import {
  useStripe,
  useElements,
  CardElement
} from '@stripe/react-stripe-js';

const PaymentForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async (event) => {
    event.preventDefault();
    
    if (!stripe || !elements) {
      return;
    }

    // 1. Get a reference to the CardElement mounted by ReactStripeElements
    const cardElement = elements.getElement(CardElement);
    // 2. Use stripe.createPaymentMethod to create the Payment Method
    const { error: stripeError, paymentMethod } = await stripe.createPaymentMethod({
        type: 'card',
        card: cardElement,
    });

    if (stripeError) {
        // Show error to your customer (e.g., invalid card)
        return
    }

    // PaymentMethod created successfully. Send the ID (token) to DIspatch API server.
    const response = await fetch('/api/common/customers/payment-methods', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
          token: paymentMethod.id,
          type: paymentMethod.type
        }),
    });

    const result = await response.json();
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Credit or debit card</label>
        <CardElement
          id="card-element"
        />
      </div>
      
      <button 
        type="submit" 
        disabled={!stripe || loading}
      >
        Save Payment Method
      </button>
    </form>
  );
};

export default PaymentForm;
```

### What Dispatch API Expects

Your frontend code is now correctly configured to send a request to Dispatch API endpoint:

Endpoint: [POST /customers/payment-methods](/api-reference/endpoint/customer/addPaymentMethod)

Request Body (JSON):

```JSON theme={null}
{
    "token": "pm_.....", // The Payment Method ID from Stripe
    "type": "card" // The type, also from the Stripe Payment Method object 
}
```

On success, the API returns the saved payment method record:

```JSON theme={null}
{
    "id": 42,                          // Internal ID, not needed for future requests
    "paymentMethodToken": "pm_.....",  // Save this — required for creating or updating service orders
    "type": "card",
    "provider": "stripe",
    "centsCustomerId": 123
}
```

<Tip>
  Save the returned `paymentMethodToken`. You will need it to specify a payment method when creating or updating a service order.
</Tip>

By following this guide, you have implemented a secure, PCI-compliant way to add new payment methods without sensitive card data ever touching servers.
