Implementing Stripe in React

Tiempo de lectura: 3 minutos

Today we are going to learn how to implement the Stripe payment platform in React.

Stripe is a secure payment platform for online transactions or micro-transactions. It will save us from having to store credit card data and help comply with GDPR.

Another advantage is the low commission it charges on each transaction.

The first thing we are going to do is to create an account on Stripe. We go to the page and create the account.

I recommend using test mode for the first transactions.

Now we will go to the Developers section:

And API keys:

We will create the publishable and secret keys, and copy them.

Now let’s go to React and install the dependency:

npm i @stripe/react-stripe-js --save

Once installed, we will create a checkout for it we have to create a new product.

We go to Stripe and open the “Product Catalog”

We fill in all the requested data:

https://i0.wp.com/devcodelight.com/wp-content/uploads/2024/04/imagen-4.png?resize=627%2C853&ssl=1

Now let’s go to our React and create a new function called Stripe.tsx

import { loadStripe } from '@stripe/stripe-js';

const test = true;

function getStripePublicKey() {
    if (test) {
        return "pk_TEST"
    } else {
        return "pk_live_REAL"
    }
}

export enum Products {
    PRODUCT = "product",
}

function getProduct(product: Products) {
    if (test) {//Tests
        switch (product) {
            case Products.PRODUCT:
                return "price_TEST";
        }
    } else {
        switch (product) {
            case Products.PRODUCT:
                return "price_REAL";
        }
    }
}

export function purchase_product(product: Products) {
    const stripe = loadStripe(getStripePublicKey());
    const useProduct = getProduct(product);
stripe.then((stripeData) => {
    stripeData?.redirectToCheckout({
        lineItems: [{ price: useProduct, quantity: 1 }],
        mode: 'payment',
        successUrl: 'https://URL_PAYMENT_COMPLETED',
        cancelUrl: 'https://URL_PAYMENT_CANCELED',
    });
});

}
I have created an enum structure to differentiate the different products that may exist.

Then I have created a variable that will define the test environment true/false and according to that variable, it will return a purchase code and connection to Stripe.

Finally, I indicate that it is of type payment (mode), it can be payment/subscription

You must change successUrl and cancelUrl with two URLs where you indicate the payment status.

And to use it we will put:

purchase_product(Product.PRODUCT);

In our case, in test mode, it will open the purchase:

To make it work in production mode, we will have to add our final domain as an allowed redirect within Stripe. To do this, we go to https://dashboard.stripe.com/settings/checkout

Now we have to validate purchases. For this, I will show you in the following tutorial how to validate purchases with PHP using a webhook.

Leave a Comment