In today’s digital landscape, a smooth and secure payment experience is crucial for any web
application. Stripe, a leading payment gateway, simplifies the process of accepting online
payments. This blog post guides you through integrating Stripe payments into your React
application, empowering you to accept credit card payments with ease.
In terminal
npm install @stripe/stripe-js @stripe/react-stripe-js
import React, { useState } from 'react';
import { Elements, CardElement, useStripe, useElements } from
'@stripe/react-stripe-js';
const YOUR_PUBLISHABLE_KEY = 'YOUR_STRIPE_PUBLISHABLE_KEY';
//
Replace with your publishable key
const PaymentForm = () => {
const [cardError, setCardError] = useState(null);
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (event) => {
event.preventDefault();
if (!stripe || !elements) {
// Stripe.js has not loaded yet. Make sure to disable submit
button while loading
return;
}
const result=await
stripe.confirmCardPayment(YOUR_BACKEND_ENDPOINT,{
payment_method:{
card:elements.getElement(CardElement),
},
});
if(result.error){
console.error(result.error.message);
setCardError(result.error.message);
}else{
//Paymentsuccessful!Handletheresponsefromyourbackend
(e.g.,showsuccessmessage)
console.log('Paymentsuccessful!',result);
}
};
return(
<Elementsstripe={YOUR_PUBLISHABLE_KEY}>
<formonSubmit={handleSubmit}>
<CardElementonChange={(event)=>
setCardError(event.error)}/>
<buttontype="submit"disabled={!stripe}>
Pay
</button>
{cardError&&<div>{cardError}</div>}
</form>
</Elements>
);
};
exportdefaultPaymentForm;
importReactfrom'react';
importPaymentFormfrom'./PaymentForm';
functionApp(){
return (
<Elements stripe={YOUR_PUBLISHABLE_KEY}>
<PaymentForm />
</Elements>
);
}
export default App;