# How to add Stripe Intents as a payment provider

Source: https://dev.arcxp.com/subscriptions/sales/build/payment-provider-stripe-intents/

[Stripe Intents](https://stripe.com/) is a powerful API provided by Stripe, designed to simplify and secure the process of accepting online payments.

> **Note:**
> 
> If you are using Stripe Intents as your payment provider, with a few pages and clicks you can use our Theme blocks to have the checkout flow working on your site.

## Prerequisites

1. [Add Stripe Intents as a payment provider](https://dev.arcxp.com/subscriptions/sales/configure/payment-gateway-providers/#setting-up-a-payment-provider) through the Admin tool.
2. Verify domain(s): Stripe Intents supports `Apple Pay`, `Google Pay`, among others as [wallets](https://docs.stripe.com/payments/wallets). To provide these payment options to your end users, you need to enable them in the Stripe Developer Console. Our Theme blocks will render `Apple Pay` (Safari) or `Google Pay` (on the web) options automatically if they are enabled. In this guide, we will show you the code required in case you want to implement the Stripe Intents form by your own.

To enable `Apple Pay` and/or `Google Pay` as wallets

1. `Enable Apple Pay & Google Pay`: In Stripe developer console, go to `Settings`, click on `Payments`, then select `Payment methods`. In the “Wallets” section, enable “Apple Pay” and/or “Google Pay”.  
![Enable wallets](https://dev.arcxp.com/images/subscriptions/sales/build/payment-provider-stripe-intents/enable-wallets.png)
2. `Register and verify the domain`: Expand `Apple Pay` or `Google Pay`, and click on `Configure domains`. Then, enter your domain.  
![Enable wallets](https://dev.arcxp.com/images/subscriptions/sales/build/payment-provider-stripe-intents/configure-domain.png)  
Once the domain is registered, it appears as `unverified`. Ensure to verify the domain: Host the file provided by Stripe inside the _.well-known_ folder. Alternatively, you can verify the domain as Stripe describes in: [Register domains for payment methods](https://docs.stripe.com/payments/payment-methods/pmd-registration?dashboard-or-api=api).  
Contact [Arc XP Customer Support](https://support.arcpublishing.com/) in case you are using fusion. You will need to provide them the file and they will host the file for you.  
![Host well known file](https://dev.arcxp.com/images/subscriptions/sales/build/payment-provider-stripe-intents/host-well-known-file.png)

## Checkout flow

> **Note:**
> 
> We will walk through this document using our SDK methods, but if you need to call the APIs directly, please check [How to Connect with Arc XP Sales SDK and APIs on the web](https://dev.arcxp.com/subscriptions/sales/build/how-to-connect-with-sdks-and-apis/#arc-xp-sales-sdks-and-apis) to see the API that our SDK methods are wrapping.

The Stripe Intent checkout workflow follows the steps defined on [Checkout to purchase a subscription](https://dev.arcxp.com/subscriptions/sales/learn/checkout-to-purchase-a-subscription/). The code provided below is explained according to the **regular checkout** flow.

1. `Authenticate`: The end user [logs in](https://dev.arcxp.com/subscriptions/identity/learn/manage-user-accounts-reader-experience/#user-login) before starting to put items into the cart.
2. `Get products and prices`. There is no SDK method for this, but you can retrieve a live offer by calling:  
`GET /retail/public/v1/offer/live/default` or `GET /retail/public/v1/offer/live/{campaignName}`
3. `Add item(s) to cart`: The live offer may contain multiple products and prices. The end user should [add each desired item](https://dev.arcxp.com/subscriptions/sales/learn/subscription-management-reader-experience/#add-item-to-cart) (product and price) to the cart.
4. `Create order`: When the end user has at least one item in their cart, they can initiate the payment flow by calling [create order](https://dev.arcxp.com/subscriptions/sales/learn/subscription-management-reader-experience/#create-order).  
As described on [Secure your site against attacks: CORS Domains, Blocked email domains and reCAPTCHA](https://dev.arcxp.com/subscriptions/identity/configure/secure-your-site-against-attacks-cors-domains-blocked-email-domains-and-recaptcha#recaptcha), reCAPTCHA can be enabled for `checkout` flow. If reCAPTCHA is enabled, you must to pass a reCAPTCHA token when calling `createOrder()`.  
A successful `createOrder()` call requires a valid reCAPTCHA token, if reCAPTCHA is enabled for checkout. Therefore, the reCAPTCHA should be displayed or hidden based on the tenant’s settings.

  1. `Obtain the tenant configuration`: Retrieve the configuration from Sales to check if reCAPTCHA is enabled for checkout (i.e. `Sales.getConfig()`). However, since the parameters to initialize reCAPTCHA are found in Identity, you will also need to retrieve the configuration from Identity (i.e. `Identity.getConfig()`).
  2. `Display or hide the reCAPTCHA and pass reCAPTCHA token` when calling `createOrder()`. See [Registration](https://dev.arcxp.com/subscriptions/identity/build/implement-registration-login-one-time-access/#registration) implementation, where code related to reCAPTCHA implementation is provided. You will need to apply few adjustements to check if reCAPTCHA is enabled for checkout.
5. `Get payment options`: Retrieve the payment gateway configuration set up in the Admin tool for the tenant (organization + site) making a call to `Sales.getPaymentOptions()`. This SDK returns an array containing all payment methods configured for the tenant.
6. `Initialize payment`: On the previous step, you can identify [payment methods](https://dev.arcxp.com/subscriptions/sales/configure/payment-gateway-providers) set up for stripe Intents, by checking if they have `paymentMethodType: 18`. For each element returned on the previous step, you will see a `paymentMethodID`, this value together with the orden number are required when calling `Sales.initializePayment()`. This method will create a payment session with the chosen payment provider and the billing details for the order.  
```js
    const orderNumber = Sales.currentOrder.orderNumber;
    const paymentProvider = chosenPaymentOption; // chosen by the user with paymentMethodType: 18
    ...
    const payment = await Sales.initializePayment(orderNumber, paymentProvider.paymentMethodID);
```
If successful, Sales.initializePayment will resolve to an object. The token returned as `parameter2` is used to initialize the interaction with Stripe and render the elements on the payment form.

**Execute Stripe’s js**  
```js
    import { loadStripe } from "@stripe/stripe-js";
    import { Elements } from "@stripe/react-stripe-js";
    import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
    ...
    export const StripeIntentCheckout = props => {
    ...
        // stripe hooks have to be within Elements wrapper
        // https://stripe.com/docs/stripe-js/react#useelements-hook
    const elements = useElements();
    const stripe = useStripe();
    const [stripePromise, setStripePromise] = useState(null);
    //payment contains the values returned by Sales.initializePayment()
    useEffect(() => {
        const initStripe = async () => {
            try {
                loadStripe(payment.parameter2).then(data => setStripePromise(data));
            } catch (e) {
                ...
            }
        };
        initStripe();
    }, [payment]);
    const handleSubmit = async (event, elements, stripe, details) => {
        event.preventDefault();
        const cardElement = elements.getElement('card');
        const { error, paymentMethod } = await stripe.createPaymentMethod({
            type: 'card',
            card: cardElement,
            billing_details: details
        });
        if (error) {
            setError(error);
            return;
        }
        let result;
        const totalOrder = Sales.currentOrder.total;
        if (totalOrder > 0) {
            // https://docs.stripe.com/js/payment_intents/confirm_card_payment
            result = await stripe.confirmCardPayment(payment.parameter1, {
                payment_method: paymentMethod.id
                });
        } else {
            // https://docs.stripe.com/js/setup_intents/confirm_card_setup
            result = await stripe.confirmCardSetup(payment.parameter1, {
                payment_method: paymentMethod.id
                });
        }
        if (result.error) {
            setError(result.error);
            return;
        } else {
            const isLoggedIn = await Identity.isLoggedIn();
            let orderDetails;
            if (isLoggedIn) {
                if (totalOrder > 0) {
                    await Sales.finalizePayment(orderNumber, paymentMethodID, result.paymentIntent.id);
                    // If you need to pass reCAPTCHA
                    // Sales.finalizePayment(orderNumber, paymentMethodID, result.paymentIntent.id, null, captcha)
                } else {
                    await Sales.finalizePayment(orderNumber, paymentMethodID, result.setupIntent.id);
                    // If you need to pass reCAPTCHA
                    // Sales.finalizePayment(orderNumber, paymentMethodID, result.setupIntent.id, null, captcha)
                }
                // go to success page
            }
        }
    }
    if (stripePromise) {
        <Elements stripe={stripePromise}>
            // CheckoutStripeIntentForm contains the Stripe elements
            <CheckoutStripeIntentForm
                handleSubmit={handleSubmit}
                error={error}
            />
        </Elements>
    }
}
```
7. `Finalize payment`: In the previous code, you can see that different Stripe methods need to be called depending on the total order amount:

  - If total order amount is greater to zero use _stripe.confirmCardPayment()_.
  - If total order amout is zero use _stripe.confirmCardSetup()_  
If the response from _stripe.confirmCardSetup()_ or _stripe.confirmCardPayment()_ is successful, it indicates the payment was approved by Stripe, and a token will be returned:

  - _result.paymentIntent.id_ if you called _stripe.confirmCardPayment()_, that means if the total order amout was greater to zero.
  - _result.setupIntent.id_ if you called _stripe.confirmCardSetup()_, that means if the total order amout was zero  
This _token_, along with the order number and the reCAPTCHA token (if this feature is enabled for checkout) should be passed when calling `Sales.finalizePayment()`.  
For orders with a total of zero, no charges apply to the end user, but a stripe _token_ and a _transaction_ must be generated for future renewals.

> **Note:**
> 
> Please refer to [Stripe documentation](https://docs.stripe.com/elements/express-checkout-element/accept-a-payment?client=react) for more details, including how to enable Apple Pay, Google Pay, and other payment methods in your payment form. [Here](https://docs.stripe.com/testing) you can find a list of accepted cards for testing purpose.
