Raw
1 ---
2 tags:
3 - storefront
4 - name: payment
5 label: Customize Stripe in Next.js Starter
6 products:
7 - payment
8 ---
9
10 import { Prerequisites, InlineIcon } from "docs-ui"
11 import { EllipsisHorizontal } from "@medusajs/icons"
12
13 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1734007558/Medusa%20Resources/integrations-stripe_qfnwtf.jpg"
14
15 export const metadata = {
16 title: `Use Stripe's Payment Element in the Next.js Starter Storefront`,
17 openGraph: {
18 images: [
19 {
20 url: ogImage,
21 width: 800,
22 height: 450,
23 type: "image/jpeg"
24 }
25 ],
26 },
27 twitter: {
28 images: [
29 {
30 url: ogImage,
31 width: 800,
32 height: 450,
33 type: "image/jpeg"
34 }
35 ]
36 }
37 }
38
39 # {metadata.title}
40
41 In this tutorial, you'll learn how to customize the Next.js Starter Storefront to use [Stripe's Payment Element](https://docs.stripe.com/payments/payment-element).
42
43 By default, the Next.js Starter Storefront comes with a basic Stripe card payment integration. However, you can replace it with Stripe's Payment Element instead.
44
45 By using the Payment Element, you can offer a unified payment experience that supports various payment methods, including credit cards, PayPal, iDeal, and more, all within a single component.
46
47 ## Summary
48
49 By following this tutorial, you'll learn how to:
50
51 - Set up a Medusa application with the Stripe Module Provider.
52 - Customize the Next.js Starter Storefront to use Stripe's Payment Element.
53
54 ---
55
56 ## Step 1: Set Up Medusa Project
57
58 In this step, you'll set up a Medusa application and configure the Stripe Module Provider. You can skip this step if you already have a Medusa application running with the Stripe Module Provider configured.
59
60 ### a. Install Medusa Application
61
62 <Prerequisites items={[
63 {
64 text: "Node.js v20.19.0+ or v22.12.0+",
65 link: "https://nodejs.org/en/download"
66 },
67 {
68 text: "Git CLI tool",
69 link: "https://git-scm.com/downloads"
70 },
71 {
72 text: "PostgreSQL",
73 link: "https://www.postgresql.org/download/"
74 }
75 ]} />
76
77 To install the Medusa application, run the following command:
78
79 ```bash npx2yarnExec
80 npx create-medusa-app@latest
81 ```
82
83 You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `Y` for yes.
84
85 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
86
87 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form.
88
89 Afterwards, you can log in with the new user and explore the dashboard. The Next.js Starter Storefront is also running at `http://localhost:8000`.
90
91 <Note title="Ran into Errors?">
92
93 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
94
95 </Note>
96
97 <Note>
98
99 In this guide, all backend customizations are relative to the `apps/backend` directory of your project, and all storefront customizations are relative to the `apps/storefront` directory.
100
101 </Note>
102
103 ### b. Configure Stripe Module Provider
104
105 Next, you'll configure the [Stripe Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx) in your Medusa application. The Stripe Module Provider allows you to accept payments through Stripe in your Medusa application.
106
107 <Prerequisites items={[
108 {
109 text: "Stripe account↗",
110 link: "https://stripe.com"
111 },
112 {
113 text: "Stripe Secret API Key",
114 link: "https://support.stripe.com/questions/locate-api-keys-in-the-dashboard"
115 }
116 ]} />
117
118 The Stripe Module Provider is installed by default in your application. To use it, add it to the array of providers passed to the Payment Module in `medusa-config.ts`:
119
120 ```ts title="medusa-config.ts" badgeLabel="Medusa Application" badgeColor="green"
121 module.exports = defineConfig({
122 // ...
123 modules: [
124 {
125 resolve: "@medusajs/medusa/payment",
126 options: {
127 providers: [
128 {
129 resolve: "@medusajs/medusa/payment-stripe",
130 id: "stripe",
131 options: {
132 apiKey: process.env.STRIPE_API_KEY,
133 },
134 },
135 ],
136 },
137 },
138 ],
139 })
140 ```
141
142 For more details about other available options and the webhook URLs that Medusa provides, refer to the [Stripe Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx) documentation.
143
144 ### c. Set Environment Variables
145
146 Next, make sure to add the necessary environment variables for the above options in `.env` in your Medusa application:
147
148 ```bash badgeLabel="Medusa Application" badgeColor="green"
149 STRIPE_API_KEY=<YOUR_STRIPE_API_KEY>
150 ```
151
152 Where `<YOUR_STRIPE_API_KEY>` is your Stripe [Secret API Key](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard).
153
154 You also need to add the Stripe [Publishable API Key](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard) in the Next.js Starter Storefront's environment variables:
155
156 ```bash badgeLabel="Storefront" badgeColor="blue"
157 NEXT_PUBLIC_STRIPE_KEY=<YOUR_STRIPE_PUBLISHABLE_API_KEY>
158 ```
159
160 Where `<YOUR_STRIPE_PUBLISHABLE_API_KEY>` is your Stripe [Publishable API Key](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard).
161
162 ### d. Enable Stripe in a Region
163
164 Finally, you need to add Stripe as a payment provider to one or more regions in your Medusa Admin. This will allow customers to use Stripe as a payment method during checkout.
165
166 To do that:
167
168 1. Log in to your Medusa Admin dashboard at `http://localhost:9000/app`.
169 2. Go to Settings -> Regions.
170 3. Select a region you want to enable Stripe for (or create a new one).
171 4. Click the <InlineIcon Icon={EllipsisHorizontal} alt="three-dots" /> icon on the upper right corner.
172 5. Choose "Edit" from the dropdown menu.
173 6. In the Payment Providers field, select “Stripe (STRIPE)”
174 7. Click the Save button.
175
176 Do this for all regions you want to enable Stripe for.
177
178 ---
179
180 ## Step 2: Update Payment Step in Checkout
181
182 You'll start customizing the Next.js Starter Storefront by updating the payment step in the checkout process. By default, the payment step is implemented to show all available payment methods in the region the customer is in, and allows the customer to select one of them.
183
184 In this step, you'll replace the current payment method selection with Stripe's Payment Element. You'll no longer need to handle different payment methods separately, as the Payment Element will automatically adapt to the available methods configured in your Stripe account.
185
186 ### a. Update the Stripe SDKs
187
188 To ensure you have the latest Stripe packages, update the `@stripe/react-stripe-js` and `@stripe/stripe-js` packages in your Next.js Starter Storefront:
189
190 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
191 npm install @stripe/react-stripe-js@latest @stripe/stripe-js@latest
192 ```
193
194 ### b. Update the Payment Component
195
196 The `Payment` component in `src/modules/checkout/components/payment/index.tsx` shows the payment step in checkout. It handles the payment method selection and submission. You'll update this component first to use the Payment Element.
197
198 <Note>
199
200 The full final code is available at the end of the section.
201
202 </Note>
203
204 First, add the following imports at the top of the file:
205
206 ```tsx title="src/modules/checkout/components/payment/index.tsx"
207 // ...other imports
208 import { useContext } from "react"
209 import { PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
210 import { StripePaymentElementChangeEvent } from "@stripe/stripe-js"
211 import { StripeContext } from "../payment-wrapper/stripe-wrapper"
212 ```
213
214 You import components from the Stripe SDKs, and the `StripeContext` created in the `StripeWrapper` component. This context will allow you to check whether Stripe is ready to be used.
215
216 Next, in the `Payment` component, replace the existing state variables with the following:
217
218 ```tsx title="src/modules/checkout/components/payment/index.tsx"
219 const [isLoading, setIsLoading] = useState(false)
220 const [error, setError] = useState<string | null>(null)
221 const [stripeComplete, setStripeComplete] = useState(false)
222 const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>("")
223
224 const stripeReady = useContext(StripeContext)
225 const stripe = stripeReady ? useStripe() : null
226 const elements = stripeReady ? useElements() : null
227 ```
228
229 You define the following variables:
230
231 - `isLoading`: A boolean that indicates whether the payment is being processed.
232 - `error`: A string that holds any error message related to the payment.
233 - `stripeComplete`: A boolean that indicates whether operations with the Stripe Payment Element are complete. When this is enabled, the customer can proceed to the "Review" checkout step.
234 - `selectedPaymentMethod`: A string that holds the currently selected payment method in the Payment Element. For example, `card` or `eps`.
235 - `stripeReady`: A boolean that indicates whether Stripe is ready to be used, fetched from the `StripeContext`.
236 - This context is defined in `src/modules/checkout/components/payment-wrapper/stripe-wrapper.tsx` and it wraps the checkout page in Stripe's `Elements` component, which initializes the Stripe SDKs.
237 - `stripe`: The Stripe instance, which is used to interact with the Stripe API. It's only initialized if `stripeReady` from the Stripe context is true.
238 - `elements`: The Stripe Elements instance, which is used to manage the Payment Element. It's also only initialized if `stripeReady` is true.
239
240 Next, add the following function to the `Payment` component to handle changes in the Payment Element:
241
242 ```tsx title="src/modules/checkout/components/payment/index.tsx"
243 const handlePaymentElementChange = async (
244 event: StripePaymentElementChangeEvent
245 ) => {
246 // Catches the selected payment method and sets it to state
247 if (event.value.type) {
248 setSelectedPaymentMethod(event.value.type)
249 }
250
251 // Sets stripeComplete on form completion
252 setStripeComplete(event.complete)
253
254 // Clears any errors on successful completion
255 if (event.complete) {
256 setError(null)
257 }
258 }
259 ```
260
261 This function will be called on every change in Stripe's Payment Element, such as when the customer selects a payment method.
262
263 In the function, you update the `selectedPaymentMethod` state with the type of payment method selected by the customer, set `stripeComplete` to true when the payment element is complete, and clear any error messages when the payment element is complete.
264
265 Then, to customize the payment step's submission, replace the `handleSubmit` function with the following:
266
267 ```tsx title="src/modules/checkout/components/payment/index.tsx"
268 const handleSubmit = async () => {
269 setIsLoading(true)
270 setError(null)
271
272 try {
273 // Check if the necessary context is ready
274 if (!stripe || !elements) {
275 setError("Payment processing not ready. Please try again.")
276 return
277 }
278
279 // Submit the payment method details
280 await elements.submit().catch((err) => {
281 console.error(err)
282 setError(err.message || "An error occurred with the payment")
283 return
284 })
285
286 // Navigate to the final checkout step
287 router.push(pathname + "?" + createQueryString("step", "review"), {
288 scroll: false,
289 })
290 } catch (err: any) {
291 setError(err.message)
292 } finally {
293 setIsLoading(false)
294 }
295 }
296 ```
297
298 In this function, you use the `elements.submit()` method to submit the payment method details entered by the customer in the Payment Element. This doesn't actually confirm the payment yet; it just prepares the payment method for confirmation.
299
300 Once the payment method is submitted successfully, you navigate the customer to the Review step of the checkout process.
301
302 Next, to make sure a payment session is initialized when the customer reaches the payment step, add the following to the `Payment` component:
303
304 ```tsx title="src/modules/checkout/components/payment/index.tsx"
305 const initStripe = async () => {
306 try {
307 await initiatePaymentSession(cart, {
308 // TODO: change the provider ID if using a different ID in medusa-config.ts
309 provider_id: "pp_stripe_stripe",
310 })
311 } catch (err) {
312 console.error("Failed to initialize Stripe session:", err)
313 setError("Failed to initialize payment. Please try again.")
314 }
315 }
316
317 useEffect(() => {
318 if (!activeSession && isOpen) {
319 initStripe()
320 }
321 }, [cart, isOpen, activeSession])
322 ```
323
324 You add an `initStripe` function that initiates a payment session in the Medusa server. Notice that you set the provider ID to `pp_stripe_stripe`, which is the ID of the Stripe payment provider in your Medusa application if the ID in `medusa-config.ts` is `stripe`.
325
326 If you used a different ID, change the `stripe` in the middle accordingly. For example, if you set the ID to `payment`, you would set the `provider_id` to `pp_payment_stripe`.
327
328 You also add a `useEffect` hook that calls `initStripe` when the payment step is opened and there is no active payment session.
329
330 You'll now update the component's return statement to render the Payment Element.
331
332 First, find the following lines in the return statement:
333
334 ```tsx title="src/modules/checkout/components/payment/index.tsx"
335 {!paidByGiftcard && availablePaymentMethods?.length && (
336 <>
337 <RadioGroup
338 value={selectedPaymentMethod}
339 onChange={(value: string) => setPaymentMethod(value)}
340 >
341 {/* ... */}
342 </RadioGroup>
343 </>
344 )}
345 ```
346
347 And replace them with the following:
348
349 ```tsx title="src/modules/checkout/components/payment/index.tsx"
350 {!paidByGiftcard &&
351 availablePaymentMethods?.length &&
352 stripeReady && (
353 <div className="mt-5 transition-all duration-150 ease-in-out">
354 <PaymentElement
355 onChange={handlePaymentElementChange}
356 options={{
357 layout: "accordion",
358 }}
359 />
360 </div>
361 )
362 }
363 ```
364
365 You replace the radio group with the payment methods available in Medusa with the `PaymentElement` component from the Stripe SDK. You pass it the following props:
366
367 - `onChange`: A callback function that is called when the payment element's state changes. You pass the `handlePaymentElementChange` function you defined earlier.
368 - `options`: An object that contains options for the payment element, such as the `layout`. Refer to [Stripe's documentation](https://docs.stripe.com/payments/payment-element#options) for other options available.
369
370 Next, find the button rendered afterward and replace it with the following:
371
372 ```tsx title="src/modules/checkout/components/payment/index.tsx"
373 <Button
374 size="large"
375 className="mt-6"
376 onClick={handleSubmit}
377 isLoading={isLoading}
378 disabled={
379 !stripeComplete ||
380 !stripe ||
381 !elements ||
382 (!selectedPaymentMethod && !paidByGiftcard)
383 }
384 data-testid="submit-payment-button"
385 >
386 Continue to review
387 </Button>
388 ```
389
390 You update the button's `disabled` condition and text.
391
392 After that, to ensure the customer can only proceed to the review step if a payment method is selected, find the following lines in the return statement:
393
394 ```tsx title="src/modules/checkout/components/payment/index.tsx"
395 {cart && paymentReady && activeSession ? (
396 // rest of code...
397 )}
398 ```
399
400 And replace them with the following:
401
402 ```tsx title="src/modules/checkout/components/payment/index.tsx"
403 {cart && paymentReady && activeSession && selectedPaymentMethod ? (
404 // rest of code...
405 )}
406 ```
407
408 You update the condition to also check if a payment method is selected within the Payment Element.
409
410 Finally, find the following lines in the return statement:
411
412 ```tsx title="src/modules/checkout/components/payment/index.tsx"
413 <Text>
414 {isStripeFunc(selectedPaymentMethod) && cardBrand
415 ? cardBrand
416 : "Another step will appear"}
417 </Text>
418 ```
419
420 And replace them with the following:
421
422 ```tsx
423 <Text>Another step may appear</Text>
424 ```
425
426 You show the same text for all payment methods since they're handled by Stripe's Payment Element.
427
428 You've now finished customizing the Payment step to show the Stripe Payment Element. This component will show the payment methods configured in your Stripe account.
429
430 <Note>
431
432 Feel free to remove unused imports, variables, and functions in the file.
433
434 </Note>
435
436 <Details summaryContent="Full updated code for src/modules/checkout/components/payment/index.tsx">
437
438 ```tsx title="src/modules/checkout/components/payment/index.tsx"
439 "use client"
440
441 import { isStripe as isStripeFunc, paymentInfoMap } from "@lib/constants"
442 import { initiatePaymentSession } from "@lib/data/cart"
443 import { CheckCircleSolid, CreditCard } from "@medusajs/icons"
444 import { Button, Container, Heading, Text, clx } from "@medusajs/ui"
445 import ErrorMessage from "@modules/checkout/components/error-message"
446 import Divider from "@modules/common/components/divider"
447 import { usePathname, useRouter, useSearchParams } from "next/navigation"
448 import { useCallback, useContext, useEffect, useState } from "react"
449 import { PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
450 import { StripePaymentElementChangeEvent } from "@stripe/stripe-js"
451 import { StripeContext } from "../payment-wrapper/stripe-wrapper"
452
453 const Payment = ({
454 cart,
455 availablePaymentMethods,
456 }: {
457 cart: any
458 availablePaymentMethods: any[]
459 }) => {
460 const activeSession = cart.payment_collection?.payment_sessions?.find(
461 (paymentSession: any) => paymentSession.status === "pending"
462 )
463 const stripeReady = useContext(StripeContext)
464
465 const [isLoading, setIsLoading] = useState(false)
466 const [error, setError] = useState<string | null>(null)
467 const [stripeComplete, setStripeComplete] = useState(false)
468 const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>("")
469
470 const stripe = stripeReady ? useStripe() : null
471 const elements = stripeReady ? useElements() : null
472
473 const searchParams = useSearchParams()
474 const router = useRouter()
475 const pathname = usePathname()
476
477 const isOpen = searchParams.get("step") === "payment"
478
479 const handlePaymentElementChange = async (
480 event: StripePaymentElementChangeEvent
481 ) => {
482 // Catches the selected payment method and sets it to state
483 if (event.value.type) {
484 setSelectedPaymentMethod(event.value.type)
485 }
486
487 // Sets stripeComplete on form completion
488 setStripeComplete(event.complete)
489
490 // Clears any errors on successful completion
491 if (event.complete) {
492 setError(null)
493 }
494 }
495
496 const setPaymentMethod = async (method: string) => {
497 setError(null)
498 setSelectedPaymentMethod(method)
499 if (isStripeFunc(method)) {
500 await initiatePaymentSession(cart, {
501 provider_id: method,
502 })
503 }
504 }
505
506 const paidByGiftcard =
507 cart?.gift_cards && cart?.gift_cards?.length > 0 && cart?.total === 0
508
509 const paymentReady =
510 (activeSession && cart?.shipping_methods.length !== 0) || paidByGiftcard
511
512 const createQueryString = useCallback(
513 (name: string, value: string) => {
514 const params = new URLSearchParams(searchParams)
515 params.set(name, value)
516
517 return params.toString()
518 },
519 [searchParams]
520 )
521
522 const handleEdit = () => {
523 router.push(pathname + "?" + createQueryString("step", "payment"), {
524 scroll: false,
525 })
526 }
527
528 const handleSubmit = async () => {
529 setIsLoading(true)
530 setError(null)
531
532 try {
533 // Check if the necessary context is ready
534 if (!stripe || !elements) {
535 setError("Payment processing not ready. Please try again.")
536 return
537 }
538
539 // Submit the payment method details
540 await elements.submit().catch((err) => {
541 console.error(err)
542 setError(err.message || "An error occurred with the payment")
543 return
544 })
545
546 // Navigate to the final checkout step
547 router.push(pathname + "?" + createQueryString("step", "review"), {
548 scroll: false,
549 })
550 } catch (err: any) {
551 setError(err.message)
552 } finally {
553 setIsLoading(false)
554 }
555 }
556
557 const initStripe = async () => {
558 try {
559 await initiatePaymentSession(cart, {
560 provider_id: "pp_stripe_stripe",
561 })
562 } catch (err) {
563 console.error("Failed to initialize Stripe session:", err)
564 setError("Failed to initialize payment. Please try again.")
565 }
566 }
567
568 useEffect(() => {
569 if (!activeSession && isOpen) {
570 initStripe()
571 }
572 }, [cart, isOpen, activeSession])
573
574 useEffect(() => {
575 setError(null)
576 }, [isOpen])
577
578 return (
579 <div className="bg-white">
580 <div className="flex flex-row items-center justify-between mb-6">
581 <Heading
582 level="h2"
583 className={clx(
584 "flex flex-row text-3xl-regular gap-x-2 items-baseline",
585 {
586 "opacity-50 pointer-events-none select-none":
587 !isOpen && !paymentReady,
588 }
589 )}
590 >
591 Payment
592 {!isOpen && paymentReady && <CheckCircleSolid />}
593 </Heading>
594 {!isOpen && paymentReady && (
595 <Text>
596 <button
597 onClick={handleEdit}
598 className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover"
599 data-testid="edit-payment-button"
600 >
601 Edit
602 </button>
603 </Text>
604 )}
605 </div>
606 <div>
607 <div className={isOpen ? "block" : "hidden"}>
608 {!paidByGiftcard &&
609 availablePaymentMethods?.length &&
610 stripeReady && (
611 <div className="mt-5 transition-all duration-150 ease-in-out">
612 <PaymentElement
613 onChange={handlePaymentElementChange}
614 options={{
615 layout: "accordion",
616 }}
617 />
618 </div>
619 )
620 }
621
622 {paidByGiftcard && (
623 <div className="flex flex-col w-1/3">
624 <Text className="txt-medium-plus text-ui-fg-base mb-1">
625 Payment method
626 </Text>
627 <Text
628 className="txt-medium text-ui-fg-subtle"
629 data-testid="payment-method-summary"
630 >
631 Gift card
632 </Text>
633 </div>
634 )}
635
636 <ErrorMessage
637 error={error}
638 data-testid="payment-method-error-message"
639 />
640
641 <Button
642 size="large"
643 className="mt-6"
644 onClick={handleSubmit}
645 isLoading={isLoading}
646 disabled={
647 !stripeComplete ||
648 !stripe ||
649 !elements ||
650 (!selectedPaymentMethod && !paidByGiftcard)
651 }
652 data-testid="submit-payment-button"
653 >
654 Continue to review
655 </Button>
656 </div>
657
658 <div className={isOpen ? "hidden" : "block"}>
659 {cart && paymentReady && activeSession && selectedPaymentMethod ? (
660 <div className="flex items-start gap-x-1 w-full">
661 <div className="flex flex-col w-1/3">
662 <Text className="txt-medium-plus text-ui-fg-base mb-1">
663 Payment method
664 </Text>
665 <Text
666 className="txt-medium text-ui-fg-subtle"
667 data-testid="payment-method-summary"
668 >
669 {paymentInfoMap[activeSession?.provider_id]?.title ||
670 activeSession?.provider_id}
671 </Text>
672 </div>
673 <div className="flex flex-col w-1/3">
674 <Text className="txt-medium-plus text-ui-fg-base mb-1">
675 Payment details
676 </Text>
677 <div
678 className="flex gap-2 txt-medium text-ui-fg-subtle items-center"
679 data-testid="payment-details-summary"
680 >
681 <Container className="flex items-center h-7 w-fit p-2 bg-ui-button-neutral-hover">
682 {paymentInfoMap[selectedPaymentMethod]?.icon || (
683 <CreditCard />
684 )}
685 </Container>
686 <Text>Another step may appear</Text>
687 </div>
688 </div>
689 </div>
690 ) : paidByGiftcard ? (
691 <div className="flex flex-col w-1/3">
692 <Text className="txt-medium-plus text-ui-fg-base mb-1">
693 Payment method
694 </Text>
695 <Text
696 className="txt-medium text-ui-fg-subtle"
697 data-testid="payment-method-summary"
698 >
699 Gift card
700 </Text>
701 </div>
702 ) : null}
703 </div>
704 </div>
705 <Divider className="mt-8" />
706 </div>
707 )
708 }
709
710 export default Payment
711 ```
712
713 </Details>
714
715 ### c. Add Icons and Titles for Payment Methods
716
717 After a customer enters their payment details and proceeds to the Review step, the payment method is displayed in the collapsed Payment step.
718
719 To ensure the correct icon and title are shown for your payment methods configured through Stripe, you can add them in the `paymentInfoMap` object defined in `src/lib/constants.tsx`.
720
721 For example:
722
723 ```tsx title="src/lib/constants.tsx"
724 export const paymentInfoMap: Record<
725 string,
726 { title: string; icon: React.JSX.Element }
727 > = {
728 // ...
729 card: {
730 title: "Credit card",
731 icon: <CreditCard />,
732 },
733 paypal: {
734 title: "PayPal",
735 icon: <PayPal />,
736 },
737 }
738 ```
739
740 For every payment method you want to customize its display, add an entry in the `paymentInfoMap` object. The key should match the [type enum in Stripe's Payment Element](https://docs.stripe.com/api/payment_methods/object#payment_method_object-type), and the value is an object with the following properties:
741
742 - `title`: The title to display for the payment method.
743 - `icon`: A JSX element representing the icon for the payment method. You can use icons from [Medusa UI](!ui!/icons/overview) or custom icons.
744
745 ### Test it out
746
747 Before you test out the payment checkout step, make sure you have the necessary [payment methods configured in Stripe](https://docs.stripe.com/payments/payment-methods/overview).
748
749 Then, follow these steps to test the payment checkout step in your Next.js Starter Storefront:
750
751 1. Start the Medusa application with the following command:
752
753 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
754 npm run dev
755 ```
756
757 2. Start the Next.js Starter Storefront with the following command:
758
759 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
760 npm run dev
761 ```
762
763 3. Open the storefront at `http://localhost:8000` in your browser.
764 4. Go to Menu -> Store, choose a product, and add it to the cart.
765 5. Proceed to checkout by clicking the cart icon in the top right corner, then click "Go to checkout".
766 6. Complete the Address and Delivery steps that are before the Payment step.
767 7. Once you reach the Payment step, your Stripe Payment Element should appear and list the different payment methods you’ve enabled in your Stripe account.
768
769 At this point, you can proceed to the Review step, but you can't confirm the payment with Stripe and place an order in Medusa. You'll customize the payment button in the next step to handle the payment confirmation with Stripe.
770
771 ![The Stripe Payment Element allows you to pay with different payment methods like PayPal](https://res.cloudinary.com/dza7lstvk/image/upload/v1734005395/Medusa%20Resources/Screenshot_2024-12-10_at_18.04.52_wemqwg.jpg)
772
773 ---
774
775 ## Step 3: Update the Payment Button
776
777 Next, you'll update the payment button in the Review step of the checkout process. This button is used to confirm the payment with Stripe, then place the order in Medusa.
778
779 In this step, you'll customize the `PaymentButton` component in `src/modules/checkout/components/payment-button/index.tsx` to support confirming the payment with Stripe's Payment Element.
780
781 <Note>
782
783 The full final code is available at the end of the section.
784
785 </Note>
786
787 Start by adding the following imports at the top of the file:
788
789 ```tsx title="src/modules/checkout/components/payment-button/index.tsx"
790 // ...other imports
791 import { useEffect } from "react"
792 import { useParams, usePathname, useRouter } from "next/navigation"
793 ```
794
795 Then, in the `StripePaymentButton` component, add the following variables:
796
797 ```tsx title="src/modules/checkout/components/payment-button/index.tsx"
798 const { countryCode } = useParams()
799 const router = useRouter()
800 const pathname = usePathname()
801 const paymentSession = cart.payment_collection?.payment_sessions?.find(
802 // TODO change the provider_id if using a different ID in medusa-config.ts
803 (session) => session.provider_id === "pp_stripe_stripe"
804 )
805 ```
806
807 You define the following variables:
808
809 - `countryCode`: The country code of the customer's region, fetched from the URL. You'll use this later to create Stripe's redirect URL.
810 - `router`: The Next.js router instance. You'll use this to redirect back to the payment step if necessary.
811 - `pathname`: The current pathname. You'll use this when redirecting back to the payment step if necessary.
812 - `paymentSession`: The Medusa payment session for the Stripe payment provider. This is used to get the `clientSecret` needed to confirm the payment.
813 - Notice that the provider ID is set to `pp_stripe_stripe`, which is the ID of the Stripe payment provider in your Medusa application if the ID in `medusa-config.ts` is `stripe`. If you used a different ID, change the `stripe` in the middle accordingly.
814
815 After that, change the `handlePayment` function to the following:
816
817 ```tsx title="src/modules/checkout/components/payment-button/index.tsx"
818 const handlePayment = async () => {
819 if (!stripe || !elements || !cart) {
820 return
821 }
822 setSubmitting(true)
823
824 const { error: submitError } = await elements.submit()
825 if (submitError) {
826 setErrorMessage(submitError.message || null)
827 setSubmitting(false)
828 return
829 }
830
831 const clientSecret = paymentSession?.data?.client_secret as string
832
833 await stripe
834 .confirmPayment({
835 elements,
836 clientSecret,
837 confirmParams: {
838 return_url: `${
839 window.location.origin
840 }/api/capture-payment/${cart.id}?country_code=${countryCode}`,
841 payment_method_data: {
842 billing_details: {
843 name:
844 cart.billing_address?.first_name +
845 " " +
846 cart.billing_address?.last_name,
847 address: {
848 city: cart.billing_address?.city ?? undefined,
849 country: cart.billing_address?.country_code ?? undefined,
850 line1: cart.billing_address?.address_1 ?? undefined,
851 line2: cart.billing_address?.address_2 ?? undefined,
852 postal_code: cart.billing_address?.postal_code ?? undefined,
853 state: cart.billing_address?.province ?? undefined,
854 },
855 email: cart.email,
856 phone: cart.billing_address?.phone ?? undefined,
857 },
858 },
859 },
860 redirect: "if_required",
861 })
862 .then(({ error, paymentIntent }) => {
863 if (error) {
864 const pi = error.payment_intent
865
866 if (
867 (pi && pi.status === "requires_capture") ||
868 (pi && pi.status === "succeeded")
869 ) {
870 onPaymentCompleted()
871 return
872 }
873
874 setErrorMessage(error.message || null)
875 setSubmitting(false)
876 return
877 }
878
879 if (
880 paymentIntent.status === "requires_capture" ||
881 paymentIntent.status === "succeeded"
882 ) {
883 onPaymentCompleted()
884 }
885 })
886 }
887 ```
888
889 In the function, you:
890
891 - Ensure that the `stripe`, `elements`, and `cart` are available before proceeding.
892 - Set the `submitting` state to true to indicate that the payment is being processed.
893 - Use `elements.submit()` to submit the payment method details that the customer enters in the Payment Element. This ensures all necessary payment details are entered.
894 - Use `stripe.confirmPayment()` to confirm the payment with Stripe. You pass it the following details:
895 - `elements`: The Stripe Elements instance that contains the Payment Element.
896 - `clientSecret`: The client secret from the payment session, which is used to confirm the payment.
897 - `confirmParams`: An object that contains the parameters for confirming the payment.
898 - `return_url`: The URL to redirect the customer to after the payment is confirmed. This redirect URL is useful when using providers like PayPal, where the customer is redirected to complete the payment externally. You'll create the route in your Next.js Starter Storefront in the next step.
899 - `payment_method_data`: An object that contains the billing details of the customer.
900 - `redirect`: The redirect behavior for the payment confirmation. By setting `redirect: "if_required"`, you'll only redirect to the `return_url` if the payment is completed externally.
901 - Handle the response from `confirmPayment()`.
902 - If the payment is successful or requires capture, you call the `onPaymentCompleted` function to complete the payment and place the order.
903 - If an error occurred, you set the `errorMessage` state variable to show the error to the customer.
904
905 Finally, add the following `useEffect` hooks to the `StripePaymentButton` component:
906
907 ```tsx title="src/modules/checkout/components/payment-button/index.tsx"
908 useEffect(() => {
909 if (cart.payment_collection?.status === "authorized") {
910 onPaymentCompleted()
911 }
912 }, [cart.payment_collection?.status])
913
914 useEffect(() => {
915 elements?.getElement("payment")?.on("change", (e) => {
916 if (!e.complete) {
917 // redirect to payment step if not complete
918 router.push(pathname + "?step=payment", {
919 scroll: false,
920 })
921 }
922 })
923 }, [elements])
924 ```
925
926 You add two effects:
927
928 - An effect that runs when the status of the cart's payment collection changes. It triggers the `onPaymentCompleted` function to finalize the order placement when the payment collection status is `authorized`.
929 - An effect that listens for changes in the Payment Element. If the payment element is not complete, it redirects the customer back to the payment step. This is useful if the customer refreshes the page or navigates away, leading to incomplete payment details.
930
931 You've finalized changes to the `PaymentButton` component. Feel free to remove unused imports, variables, and functions in the file.
932
933 You still need to add the redirect URL route before you can test the payment button. You'll do that in the next step.
934
935 <Details summaryContent="Full updated code for src/modules/checkout/components/payment-button/index.tsx">
936
937 ```tsx title="src/modules/checkout/components/payment-button/index.tsx"
938 "use client"
939
940 import { isManual, isStripe } from "@lib/constants"
941 import { placeOrder } from "@lib/data/cart"
942 import { HttpTypes } from "@medusajs/types"
943 import { Button } from "@medusajs/ui"
944 import { useElements, useStripe } from "@stripe/react-stripe-js"
945 import React, { useState, useEffect } from "react"
946 import ErrorMessage from "../error-message"
947 import { useParams, usePathname, useRouter } from "next/navigation"
948
949
950 type PaymentButtonProps = {
951 cart: HttpTypes.StoreCart
952 "data-testid": string
953 }
954
955 const PaymentButton: React.FC<PaymentButtonProps> = ({
956 cart,
957 "data-testid": dataTestId,
958 }) => {
959 const notReady =
960 !cart ||
961 !cart.shipping_address ||
962 !cart.billing_address ||
963 !cart.email ||
964 (cart.shipping_methods?.length ?? 0) < 1
965
966 const paymentSession = cart.payment_collection?.payment_sessions?.[0]
967
968 switch (true) {
969 case isStripe(paymentSession?.provider_id):
970 return (
971 <StripePaymentButton
972 notReady={notReady}
973 cart={cart}
974 data-testid={dataTestId}
975 />
976 )
977 case isManual(paymentSession?.provider_id):
978 return (
979 <ManualTestPaymentButton notReady={notReady} data-testid={dataTestId} />
980 )
981 default:
982 return <Button disabled>Select a payment method</Button>
983 }
984 }
985
986 const StripePaymentButton = ({
987 cart,
988 notReady,
989 "data-testid": dataTestId,
990 }: {
991 cart: HttpTypes.StoreCart
992 notReady: boolean
993 "data-testid"?: string
994 }) => {
995 const [submitting, setSubmitting] = useState(false)
996 const [errorMessage, setErrorMessage] = useState<string | null>(null)
997
998 const { countryCode } = useParams()
999 const router = useRouter()
1000 const pathname = usePathname()
1001 const paymentSession = cart.payment_collection?.payment_sessions?.find(
1002 (session) => session.provider_id === "pp_stripe_stripe"
1003 )
1004
1005 const onPaymentCompleted = async () => {
1006 await placeOrder()
1007 .catch((err) => {
1008 setErrorMessage(err.message)
1009 })
1010 .finally(() => {
1011 setSubmitting(false)
1012 })
1013 }
1014
1015 const stripe = useStripe()
1016 const elements = useElements()
1017
1018 const disabled = !stripe || !elements ? true : false
1019
1020 const handlePayment = async () => {
1021 if (!stripe || !elements || !cart) {
1022 return
1023 }
1024
1025 setSubmitting(true)
1026
1027
1028 const { error: submitError } = await elements.submit()
1029 if (submitError) {
1030 setErrorMessage(submitError.message || null)
1031 setSubmitting(false)
1032 return
1033 }
1034
1035 const clientSecret = paymentSession?.data?.client_secret as string
1036
1037 await stripe
1038 .confirmPayment({
1039 elements,
1040 clientSecret,
1041 confirmParams: {
1042 return_url: `${window.location.origin}/api/capture-payment/${cart.id}?country_code=${countryCode}`,
1043 payment_method_data: {
1044 billing_details: {
1045 name:
1046 cart.billing_address?.first_name +
1047 " " +
1048 cart.billing_address?.last_name,
1049 address: {
1050 city: cart.billing_address?.city ?? undefined,
1051 country: cart.billing_address?.country_code ?? undefined,
1052 line1: cart.billing_address?.address_1 ?? undefined,
1053 line2: cart.billing_address?.address_2 ?? undefined,
1054 postal_code: cart.billing_address?.postal_code ?? undefined,
1055 state: cart.billing_address?.province ?? undefined,
1056 },
1057 email: cart.email,
1058 phone: cart.billing_address?.phone ?? undefined,
1059 },
1060 },
1061 },
1062 redirect: "if_required",
1063 })
1064 .then(({ error, paymentIntent }) => {
1065 if (error) {
1066 const pi = error.payment_intent
1067
1068 if (
1069 (pi && pi.status === "requires_capture") ||
1070 (pi && pi.status === "succeeded")
1071 ) {
1072 onPaymentCompleted()
1073 return
1074 }
1075
1076 setErrorMessage(error.message || null)
1077 setSubmitting(false)
1078 return
1079 }
1080
1081 if (
1082 paymentIntent.status === "requires_capture" ||
1083 paymentIntent.status === "succeeded"
1084 ) {
1085 onPaymentCompleted()
1086 }
1087 })
1088 }
1089
1090 useEffect(() => {
1091 if (cart.payment_collection?.status === "authorized") {
1092 onPaymentCompleted()
1093 }
1094 }, [cart.payment_collection?.status])
1095
1096 useEffect(() => {
1097 elements?.getElement("payment")?.on("change", (e) => {
1098 if (!e.complete) {
1099 // redirect to payment step if not complete
1100 router.push(pathname + "?step=payment", {
1101 scroll: false,
1102 })
1103 }
1104 })
1105 }, [elements])
1106
1107 return (
1108 <>
1109 <Button
1110 disabled={disabled || notReady}
1111 onClick={handlePayment}
1112 size="large"
1113 isLoading={submitting}
1114 data-testid={dataTestId}
1115 >
1116 Place order
1117 </Button>
1118 <ErrorMessage
1119 error={errorMessage}
1120 data-testid="stripe-payment-error-message"
1121 />
1122 </>
1123 )
1124 }
1125
1126 const ManualTestPaymentButton = ({ notReady }: { notReady: boolean }) => {
1127 const [submitting, setSubmitting] = useState(false)
1128 const [errorMessage, setErrorMessage] = useState<string | null>(null)
1129
1130 const onPaymentCompleted = async () => {
1131 await placeOrder()
1132 .catch((err) => {
1133 setErrorMessage(err.message)
1134 })
1135 .finally(() => {
1136 setSubmitting(false)
1137 })
1138 }
1139
1140 const handlePayment = () => {
1141 setSubmitting(true)
1142
1143 onPaymentCompleted()
1144 }
1145
1146 return (
1147 <>
1148 <Button
1149 disabled={notReady}
1150 isLoading={submitting}
1151 onClick={handlePayment}
1152 size="large"
1153 data-testid="submit-order-button"
1154 >
1155 Place order
1156 </Button>
1157 <ErrorMessage
1158 error={errorMessage}
1159 data-testid="manual-payment-error-message"
1160 />
1161 </>
1162 )
1163 }
1164
1165 export default PaymentButton
1166 ```
1167
1168 </Details>
1169
1170 ---
1171
1172 ## Step 4: Handle External Payment Callbacks
1173
1174 Some payment providers, such as PayPal, require the customers to perform actions on their portal before authorizing or confirming the payment. In those scenarios, you need an endpoint that the provider redirects the customer to complete their purchase.
1175
1176 In this step, you'll create an API route in your Next.js Starter Storefront that handles this use case. This route is the `return_url` route you passed to the `stripe.confirmPayment` earlier.
1177
1178 Create the file `src/app/api/capture-payment/[cartId]/route.ts` with the following content:
1179
1180 ```tsx title="src/app/api/capture-payment/[cartId]/route.ts"
1181 import { placeOrder, retrieveCart } from "@lib/data/cart"
1182 import { NextRequest, NextResponse } from "next/server"
1183
1184 type Params = Promise<{ cartId: string }>
1185
1186 export async function GET(req: NextRequest, { params }: { params: Params }) {
1187 const { cartId } = await params
1188 const { origin, searchParams } = req.nextUrl
1189
1190 const paymentIntent = searchParams.get("payment_intent")
1191 const paymentIntentClientSecret = searchParams.get(
1192 "payment_intent_client_secret"
1193 )
1194 const redirectStatus = searchParams.get("redirect_status") || ""
1195 const countryCode = searchParams.get("country_code")
1196
1197 const cart = await retrieveCart(cartId)
1198
1199 if (!cart) {
1200 return NextResponse.redirect(`${origin}/${countryCode}`)
1201 }
1202
1203 const paymentSession = cart.payment_collection?.payment_sessions?.find(
1204 (payment) => payment.data.id === paymentIntent
1205 )
1206
1207 if (
1208 !paymentSession ||
1209 paymentSession.data.client_secret !== paymentIntentClientSecret ||
1210 !["pending", "succeeded"].includes(redirectStatus) ||
1211 !["pending", "authorized"].includes(paymentSession.status)
1212 ) {
1213 return NextResponse.redirect(
1214 `${origin}/${countryCode}/cart?step=review&error=payment_failed`
1215 )
1216 }
1217
1218 const order = await placeOrder(cartId)
1219
1220 return NextResponse.redirect(
1221 `${origin}/${countryCode}/order/${order.id}/confirmed`
1222 )
1223 }
1224 ```
1225
1226 In this route, you validate that the payment intent and client secret match the cart's payment session data. If so, you place the order and redirect the customer to the order confirmation page.
1227
1228 If the payment failed or other validation checks fail, you redirect the customer back to the cart page with an error message.
1229
1230 Stripe will redirect the customer back to this route when using payment methods like PayPal.
1231
1232 ---
1233
1234 ### Test Payment Confirmation and Order placement
1235
1236 You can now test out the entire checkout flow with payment confirmation and order placement.
1237
1238 Start the Medusa application and the Next.js Starter Storefront as you did in the previous steps, and proceed to checkout.
1239
1240 In the payment step, select a payment method, such as card or PayPal. Fill out the necessary details in the Payment Element, then click the "Continue to review" button.
1241
1242 <Note title="Tip">
1243
1244 Find test cards in [Stripe's documentation](https://docs.stripe.com/testing#use-test-cards).
1245
1246 </Note>
1247
1248 After that, click the "Place order" button. If you selected a payment method that requires external confirmation, such as PayPal, you will be redirected to the PayPal payment page.
1249
1250 ![Example of handling payment through PayPal](https://res.cloudinary.com/dza7lstvk/image/upload/v1734006541/Medusa%20Resources/Screenshot_2024-12-10_at_19.27.13_q0w6u1.jpg)
1251
1252 Once the payment is confirmed and the order is placed, the customer will be redirected to the order confirmation page, where they can see the order details.
1253
1254 ### Test 3D Secure Payments
1255
1256 Stripe's Payment Element also supports 3D Secure payments. You can use one of [Stripe's test 3D Secure cards](https://docs.stripe.com/testing?testing-method=card-numbers#regulatory-cards) to test this feature.
1257
1258 When a customer uses a 3D Secure card, a pop-up will open prompting them to complete the authentication process. If successful, the order will be placed, and the customer will be redirected to the order confirmation page.
1259
1260 ![Stripe 3D Secure pop-up](https://res.cloudinary.com/dza7lstvk/image/upload/v1752577384/Medusa%20Resources/CleanShot_2025-07-15_at_11.12.44_2x_ibjxvx.png)
1261
1262 ### Server Webhook Verification
1263
1264 Webhook verification is useful to ensure that payment events are handled despite connection issues. The Stripe Module Provider in Medusa provides webhook verification out of the box, so you don't need to implement it yourself.
1265
1266 Learn more about the webhook API routes and how to configure them in the [Stripe Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx) guide.
1267
1268 ### Testing Declined Payments
1269
1270 You can use [Stripe's declined test cards](https://docs.stripe.com/testing#declined-payments) to test declined payments. When a payment is declined, the customer will be redirected back to the payment step to fix their payment details as necessary.