Stripe hosted checkout: Front-end
The frontend receives the sessionID and uses this id to redirect the user to the stripe checkout page.
The front-end needs to be packaged as follows:
- stripe package:
npm i @stripe/stripe-js
- react stripe:
npm i @stripe/react-stripe-js
Then set the publish key as an environment variable and set REACT_APP_PUBLISHABLE_KEY in .env.
- stripe package:
Introduce package, configure Stripe
In the front-end code, first introduce Elements & loadStripe in the outermost root component src/index.js, and then create stripePromise. After that, wrap
<Elements>
around the<App/>
component and pass in the stripePromise parameter. This way we can use stripe objects in arbitrary components.1
2
3
4
5
6
7
8
9
10
11
12
13import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js;'
const stripePromise = loadStripe(process.env.REACT_APP_PUBLISHABLE_KEY)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Elements stripe={stripePromise}>
<App />
</Elements>
</React.StrictMode>
);After setting, you need to restart the project.
Create checkout component
We need to complete a checkout component to help users jump to the Stripe hosted checkout page.
1
2
3
4
5
6
7
8
9
10
11
12
13const dataObj = { line_items: line_items, customer_email: "blhxp1@gmail.com", orderId: orderId };
axios({
method: 'POST',
url: '/payment/create-checkout-session',
data: dataObj
}).then(response => {
const { sessionId } = response.data;
stripe.redirectToCheckout({
sessionId
})
}).catch(err => {
console.log(err)
});
Create payment success and payment cancel pages
We need to create payment success and payment cancel, which are used to help users jump back to our website after completing the payment.
If we want to carry order information in these two pages, we need to put the data ID into the url from the Stripe backend:
1
2success_url: `${process.env.DOMAIN}/payment?status=success&orderId=${order_Id}`,
cancel_url: `${process.env.DOMAIN}/payment?status=failure&orderId=${order_Id}`,
How the front-end receives the id
For React, the frontend can use
useLocation()
to receive the id.For Next.js, the front end can use the SSR method and pass in the context parameter to receive the id.
1
2
3export const getServerSideProps: GetServerSideProps = async (context) => {
const { orderId, status } = context.query;
}