Skip to content

Instantly share code, notes, and snippets.

@Octagon-simon
Created August 14, 2024 09:20
Show Gist options
  • Save Octagon-simon/1639af7dc49e15d64864a2fe47d66a30 to your computer and use it in GitHub Desktop.
Save Octagon-simon/1639af7dc49e15d64864a2fe47d66a30 to your computer and use it in GitHub Desktop.
Simple stripe integration with clientSecret
import React, {useState} from 'react';
import {loadStripe} from '@stripe/stripe-js';
import {
PaymentElement,
Elements,
useStripe,
useElements,
} from '@stripe/react-stripe-js';
const CheckoutForm = () => {
const stripe = useStripe();
const elements = useElements();
const [errorMessage, setErrorMessage] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
if (elements == null) {
return;
}
// Trigger form validation and wallet collection
const {error: submitError} = await elements.submit();
if (submitError) {
// Show error to your customer
setErrorMessage(submitError.message);
return;
}
// Create the PaymentIntent and obtain clientSecret from your server endpoint
const res = await fetch('/create-intent', {
method: 'POST',
});
//convert to json
const {client_secret: clientSecret} = await res.json();
const {error} = await stripe.confirmPayment({
//`Elements` instance that was used to create the Payment Element
//remember to verify payment and confirm current subscription
elements,
clientSecret,
confirmParams: {
return_url: 'https://example.com/order/123/complete',
},
});
if (error) {
// This point will only be reached if there is an immediate error when
// confirming the payment. Show error to your customer (for example, payment
// details incomplete)
setErrorMessage(error.message);
} else {
// Your customer will be redirected to your `return_url`. For some payment
// methods like iDEAL, your customer will be redirected to an intermediate
// site first to authorize the payment, then redirected to the `return_url`.
}
};
return (
<form onSubmit={handleSubmit}>
<PaymentElement />
<button type="submit" disabled={!stripe || !elements}>
Pay
</button>
{/* Show error message to your customers */}
{errorMessage && <div>{errorMessage}</div>}
</form>
);
};
const stripePromise = loadStripe('YOUR_TEST_PUBLISHABLE_KEY');
const options = {
mode: 'payment',
amount: 1099,
currency: 'usd',
// Fully customizable with appearance API.
appearance: {
/*...*/
},
};
const StripeComponent = () => (
<Elements stripe={stripePromise} options={options}>
<CheckoutForm />
</Elements>
);
export default StripeComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment