1 ---
2 sidebar_label: "Saved Payment Methods"
3 tags:
4 - payment
5 - server
6 - tutorial
7 - nextjs
8 keywords:
9 - saved payment methods
10 - stripe
11 - payment provider
12 - checkout
13 - nextjs
14 products:
15 - payment
16 ---
17
18 import { Github, PlaySolid, EllipsisHorizontal } from "@medusajs/icons"
19 import { Prerequisites, Card, InlineIcon } from "docs-ui"
20
21 export const metadata = {
22 title: `Use Saved Payment Methods During Checkout`,
23 keywords: [
24 "saved payment methods",
25 "stripe",
26 "payment provider",
27 "checkout",
28 "nextjs",
29 ]
30 }
31
32 # {metadata.title}
33
34 In this tutorial, you'll learn how to allow customers to save their payment methods and use them for future purchases.
35
36 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. The Medusa application's commerce features are built around [Commerce Modules](../../../commerce-modules/page.mdx) which are available out-of-the-box.
37
38 Medusa's architecture facilitates integrating third-party services, such as payment providers. These payment providers can process payments and securely store customers' payment methods for future use.
39
40 In this tutorial, you'll expand on Medusa's [Stripe Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx) to allow customers to re-use their saved payment methods during checkout.
41
42 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
43
44 <Note>
45
46 While this tutorial uses Stripe as an example, you can follow the same steps to implement saved payment methods with other payment providers.
47
48 </Note>
49
50 ## Summary
51
52 By following this tutorial, you'll learn how to:
53
54 - Install and set up Medusa and the Next.js Starter Storefront.
55 - Set up the Stripe Module Provider in Medusa.
56 - Customize the checkout flow to save customers' payment methods.
57 - Allow customers to select saved payment methods during checkout.
58
59 ![Diagram illustrating the features of this guide](https://res.cloudinary.com/dza7lstvk/image/upload/v1745309355/Medusa%20Resources/saved-payment-methods_orjnix.jpg)
60
61 <Card
62 href="https://github.com/medusajs/examples/tree/main/stripe-saved-payment"
63 title="Saved Payment Methods Repository"
64 text="Find the full code for this guide in this repository."
65 icon={Github}
66 />
67
68 ---
69
70 ## Step 1: Install a Medusa Application
71
72 <Prerequisites items={[
73 {
74 text: "Node.js v20.19.0+ or v22.12.0+",
75 link: "https://nodejs.org/en/download"
76 },
77 {
78 text: "Git CLI tool",
79 link: "https://git-scm.com/downloads"
80 },
81 {
82 text: "PostgreSQL",
83 link: "https://www.postgresql.org/download/"
84 }
85 ]} />
86
87 Start by installing the Medusa application on your machine with the following command:
88
89 ```bash npx2yarnExec
90 npx create-medusa-app@latest
91 ```
92
93 You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose Yes.
94
95 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.
96
97 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. Afterwards, you can log in with the new user and explore the dashboard.
98
99 <Note title="Ran into Errors">
100
101 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
102
103 </Note>
104
105 <Note>
106
107 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
108
109 </Note>
110
111 ---
112
113 ## Step 2: Set Up the Stripe Module Provider
114
115 Medusa's [Payment Module](../../../commerce-modules/payment/page.mdx) provides payment-related models and the interface to manage and process payments. However, it delegates the actual payment processing to module providers that integrate third-party payment services.
116
117 The [Stripe Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx) is a Payment Module Provider that integrates Stripe into your Medusa application to process payments. It can also save payment methods securely.
118
119 In this section, you'll set up the Stripe Module Provider in your Medusa application.
120
121 <Prerequisites
122 items={[
123 {
124 text: "Stripe account",
125 link: "https://stripe.com/"
126 },
127 {
128 text: "Stripe Secret and Public API Keys",
129 link: "https://support.stripe.com/questions/locate-api-keys-in-the-dashboard"
130 },
131 ]}
132 />
133
134 ### Register the Stripe Module Provider
135
136 To register the Stripe Module Provider in your Medusa application, add it to the array of providers passed to the Payment Module in `medusa-config.ts`:
137
138 ```ts title="medusa-config.ts"
139 module.exports = defineConfig({
140 // ...
141 modules: [
142 {
143 resolve: "@medusajs/medusa/payment",
144 options: {
145 providers: [
146 {
147 resolve: "@medusajs/medusa/payment-stripe",
148 id: "stripe",
149 options: {
150 apiKey: process.env.STRIPE_API_KEY,
151 },
152 },
153 ],
154 },
155 },
156 ],
157 })
158 ```
159
160 The Medusa configuration accepts a `modules` array, which contains the modules to be loaded. While the Payment Module is loaded by default, you need to add it again when registering a new provider.
161
162 You register provides in the `providers` option of the Payment Module. Each provider is an object with the following properties:
163
164 - `resolve`: The package name of the provider.
165 - `id`: The ID of the provider. This is used to identify the provider in the Medusa application.
166 - `options`: The options to be passed to the provider. In this case, the `apiKey` option is required for the Stripe Module Provider.
167
168 <Note>
169
170 Learn about other options in the [Stripe Module Provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx#module-options) documentation.
171
172 </Note>
173
174 ### Add Environment Variables
175
176 Next, add the following environment variables to your `.env` file:
177
178 ```plain
179 STRIPE_API_KEY=sk_...
180 ```
181
182 Where `STRIPE_API_KEY` is your Stripe Secret API Key. You can find it in the Stripe dashboard under Developers > API keys.
183
184 ![Secret API Key in the Stripe dashboard](https://res.cloudinary.com/dza7lstvk/image/upload/v1745313823/Medusa%20Resources/Screenshot_2025-04-22_at_12.20.08_PM_w6rxxo.png)
185
186 ### Enable Stripe in a Region
187
188 In Medusa, each [region](../../../commerce-modules/region/page.mdx) (which is a geographical area where your store operates) can have different payment methods enabled. So, after registering the Stripe Module Provider, you need to enable it in a region.
189
190 To enable it in a region, start the Medusa application with the following command:
191
192 ```bash npm2yarn
193 npm run dev
194 ```
195
196 Then, go to `localhost:9000/app` and log in with the user you created earlier.
197
198 Once you're logged in:
199
200 1. Go to Settings -> Regions.
201 2. Click on the region where you want to enable the payment provider.
202 3. Click the <InlineIcon Icon={EllipsisHorizontal} alt="three-dots" /> icon at the top right of the first section
203 4. Choose "Edit" from the dropdown menu
204 5. In the side window that opens, find the "Payment Providers" field and select Stripe from the dropdown.
205 6. Once you're done, click the "Save" button.
206
207 Stripe will now be available as a payment option during checkout.
208
209 <Note>
210
211 The Stripe Module Provider supports different payment methods in Stripe, such as Bancontact or iDEAL. This guide focuses only on the card payment method, but you can enable other payment methods as well.
212
213 </Note>
214
215 ![Stripe in the dropdown](https://res.cloudinary.com/dza7lstvk/image/upload/v1745245433/Medusa%20Resources/Screenshot_2025-04-21_at_5.23.07_PM_yd7xji.png)
216
217 ### Add Evnironement Variable to Storefront
218
219 The [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) supports payment with Stripe during checkout if it's enabled in the region.
220
221 <Note title="Reminder" forceMultiline>
222
223 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
224
225 ```bash
226 cd apps/storefront
227 ```
228
229 </Note>
230
231 In the Next.js Starter Storefront project, add the Stripe public API key as an environment variable in `.env.local`:
232
233 ```plain badgeLabel="Storefront" badgeColor="blue"
234 NEXT_PUBLIC_STRIPE_KEY=pk_123...
235 ```
236
237 Where `NEXT_PUBLIC_STRIPE_KEY` is your Stripe public API key. You can find it in the Stripe dashboard under Developers > API keys.
238
239 ---
240
241 ## Step 3: List Payment Methods API Route
242
243 The Payment Module uses [account holders](../../../commerce-modules/payment/account-holder/page.mdx) to represent a customer's details that are stored in a third-party payment provider. Medusa creates an account holder for each customer, allowing you later to retrieve the customer's saved payment methods in the third-party provider.
244
245 ![Diagram illustrating the relation between customers and account holders in Medusa, and customers in Stripe](https://res.cloudinary.com/dza7lstvk/image/upload/v1745314344/Medusa%20Resources/customer-account-stripe_in5ei6.jpg)
246
247 While this feature is available out-of-the-box, you need to expose it to clients, like storefronts, by creating an [API route](!docs!/learn/fundamentals/api-routes). An API Route is an endpoint that exposes commerce features to external applications and clients.
248
249 In this step, you'll create an API route that lists the saved payment methods for an authenticated customer.
250
251 <Note>
252
253 Refer to the [API routes](!docs!/learn/fundamentals/api-routes) documentation to learn more.
254
255 </Note>
256
257 ### Create API Route
258
259 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`, and it can include path parameters using square brackets.
260
261 So, to create an API route at the path `/store/payment-methods/:account-holder-id`, create the file `src/api/store/payment-methods/[account_holder_id]/route.ts` with the following content:
262
263 export const apiRouteHighlights = [
264 ["13", "query", "Resolve Query from the Medusa container"],
265 ["16", "paymentModuleService", "Resolve the Payment Module's service from the Medusa container."],
266 ["20", "accountHolder", "Retrieve the account holder by its ID."],
267 ["38", "paymentMethods", "Retrieve the saved payment methods in the account holder's provider."]
268 ]
269
270 ```ts title="src/api/store/payment-methods/[account_holder_id]/route.ts" highlights={apiRouteHighlights}
271 import {
272 MedusaError,
273 Modules,
274 ContainerRegistrationKeys,
275 } from "@medusajs/framework/utils"
276 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
277
278 export async function GET(
279 req: MedusaRequest,
280 res: MedusaResponse
281 ) {
282 const { account_holder_id } = req.params
283 const query = req.scope.resolve(
284 ContainerRegistrationKeys.QUERY
285 )
286 const paymentModuleService = req.scope.resolve(
287 Modules.PAYMENT
288 )
289
290 const { data: [accountHolder] } = await query.graph({
291 entity: "account_holder",
292 fields: [
293 "data",
294 "provider_id",
295 ],
296 filters: {
297 id: account_holder_id,
298 },
299 })
300
301 if (!accountHolder) {
302 throw new MedusaError(
303 MedusaError.Types.NOT_FOUND,
304 "Account holder not found"
305 )
306 }
307
308 const paymentMethods = await paymentModuleService.listPaymentMethods(
309 {
310 provider_id: accountHolder.provider_id,
311 context: {
312 account_holder: {
313 data: {
314 id: accountHolder.data.id,
315 },
316 },
317 },
318 }
319 )
320
321 res.json({
322 payment_methods: paymentMethods,
323 })
324 }
325 ```
326
327 Since you export a route handler function named `GET`, you expose a `GET` API route at `/store/payment-methods/:account-holder-id`. The route handler function accepts two parameters:
328
329 1. A request object with details and context on the request, such as body parameters or authenticated customer details.
330 2. A response object to manipulate and send the response.
331
332 The request object has a `scope` property, which is an instance of the [Medusa container](!docs!/learn/fundamentals/medusa-container). The Medusa container is a registry of Framework and commerce tools that you can access in the API route.
333
334 You use the Medusa container to resolve:
335
336 - [Query](!docs!/learn/fundamentals/query), which is a tool that retrieves data across modules in the Medusa application.
337 - The [Payment Module](../../../commerce-modules/payment/page.mdx)'s service, which provides an interface to manage and process payments with third-party providers.
338
339 You use Query to retrieve the account holder with the ID passed as a path parameter. If the account holder is not found, you throw an error.
340
341 Then, you use the [listPaymentMethods](/references/payment/listPaymentMethods) method of the Payment Module's service to retrieve the payment providers saved in the third-party provider. The method accepts an object with the following properties:
342
343 - `provider_id`: The ID of the provider, such as Stripe's ID. The account holder stores the ID its associated provider.
344 - `context`: The context of the request. In this case, you pass the account holder's ID to retrieve the payment methods associated with it in the third-party provider.
345
346 Finally, you return the payment methods in the response.
347
348 ### Protect API Route
349
350 Only authenticated customers can access and use saved payment methods. So, you need to protect the API route to ensure that only authenticated customers can access it.
351
352 To protect an API route, you can add a [middleware](!docs!/learn/fundamentals/api-routes/middlewares). A middleware is a function executed when a request is sent to an API Route. You can add an authentication middleware that ensures that the request is authenticated before executing the route handler function.
353
354 <Note>
355
356 Refer to the [Middlewares](!docs!/learn/fundamentals/api-routes/middlewares) documentation to learn more.
357
358 </Note>
359
360 Middlewares are added in the `src/api/middlewares.ts` file. So, create the file with the following content:
361
362 ```ts title="src/api/middlewares.ts"
363 import { authenticate, defineMiddlewares } from "@medusajs/framework/http"
364
365 export default defineMiddlewares({
366 routes: [
367 {
368 matcher: "/store/payment-methods/:provider_id/:account_holder_id",
369 method: "GET",
370 middlewares: [
371 authenticate("customer", ["bearer", "session"]),
372 ],
373 },
374 ],
375 })
376 ```
377
378 The `src/api/middlewares.ts` file must use the `defineMiddlewares` function and export its result. The `defineMiddlewares` function accepts a `routes` array that accepts objects with the following properties:
379
380 - `matcher`: The path of the API route to apply the middleware to.
381 - `method`: The HTTP method of the API route to apply the middleware to.
382 - `middlewares`: An array of middlewares to apply to the API route.
383
384 You apply the `authenticate` middleware to the API route you created earlier. The `authenticate` middleware ensures that only authenticated customers can access the API route.
385
386 <Note>
387
388 Refer to the [Protected Routes](!docs!/learn/fundamentals/api-routes/protected-routes) documentation to learn more about the `authenticate` middleware.
389
390 </Note>
391
392 Your API route can now only be accessed by authenticated customers. You'll test it out as you customize the Next.js Starter Storefront in the next steps.
393
394 ---
395
396 ## Step 4: Save Payment Methods During Checkout
397
398 In this step, you'll customize the checkout flow in the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) to save payment methods during checkout.
399
400 <Note title="Reminder" forceMultiline>
401
402 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
403
404 ```bash
405 cd apps/storefront
406 ```
407
408 </Note>
409
410 During checkout, when the customer chooses a payment method, such as Stripe, the Next.js Starter Storefront creates a [payment session](../../../commerce-modules/payment/payment-session/page.mdx) in Medusa using the [Initialize Payment Session](!api!/store/payment-collections/initialize-payment-session) API route.
411
412 Under the hood, Medusa uses the associated payment provider (Stripe) to initiate the payment process with the associated third-party payment provider. The [Initialize Payment Session](!api!/store/payment-collections/initialize-payment-session) API route accepts a `data` object parameter in the request body that allows you to pass data relevant to the third-party payment provider.
413
414 So, to save the payment method that the customer uses during checkout with Stripe, you must pass the `setup_future_usage` property in the `data` object. The `setup_future_usage` property is a Stripe-specific property that allows you to save the payment method for future use.
415
416 In `src/modules/checkout/components/payment/index.tsx` of the Next.js Starter Storefront, there are two uses of the `initiatePaymentSession` function. Update each of them to pass the `data` property:
417
418 ```ts title="src/modules/checkout/components/payment/index.tsx" badgeLabel="Storefront" badgeColor="blue"
419 // update in two places
420 await initiatePaymentSession(cart, {
421 // ...
422 data: {
423 setup_future_usage: "off_session",
424 },
425 })
426 ```
427
428 You customize the `initiatePaymentSession` function to pass the `data` object with the `setup_future_usage` property. You set the value to `off_session` to allow using the payment method outside of the checkout flow, such as for follow up payments. You can use `on_session` instead if you only want the payment method to be used by the customer during checkout.
429
430 <Note>
431
432 By making this change, you always save the payment method that the customer uses during checkout. You can alternatively show a checkbox to confirm saving the payment method, and only pass the `data` object if the customer checks it.
433
434 </Note>
435
436 ### Test it Out
437
438 To test it out, start the Medusa application by running the following command in the `apps/backend` directory:
439
440 ```bash npm2yarn
441 npm run dev
442 ```
443
444 Then, start the Next.js Starter Storefront by running the following command in the storefront's directory:
445
446 ```bash npm2yarn
447 npm run dev
448 ```
449
450 You can open the storefront in your browser at `localhost:8000`. Then, create a new customer account by clicking on the "Account" link at the top right.
451
452 After creating an account and logging in, add a product to the cart and go to the checkout page. Once you get to the payment step, choose Stripe and enter a [test card number](https://docs.stripe.com/testing#cards), such as `4242 4242 4242 4242`.
453
454 Then, place the order. Once the order is placed, you can check on the Stripe dashboard that the payment method was saved by:
455
456 1. Going to the "Customers" section in the Stripe dashboard.
457 2. Clicking on the customer you just placed the order with.
458 3. Scrolling down to the "Payment methods" section. You'll find the payment method you just used to place the order.
459
460 ![Saved payment method on the Stripe dashboard](https://res.cloudinary.com/dza7lstvk/image/upload/v1745249064/Medusa%20Resources/Screenshot_2025-04-21_at_6.24.00_PM_peotrd.png)
461
462 In the next step, you'll show the saved payment methods to the customer during checkout and allow them to select one of them.
463
464 ---
465
466 ## Step 5: Use Saved Payment Methods During Checkout
467
468 In this step, you'll customize the checkout flow in the Next.js Starter Storefront to show the saved payment methods to the customer and allow them to select one of them to place the order.
469
470 ### Retrieve Saved Payment Methods
471
472 To retrieve the saved payment methods, you'll add a server function that retrieves the customer's saved payment methods from the API route you created earlier.
473
474 Add the following in `src/lib/data/payment.ts`:
475
476 export const paymentHighlights = [
477 ["1", "SavedPaymentMethod", "Define a type for the saved payment methods."],
478 ["2", "id", "The ID of the payment method\nin the third-party provider."],
479 ["3", "provider_id", "The ID of the provider in the Medusa application,\nsuch as Stripe's ID."],
480 ["4", "data", "Additional data retrieved from the third-party provider\nrelated to the saved payment method."],
481 ["14", "getSavedPaymentMethods", "Create a function to retrieve the saved payment methods."],
482 ]
483
484 ```ts title="src/lib/data/payment.ts" badgeLabel="Storefront" badgeColor="blue" highlights={paymentHighlights}
485 export type SavedPaymentMethod = {
486 id: string
487 provider_id: string
488 data: {
489 card: {
490 brand: string
491 last4: string
492 exp_month: number
493 exp_year: number
494 }
495 }
496 }
497
498 export const getSavedPaymentMethods = async (accountHolderId: string) => {
499 const headers = {
500 ...(await getAuthHeaders()),
501 }
502
503 return sdk.client.fetch<{
504 payment_methods: SavedPaymentMethod[]
505 }>(
506 `/store/payment-methods/${accountHolderId}`,
507 {
508 method: "GET",
509 headers,
510 }
511 ).catch(() => {
512 return {
513 payment_methods: [],
514 }
515 })
516 }
517 ```
518
519 You define a type for the retrieved payment methods. It contains the following properties:
520
521 - `id`: The ID of the payment method in the third-party provider.
522 - `provider_id`: The ID of the provider in the Medusa application, such as Stripe's ID.
523 - `data`: Additional data retrieved from the third-party provider related to the saved payment method. The type is modeled after the data returned by Stripe, but you can change it to match other payment providers.
524
525 You also create a `getSavedPaymentMethods` function that retrieves the saved payment methods from the API route you created earlier. The function accepts the account holder ID as a parameter and returns the saved payment methods.
526
527 ### Add Saved Payment Methods Component
528
529 Next, you'll add the component that shows the saved payment methods and allows the customer to select one of them.
530
531 The component that shows the Stripe card element is defined in `src/modules/checkout/components/payment-container/index.tsx`. So, you'll define the component for the saved payment methods in the same file.
532
533 Start by adding the following import statements at the top of the file:
534
535 {/* eslint-disable @medusajs/import-from-framework-not-internal */}
536
537 ```ts title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue"
538 import { Button } from "@medusajs/ui"
539 import { useEffect, useState } from "react"
540 import { HttpTypes } from "@medusajs/types"
541 import { SavedPaymentMethod, getSavedPaymentMethods } from "@lib/data/payment"
542 import { initiatePaymentSession } from "../../../../lib/data/cart"
543 import { capitalize } from "lodash"
544 ```
545
546 Then, update the `PaymentContainerProps` type to include the payment session and cart details:
547
548 ```ts title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue"
549 type PaymentContainerProps = {
550 // ...
551 paymentSession?: HttpTypes.StorePaymentSession
552 cart: HttpTypes.StoreCart
553 }
554 ```
555
556 You'll need these details to find which saved payment method the customer selected, and to initiate a new payment session for the cart when the customer chooses a saved payment method.
557
558 Next, add the following component at the end of the file:
559
560 export const stripeSavedPaymentMethodsHighlights = [
561 ["2", "paymentSession", "The currently selected payment session."],
562 ["3", "setCardComplete", "Function to indicate that payment step is completed."],
563 ["4", "setCardBrand", "Function to set the brand of the selected payment method."],
564 ["5", "setError", "Function to set any error message."],
565 ["6", "cart", "The cart's details."],
566 ["14", "savedPaymentMethods", "State variable to store the saved payment methods."],
567 ["17", "selectedPaymentMethod", "State variable to store the selected payment method."],
568 ["23", "useEffect", "Hook to retrieve the saved payment methods."],
569 ["39", "useEffect", "Hook to perform actions after a payment method is selected."],
570 ["59", "handleSelect", "Function to handle the selection of a saved payment method."],
571 ]
572
573 ```tsx title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={stripeSavedPaymentMethodsHighlights}
574 const StripeSavedPaymentMethodsContainer = ({
575 paymentSession,
576 setCardComplete,
577 setCardBrand,
578 setError,
579 cart,
580 }: {
581 paymentSession?: HttpTypes.StorePaymentSession
582 setCardComplete: (complete: boolean) => void
583 setCardBrand: (brand: string) => void
584 setError: (error: string | null) => void
585 cart: HttpTypes.StoreCart
586 }) => {
587 const [savedPaymentMethods, setSavedPaymentMethods] = useState<
588 SavedPaymentMethod[]
589 >([])
590 const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<
591 string | null
592 >(
593 paymentSession?.data?.payment_method as string | null
594 )
595
596 useEffect(() => {
597 const accountHolderId = (
598 paymentSession?.context?.account_holder as Record<string, string>
599 )
600 ?.id
601
602 if (!accountHolderId) {
603 return
604 }
605
606 getSavedPaymentMethods(accountHolderId)
607 .then(({ payment_methods }) => {
608 setSavedPaymentMethods(payment_methods)
609 })
610 }, [paymentSession])
611
612 useEffect(() => {
613 if (!selectedPaymentMethod || !savedPaymentMethods.length) {
614 setCardComplete(false)
615 setCardBrand("")
616 setError(null)
617 return
618 }
619 const selectedMethod = savedPaymentMethods.find(
620 (method) => method.id === selectedPaymentMethod
621 )
622
623 if (!selectedMethod) {
624 return
625 }
626
627 setCardBrand(capitalize(selectedMethod.data.card.brand))
628 setCardComplete(true)
629 setError(null)
630 }, [selectedPaymentMethod, savedPaymentMethods])
631
632 const handleSelect = async (method: SavedPaymentMethod) => {
633 // initiate a new payment session with the selected payment method
634 await initiatePaymentSession(cart, {
635 provider_id: method.provider_id,
636 data: {
637 payment_method: method.id,
638 },
639 }).catch((error) => {
640 setError(error.message)
641 })
642
643 setSelectedPaymentMethod(method.id)
644 }
645
646 if (!savedPaymentMethods.length) {
647 return <></>
648 }
649
650 // TODO add return statement
651 }
652 ```
653
654 You define a `StripeSavedPaymentMethodsContainer` component that accepts the following props:
655
656 - `paymentSession`: The cart's current payment session.
657 - `setCardComplete`: A function to tell parent components whether the cart or payment method selection is complete. This allows the customer to proceed to the next step in the checkout flow.
658 - `setCardBrand`: A function to set the brand of the selected payment method. This is useful to show the brand of the selected payment method in review sections of the checkout flow.
659 - `setError`: A function to set the error message in case of an error.
660 - `cart`: The cart's details.
661
662 In the component, you define a state variable to store the saved payment methods and another one to store the selected payment method.
663
664 Then, you use the `useEffect` hook to retrieve the saved payment methods for the account holder set in the cart's payment session. You use the `getSavedPaymentMethods` function you created earlier to retrieve the saved payment methods.
665
666 You also use another `useEffect` hook that is executed when the selected payment method changes. In this hook, you check if the selected payment method is valid and set the card brand and completion status accordingly.
667
668 Finally, you define a `handleSelect` function that you'll execute when the customer selects a saved payment method. It creates a new payment session with the selected payment method.
669
670 To show the saved payment methods, replace the `TODO` with the following `return` statement:
671
672 ```tsx title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue"
673 return (
674 <div className="flex flex-col gap-y-2">
675 <Text className="txt-medium-plus text-ui-fg-base">
676 Choose a saved payment method:
677 </Text>
678 {savedPaymentMethods.map((method) => (
679 <div
680 key={method.id}
681 className={`flex items-center justify-between p-4 border rounded-lg cursor-pointer hover:border-ui-border-interactive ${
682 selectedPaymentMethod === method.id ? "border-ui-border-interactive" : ""
683 }`}
684 role="button"
685 onClick={() => handleSelect(method)}
686 >
687 <div className="flex items-center gap-x-4">
688 <input
689 type="radio"
690 name="saved-payment-method"
691 value={method.id}
692 checked={selectedPaymentMethod === method.id}
693 className="h-4 w-4 text-ui-fg-interactive"
694 onChange={(e) => {
695 if (e.target.checked) {
696 handleSelect(method)
697 }
698 }}
699 />
700 <div className="flex flex-col">
701 <span className="text-sm font-medium text-ui-fg-base">
702 {capitalize(method.data.card.brand)} •••• {method.data.card.last4}
703 </span>
704 <span className="text-xs text-ui-fg-subtle">
705 Expires {method.data.card.exp_month}/{method.data.card.exp_year}
706 </span>
707 </div>
708 </div>
709 </div>
710 ))}
711 </div>
712 )
713 ```
714
715 You display the saved payment methods as radio buttons. When the customer selects one of them, you execute the `handleSelect` function to initiate a new payment session with the selected payment method.
716
717 ### Modify Existing Stripe Element
718
719 Now that you have the component to show the saved payment methods, you need to modify the existing Stripe element to allow customers to select an existing payment method or enter a new one.
720
721 In the same `src/modules/checkout/components/payment-container/index.tsx` file, expand the new `paymentSession` and `cart` props of the `StripeCardContainer` component:
722
723 ```ts title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue"
724 export const StripeCardContainer = ({
725 // ...
726 paymentSession,
727 cart,
728 }: Omit<PaymentContainerProps, "children"> & {
729 // ...
730 }) => {
731 // ...
732 }
733 ```
734
735 Then, add a new state variable that keeps track of whether the customer is using a saved payment method or entering a new one:
736
737 ```ts title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue"
738 const [isUsingSavedPaymentMethod, setIsUsingSavedPaymentMethod] = useState(
739 paymentSession?.data?.payment_method !== null
740 )
741 ```
742
743 Next, add a function that resets the payment session when the customer switches between saved and new payment methods:
744
745 ```ts title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue"
746 const handleRefreshSession = async () => {
747 await initiatePaymentSession(cart, {
748 provider_id: paymentProviderId,
749 })
750 setIsUsingSavedPaymentMethod(false)
751 }
752 ```
753
754 This function initiates a new payment session for the cart and disables the `isUsingSavedPaymentMethod` state variable.
755
756 Finally, replace the `return` statement of the `StripeCardContainer` component with the following:
757
758 export const stripeCardReturnHighlights = [
759 ["7", "paymentSession", "Pass new prop."],
760 ["8", "cart", "Pass new prop."],
761 ["13", "StripeSavedPaymentMethodsContainer", "Add the new component for saved payment methods."],
762 ["21", "Button", "Show a button to switch back to entering a new payment method."],
763 ]
764
765 ```tsx title="src/modules/checkout/components/payment-container/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={stripeCardReturnHighlights}
766 return (
767 <PaymentContainer
768 paymentProviderId={paymentProviderId}
769 selectedPaymentOptionId={selectedPaymentOptionId}
770 paymentInfoMap={paymentInfoMap}
771 disabled={disabled}
772 paymentSession={paymentSession}
773 cart={cart}
774 >
775 {selectedPaymentOptionId === paymentProviderId &&
776 (stripeReady ? (
777 <div className="my-4 transition-all duration-150 ease-in-out">
778 <StripeSavedPaymentMethodsContainer
779 setCardComplete={setCardComplete}
780 setCardBrand={setCardBrand}
781 setError={setError}
782 paymentSession={paymentSession}
783 cart={cart}
784 />
785 {isUsingSavedPaymentMethod && (
786 <Button
787 variant="secondary"
788 size="small"
789 className="mt-2"
790 onClick={handleRefreshSession}
791 >
792 Use a new payment method
793 </Button>
794 )}
795 {!isUsingSavedPaymentMethod && (
796 <>
797 <Text className="txt-medium-plus text-ui-fg-base my-1">
798 Enter your card details:
799 </Text>
800 <CardElement
801 options={useOptions as StripeCardElementOptions}
802 onChange={(e) => {
803 setCardBrand(
804 e.brand && e.brand.charAt(0).toUpperCase() + e.brand.slice(1)
805 )
806 setError(e.error?.message || null)
807 setCardComplete(e.complete)
808 }}
809 />
810 </>
811 )}
812 </div>
813 ) : (
814 <SkeletonCardDetails />
815 ))}
816 </PaymentContainer>
817 )
818 ```
819
820 You update the `return` statement to:
821
822 - Pass the new `paymentSession` and `cart` props to the `PaymentContainer` component.
823 - Show the `StripeSavedPaymentMethodsContainer` component before Stripe's card element.
824 - Add a button that's shown when the customer selects a saved payment method. The button allows the customer to switch back to entering a new payment method.
825
826 The existing Stripe element in checkout will now show the saved payment methods to the customer along with the component to enter a card's details.
827
828 Since you added new props to the `StripeCardContainer` and `PaymentContainer` components, you need to update other components that use them to pass the props.
829
830 In `src/modules/checkout/components/payment/index.tsx`, find usages of `StripeCardContainer` and `PaymentContainer` in the return statement and add the `paymentSession` and `cart` props:
831
832 ```tsx title="src/modules/checkout/components/payment/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={[["5"], ["6"], ["11"], ["12"]]}
833 <div key={paymentMethod.id}>
834 {isStripeFunc(paymentMethod.id) ? (
835 <StripeCardContainer
836 // ...
837 paymentSession={activeSession}
838 cart={cart}
839 />
840 ) : (
841 <PaymentContainer
842 // ...
843 paymentSession={activeSession}
844 cart={cart}
845 />
846 )}
847 </div>
848 ```
849
850 ### Support Updating Stripe's Client Secret
851
852 The Next.js Starter Storefront uses Stripe's `Elements` component to wrap the payment elements. The `Elements` component requires a `clientSecret` prop, which is available in the cart's payment session.
853
854 With the recent changes, the client secret will be updated whenever a payment session is initiated, such as when the customer selects a saved payment method. However, the `options.clientSecret` prop of the `Elements` component is immutable, meaning that it cannot be changed after the component is mounted.
855
856 To force the component to re-mount and update the `clientSecret` prop, you can add a `key` prop to the `Elements` component. The `key` prop ensures that the `Elements` component re-mounts whenever the client secret changes, allowing Stripe to process the updated payment session.
857
858 In `src/modules/checkout/components/payment-wrapper/stripe-wrapper.tsx`, find the `Elements` component in the `return` statement and add the `key` prop:
859
860 ```tsx title="src/modules/checkout/components/payment-wrapper/stripe-wrapper.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={[["4"]]}
861 <Elements
862 options={options}
863 stripe={stripePromise}
864 key={options.clientSecret}
865 >
866 {children}
867 </Elements>
868 ```
869
870 You set the `key` prop to the client secret, which forces the `Elements` component to re-mount whenever the client secret changes.
871
872 ### Support Payment with Saved Payment Method
873
874 The last change you need to make ensures that the customer can place an order with a saved payment method.
875
876 When the customer places the order, and they've chosen Stripe as a payment method, the Next.js Starter Storefront uses Stripe's `confirmCardPayment` method to confirm the payment. This method accepts either the ID of a saved payment method, or the details of a new card.
877
878 So, you need to update the `confirmCardPayment` usage to support passing the ID of the selected payment method if the customer has selected one.
879
880 In `src/modules/checkout/components/payment-button/index.tsx`, find the `handlePayment` method and update its first `if` condition:
881
882 ```ts title="src/modules/checkout/components/payment-button/index.tsx" badgeLabel="Storefront" badgeColor="blue"
883 if (!stripe || !elements || (!card && !session?.data.payment_method) || !cart) {
884 setSubmitting(false)
885 return
886 }
887 ```
888
889 This allows the customer to place their order if they have selected a saved payment method but have not entered a new card.
890
891 Then, find the usage of `confirmCardPayment` in the `handlePayment` function and change it to the following:
892
893 export const confirmPaymentHighlights = [
894 ["3", "payment_method", "Pass either the ID of a saved payment method\nor the details of a new card."],
895 ]
896
897 ```ts title="src/modules/checkout/components/payment-button/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={confirmPaymentHighlights}
898 await stripe
899 .confirmCardPayment(session?.data.client_secret as string, {
900 payment_method: session?.data.payment_method as string || {
901 card: card!,
902 billing_details: {
903 name:
904 cart.billing_address?.first_name +
905 " " +
906 cart.billing_address?.last_name,
907 address: {
908 city: cart.billing_address?.city ?? undefined,
909 country: cart.billing_address?.country_code ?? undefined,
910 line1: cart.billing_address?.address_1 ?? undefined,
911 line2: cart.billing_address?.address_2 ?? undefined,
912 postal_code: cart.billing_address?.postal_code ?? undefined,
913 state: cart.billing_address?.province ?? undefined,
914 },
915 email: cart.email,
916 phone: cart.billing_address?.phone ?? undefined,
917 },
918 },
919 })
920 .then(({ error, paymentIntent }) => {
921 if (error) {
922 const pi = error.payment_intent
923
924 if (
925 (pi && pi.status === "requires_capture") ||
926 (pi && pi.status === "succeeded")
927 ) {
928 onPaymentCompleted()
929 }
930
931 setErrorMessage(error.message || null)
932 return
933 }
934
935 if (
936 (paymentIntent && paymentIntent.status === "requires_capture") ||
937 paymentIntent.status === "succeeded"
938 ) {
939 return onPaymentCompleted()
940 }
941
942 return
943 })
944 ```
945
946 In particular, you're changing the `payment_method` property to either be the ID of the selected payment method, or the details of a new card. This allows the customer to place an order with either a saved payment method or a new one.
947
948 ### Test it Out
949
950 You can now test out placing orders with a saved payment method.
951
952 To do that, start the Medusa application by running the following command in the `apps/backend` directory:
953
954 ```bash npm2yarn
955 npm run dev
956 ```
957
958 Then, start the Next.js Starter Storefront by running the following command in the storefront's directory:
959
960 ```bash npm2yarn
961 npm run dev
962 ```
963
964 In the Next.js Starter Storefront, login with the customer account you created earlier and add a product to the cart.
965
966 Then, proceed to the checkout flow. In the payment step, you should see the saved payment method you used earlier. You can select it and place the order.
967
968 ![Saved payment method in checkout](https://res.cloudinary.com/dza7lstvk/image/upload/v1745308047/Medusa%20Resources/Screenshot_2025-04-21_at_4.07.34_PM_krudjq.png)
969
970 Once the order is placed successfully, you can check it in the Medusa Admin dashboard. You can view the order and capture the payment.
971
972 ![Order in the Medusa Admin dashboard](https://res.cloudinary.com/dza7lstvk/image/upload/v1745318042/Medusa%20Resources/Screenshot_2025-04-22_at_1.33.39_PM_uynlfp.png)
973
974 ---
975
976 ## Next Steps
977
978 You've added support for saved payment methods in your Medusa application and Next.js Starter Storefront, allowing customers to save their payment methods during checkout and use them in future orders.
979
980 You can add more features to the saved payment methods, such as allowing customers to delete saved payment methods. You can use [Stripe's APIs](https://docs.stripe.com/api/payment_methods/detach) in the storefront or add an [API route](!docs!/learn/fundamentals/api-routes) in Medusa to delete the saved payment method.
981
982 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
983
984 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).