1 ---
2 tags:
3 - cart
4 - storefront
5 - payment
6 products:
7 - cart
8 - payment
9 ---
10
11 import { CodeTabs, CodeTab } from "docs-ui"
12
13 export const metadata = {
14 title: `Checkout Step 4: Choose Payment Provider`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to implement the last step of the checkout flow, where the customer chooses the payment provider and performs any necessary actions. This is typically the fourth step of the checkout flow, but you can change the steps of the checkout flow as you see fit.
20
21 ## Payment Step Flow in Storefront Checkout
22
23 The payment step requires implementing the following flow:
24
25 ![Storefront payment checkout flow diagram illustrating the complete payment process: retrieving available payment providers, customer selection of payment method, payment collection creation, session initialization, and showing the necessary UI to complete the payment](https://res.cloudinary.com/dza7lstvk/image/upload/v1718029777/Medusa%20Resources/storefront-payment_dxry7l.jpg)
26
27 1. Retrieve the payment providers using the [List Payment Providers API route](!api!/store/payment-providers/list-payment-providers).
28 2. Customer chooses the payment provider to use.
29 3. If the cart doesn't have an associated payment collection, create a payment collection for it using the [Create Payment Collection API route](!api!/store/payment-collections/create-payment-collection).
30 4. Initialize the payment sessions of the cart's payment collection using the [Initialize Payment Sessions API route](!api!/store/payment-collections/initialize-payment-session).
31 - If you're using the JS SDK, it combines the third and fourth steps in a single `initiatePaymentSession` function.
32 5. Optionally perform additional actions for payment based on the chosen payment provider. For example, if the customer chooses Stripe, you show them the UI to enter their card details.
33 - You can refer to the [Stripe guide](./stripe/page.mdx) for an example of how to implement this.
34
35 ---
36
37 ## How to Implement the Payment Step Flow
38
39 For example, to implement the payment step flow:
40
41 <Note title="Tip">
42
43 - This example uses the `useCart` hook defined in the [Cart React Context guide](../../cart/context/page.mdx).
44 - Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
45
46 </Note>
47
48 <CodeTabs group="store-request">
49 <CodeTab label="React" value="react">
50
51 export const highlights = [
52 ["4", "useCart", "The `useCart` hook was defined in the Cart React Context documentation."],
53 ["24", "listPaymentProviders", "Retrieve available payment providers."],
54 ["29", "setSelectedPaymentProvider", "If a payment provider was selected before, pre-fill it."],
55 ["35", "handleSelectProvider", "This function is executed when the customer submits their chosen payment provider."],
56 ["45", "initiatePaymentSession", "Create a payment collection and initialize the payment session for the chosen provider."],
57 ["50", "retrieve", "Retrieve the cart again to update its data."],
58 ["56", "getPaymentUi", "This function shows the necessary UI based on the selected payment provider."],
59 ["57", "activePaymentSession", "The active session is the first in the payment collection's sessions."],
60 ["62", "", "Test which payment provider is chosen based on the prefix of the provider ID."],
61 ["63", `"pp_stripe_"`, "Check if the chosen provider is Stripe."],
62 ["71", `"pp_system_default"`, "Check if the chosen provider is the default system provider."],
63 ["77", "default", "Handle unrecognized providers."],
64 ["112", "getPaymentUi", "If a provider is chosen, render its UI."]
65 ]
66
67 ```tsx highlights={highlights}
68 "use client" // include with Next.js 13+
69
70 import { useCallback, useEffect, useState } from "react"
71 import { useCart } from "@/providers/cart"
72 import { HttpTypes } from "@medusajs/types"
73 import { sdk } from "@/lib/sdk"
74
75 export default function CheckoutPaymentStep() {
76 const { cart, setCart } = useCart()
77 const [paymentProviders, setPaymentProviders] = useState<
78 HttpTypes.StorePaymentProvider[]
79 >([])
80 const [
81 selectedPaymentProvider,
82 setSelectedPaymentProvider,
83 ] = useState<string | undefined>()
84 const [loading, setLoading] = useState(false)
85
86 useEffect(() => {
87 if (!cart) {
88 return
89 }
90
91 sdk.store.payment.listPaymentProviders({
92 region_id: cart.region_id || "",
93 })
94 .then(({ payment_providers }) => {
95 setPaymentProviders(payment_providers)
96 setSelectedPaymentProvider(
97 cart.payment_collection?.payment_sessions?.[0]?.id
98 )
99 })
100 }, [cart])
101
102 const handleSelectProvider = async (
103 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
104 ) => {
105 e.preventDefault()
106 if (!cart || !selectedPaymentProvider) {
107 return
108 }
109
110 setLoading(true)
111
112 await sdk.store.payment.initiatePaymentSession(cart, {
113 provider_id: selectedPaymentProvider,
114 })
115
116 // re-fetch cart
117 const { cart: updatedCart } = await sdk.store.cart.retrieve(cart.id)
118
119 setCart(updatedCart)
120 setLoading(false)
121 }
122
123 const getPaymentUi = useCallback(() => {
124 const activePaymentSession = cart?.payment_collection?.payment_sessions?.[0]
125 if (!activePaymentSession) {
126 return
127 }
128
129 switch(true) {
130 case activePaymentSession.provider_id.startsWith("pp_stripe_"):
131 return (
132 <span>
133 You chose stripe!
134 {/* TODO add stripe UI */}
135 </span>
136 )
137 case activePaymentSession.provider_id
138 .startsWith("pp_system_default"):
139 return (
140 <span>
141 You chose manual payment! No additional actions required.
142 </span>
143 )
144 default:
145 return (
146 <span>
147 You chose {activePaymentSession.provider_id} which is
148 in development.
149 </span>
150 )
151 }
152 } , [cart])
153
154 return (
155 <div>
156 <form>
157 <select
158 value={selectedPaymentProvider}
159 onChange={(e) => setSelectedPaymentProvider(e.target.value)}
160 >
161 {paymentProviders.map((provider) => (
162 <option
163 key={provider.id}
164 value={provider.id}
165 >
166 {provider.id}
167 </option>
168 ))}
169 </select>
170 <button
171 disabled={loading}
172 onClick={async (e) => {
173 await handleSelectProvider(e)
174 }}
175 >
176 Submit
177 </button>
178 </form>
179 {getPaymentUi()}
180 </div>
181 )
182 }
183 ```
184
185 </CodeTab>
186 <CodeTab label="JS SDK" value="js-sdk">
187
188 export const fetchHighlights = [
189 ["8", "retrievePaymentProviders", "This function retrieves the payment provider that the customer can choose from."],
190 ["9", "listPaymentProviders", "Retrieve available payment providers."],
191 ["16", "selectPaymentProvider", "This function is executed when the customer submits their chosen payment provider."],
192 ["19", "initiatePaymentSession", "Create a payment collection and initialize the payment session for the chosen provider."],
193 ["26", "retrieve", "Retrieve the cart again to update its data."],
194 ["31", "getPaymentUi", "This function shows the necessary UI based on the selected payment provider."],
195 ["32", "activePaymentSession", "The active session is the first in the payment collection's sessions."],
196 ["38", "", "Test which payment provider is chosen based on the prefix of the provider ID."],
197 ["39", `"pp_stripe_"`, "Check if the chosen provider is Stripe."],
198 ["43", `"pp_system_default"`, "Check if the chosen provider is the default system provider."],
199 ["45", "default", "Handle unrecognized providers."],
200 ["52", "handlePayment", "The function that handles the payment process using the above functions."]
201 ]
202
203 ```ts highlights={fetchHighlights}
204 // assuming the cart is previously fetched
205 const cart = {
206 id: "cart_123",
207 region_id: "reg_123",
208 // cart object...
209 }
210
211 const retrievePaymentProviders = async () => {
212 const { payment_providers } = await sdk.store.payment.listPaymentProviders({
213 region_id: cart.region_id || "",
214 })
215
216 return payment_providers
217 }
218
219 const selectPaymentProvider = async (
220 selectedPaymentProviderId: string
221 ) => {
222 await sdk.store.payment.initiatePaymentSession(cart, {
223 provider_id: selectedPaymentProviderId,
224 })
225
226 // re-fetch cart
227 const {
228 cart: updatedCart,
229 } = await sdk.store.cart.retrieve(cart.id)
230
231 return updatedCart
232 }
233
234 const getPaymentUi = () => {
235 const activePaymentSession = cart?.payment_collection?.
236 payment_sessions?.[0]
237 if (!activePaymentSession) {
238 return
239 }
240
241 switch(true) {
242 case activePaymentSession.provider_id.startsWith("pp_stripe_"):
243 // TODO handle Stripe UI
244 return "You chose stripe!"
245 case activePaymentSession.provider_id
246 .startsWith("pp_system_default"):
247 return "You chose manual payment! No additional actions required."
248 default:
249 return `You chose ${
250 activePaymentSession.provider_id
251 } which is in development.`
252 }
253 }
254
255 const handlePayment = () => {
256 retrievePaymentProviders()
257
258 // ... customer chooses payment provider
259 // const providerId = ...
260
261 selectPaymentProvider(providerId)
262
263 getPaymentUi()
264 }
265 ```
266
267 </CodeTab>
268 </CodeTabs>
269
270 In the example above, you:
271
272 - Retrieve the payment providers from the Medusa application using the [List Payment Providers API route](!api!/store/payment-providers/list-payment-providers). You use those to show the customer the available options.
273 - When the customer chooses a payment provider, you use the `initiatePaymentSession` function to create a payment collection and initialize the payment session for the chosen provider.
274 - If you're not using the JS SDK, you need to create a payment collection using the [Create Payment Collection API route](!api!/store/payment-collections/create-payment-collection) if the cart doesn't have one. Then, you need to initialize the payment session using the [Initialize Payment Session API route](!api!/store/payment-collections/initialize-payment-session).
275 - Once the cart has a payment session, you optionally render the UI to perform additional actions. For example, if the customer chose Stripe, you can show them the card form to enter their credit card.
276
277 In the `Fetch API` example, the `handlePayment` function implements this flow by calling the different functions in the correct order.
278
279 ---
280
281 ## Troubleshooting
282
283 ### Unknown Error for Zero Cart Total
284
285 If your cart has a total of `0`, you might encounter an `unknown error` when trying to create a payment session.
286
287 Some payment providers, such as Stripe, require a non-zero amount to create a payment session. So, if your cart has a total of `0`, the error will be thrown on the payment provider's side.
288
289 In those cases, you can either:
290
291 - Make sure the payment session is only initialized when the cart has a total greater than `0`.
292 - Use payment providers like the Manual System Payment Provider, which doesn't create a payment session with a third-party provider.
293 - The Manual System Payment Provider is available by default in Medusa and can be used to handle payments without a third-party provider. It allows you to mark the order as paid without requiring any additional actions from the customer.
294 - Make sure to configure the Manual System Payment Provider in your store's region. Learn more in the [Manage Region](!user-guide!/settings/regions#edit-region-details) user guide.
295
296 ---
297
298 ## Stripe Example
299
300 If you're integrating Stripe in your Medusa application and storefront, refer to the [Stripe guide](./stripe/page.mdx) for an example of how to handle the payment process using Stripe.