1 import { CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `Accept Payment in Checkout Flow`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to implement it using workflows or the Payment Module.
10
11 ## Why Implement the Payment Flow?
12
13 Medusa already provides a built-in payment flow that allows you to accept payments from customers, which you can learn about in the [Accept Payment Flow in Checkout](../payment-checkout-flow/page.mdx) guide.
14
15 You may need to implement a custom payment flow if you have a different use case, or you're using the Payment Module separately from the Medusa application.
16
17 This guide will help you understand how to implement a payment flow using the Payment Module's main service or workflows.
18
19 You can also follow this guide to get a general understanding of how the payment flow works in the Medusa application.
20
21 ---
22
23 ## How to Implement the Accept Payment Flow?
24
25 <Note title="Tip">
26
27 For a guide on how to implement this flow in the storefront, check out [this guide](../../../storefront-development/checkout/payment/page.mdx).
28
29 </Note>
30
31 <Note>
32
33 It's highly recommended to use Medusa's workflows to implement this flow. Use the Payment Module's main service for more complex cases.
34
35 </Note>
36
37 ### 1. Create a Payment Collection
38
39 A payment collection holds all details related to a resource’s payment operations. So, you start off by creating a payment collection.
40
41 In the Medusa application, you associate the payment collection with a cart, which is the resource that the customer is trying to pay for.
42
43 For example:
44
45 <CodeTabs group="workflow-service">
46 <CodeTab label="Using Workflow" value="workflow">
47
48 ```ts
49 import { createPaymentCollectionForCartWorkflow } from "@medusajs/medusa/core-flows"
50
51 // ...
52
53 await createPaymentCollectionForCartWorkflow(container)
54 .run({
55 input: {
56 cart_id: "cart_123",
57 },
58 })
59 ```
60
61 </CodeTab>
62 <CodeTab label="Using Service" value="service">
63
64 ```ts
65 const paymentCollection =
66 await paymentModuleService.createPaymentCollections({
67 currency_code: "usd",
68 amount: 50,
69 })
70 ```
71
72 </CodeTab>
73 </CodeTabs>
74
75 ### 2. Show Payment Providers
76
77 Next, you'll show the customer the available payment providers to choose from.
78
79 In the Medusa application, you need to use [Query](!docs!/learn/fundamentals/query) to retrieve the available payment providers in a region.
80
81 <CodeTabs group="query-service">
82 <CodeTab label="Using Query" value="query">
83
84 ```ts
85 const query = container.resolve(ContainerRegistrationKeys.QUERY)
86
87 const { data: regionPaymentProviders } = await query.graph({
88 entryPoint: "region_payment_provider",
89 variables: {
90 filters: {
91 region_id: "reg_123",
92 },
93 },
94 fields: ["payment_providers.*"],
95 })
96
97 const paymentProviders = regionPaymentProviders.map(
98 (relation) => relation.payment_providers
99 )
100 ```
101
102 </CodeTab>
103 <CodeTab label="Using Service" value="service">
104
105 ```ts
106 const paymentProviders = await paymentModuleService.listPaymentProviders()
107 ```
108
109 </CodeTab>
110 </CodeTabs>
111
112 ### 3. Create Payment Sessions
113
114 The payment collection has one or more payment sessions, each being a payment amount to be authorized by a payment provider.
115
116 So, once the customer selects a payment provider, create a payment session for the selected payment provider.
117
118 This will also initialize the payment session in the third-party payment provider.
119
120 <Note>
121
122 When creating a payment session through `createPaymentSessionsWorkflow`, Medusa validates that the chosen payment provider is enabled in the cart's region. If the provider is not enabled in the region, the workflow throws an error. This validation only applies to payment collections linked to an active (not yet completed) cart; payment collections on orders are not affected.
123
124 </Note>
125
126 For example:
127
128 <CodeTabs group="workflow-service">
129 <CodeTab label="Using Workflow" value="workflow">
130
131 ```ts
132 import { createPaymentSessionsWorkflow } from "@medusajs/medusa/core-flows"
133
134 // ...
135
136 const { result: paymentSession } = await createPaymentSessionsWorkflow(container)
137 .run({
138 input: {
139 payment_collection_id: "paycol_123",
140 provider_id: "pp_stripe_stripe",
141 },
142 })
143 ```
144
145 </CodeTab>
146 <CodeTab label="Using Service" value="service">
147
148 ```ts
149 const paymentSession =
150 await paymentModuleService.createPaymentSession(
151 paymentCollection.id,
152 {
153 provider_id: "pp_stripe_stripe",
154 currency_code: "usd",
155 amount: 50,
156 data: {
157 // any necessary data for the
158 // payment provider
159 },
160 }
161 )
162 ```
163
164 </CodeTab>
165 </CodeTabs>
166
167 ### 4. Authorize Payment Session
168
169 Once the customer places the order, you need to authorize the payment session with the third-party payment provider.
170
171 For example:
172
173 <CodeTabs group="workflow-service">
174 <CodeTab label="Using Step" value="workflow">
175
176 ```ts
177 import { authorizePaymentSessionStep } from "@medusajs/medusa/core-flows"
178
179 // ...
180
181 authorizePaymentSessionStep({
182 id: "payses_123",
183 context: {},
184 })
185 ```
186
187 </CodeTab>
188 <CodeTab label="Using Service" value="service">
189
190 ```ts
191 const payment = await paymentModuleService.authorizePaymentSession(
192 "payses_123",
193 {}
194 )
195 ```
196
197 </CodeTab>
198 </CodeTabs>
199
200 When the payment authorization is successful, a payment is created and returned.
201
202 #### Handling Deferred Authorization
203
204 Some payment methods (for example, bank transfers, payment links, or vouchers like OXXO or boleto) don't authorize immediately. For these methods, the payment provider returns a `pending_authorization` status instead of `authorized`.
205
206 When this happens:
207
208 - `authorizePaymentSession` returns `null` instead of a payment object.
209 - The payment session's `status` is updated to `pending_authorization`.
210 - The cart can still be completed and an order is created with an "awaiting" payment status.
211 - Medusa will re-attempt authorization automatically when it receives a webhook event from the payment provider confirming the payment.
212 - Admins can also manually trigger a re-check from the order details page in the Medusa Admin.
213
214 <Note>
215
216 Support for `pending_authorization` is available since Medusa [v2.17.2](https://github.com/medusajs/medusa/releases/tag/v2.17.2).
217
218 </Note>
219
220 #### Handling Additional Action
221
222 <Note>
223
224 If you used the `authorizePaymentSessionStep`, you don't need to implement this logic as it's implemented in the step.
225
226 </Note>
227
228 If the payment authorization isn't successful, whether because it requires additional action or for another reason, the method updates the payment session with the new status and throws an error.
229
230 In that case, you can catch that error and, if the session's `status` property is `requires_more`, handle the additional action, then retry the authorization.
231
232 For example:
233
234 ```ts
235 try {
236 const payment =
237 await paymentModuleService.authorizePaymentSession(
238 paymentSession.id,
239 {}
240 )
241 } catch (e) {
242 // retrieve the payment session again
243 const updatedPaymentSession = (
244 await paymentModuleService.listPaymentSessions({
245 id: [paymentSession.id],
246 })
247 )[0]
248
249 if (updatedPaymentSession.status === "requires_more") {
250 // TODO perform required action
251 // TODO authorize payment again.
252 }
253 }
254 ```
255
256 ### 5. Payment Flow Complete
257
258 The payment flow is complete once the payment session is authorized and the payment is created.
259
260 You can then:
261
262 - Complete the cart using the [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow) if you're using the Medusa application.
263 - Capture the payment either using the [capturePaymentWorkflow](/references/medusa-workflows/capturePaymentWorkflow) or [capturePayment method](/references/payment/capturePayment).
264 - Refund captured amounts using the [refundPaymentsWorkflow](/references/medusa-workflows/refundPaymentsWorkflow) or [refundPayment method](/references/payment/refundPayment).
265
266 <Note>
267
268 Some payment providers allow capturing the payment automatically once it's authorized. In that case, you don't need to do it manually.
269
270 </Note>
271
272 ### Capture Payments
273
274 To capture a payment, use the `capturePaymentWorkflow` or the Payment Module's `capturePayment` method.
275
276 If you pass an `amount`, it must be greater than 0. If you omit the `amount`, Medusa captures the full payment amount.
277
278 <Note>
279
280 Before [Medusa v2.18.0](https://github.com/medusajs/medusa/releases/tag/v2.18.0), passing `0` as the capture amount was treated as if no amount was provided, defaulting to the full payment amount. Now, passing `0` or a negative number throws an error.
281
282 </Note>
283
284 ---
285
286 ### Refund Payments
287
288 If you need to refund a payment, use the `refundPaymentsWorkflow`.
289
290 If you pass an `amount`, it must be greater than 0. If you omit the `amount`, Medusa refunds the full payment amount.
291
292 <Note>
293
294 Before [Medusa v2.18.0](https://github.com/medusajs/medusa/releases/tag/v2.18.0), passing `0` as the refund amount was treated as if no amount was provided, defaulting to the full payment amount. Now, passing `0` or a negative number throws an error.
295
296 </Note>
297
298 For example:
299
300 <CodeTabs group="workflow-service">
301 <CodeTab label="Using Workflow" value="workflow">
302
303 ```ts
304 import { refundPaymentsWorkflow } from "@medusajs/medusa/core-flows"
305
306 // ...
307
308 await refundPaymentsWorkflow(container)
309 .run({
310 input: [
311 {
312 payment_id: "pay_123",
313 amount: 10, // refund amount
314 note: "Customer requested refund", // optional note
315 metadata: { // optional custom data
316 reason: "damaged_goods",
317 return_id: "ret_456",
318 },
319 },
320 ],
321 })
322 ```
323
324 </CodeTab>
325 <CodeTab label="Using Service" value="service">
326
327 ```ts
328 const refund = await paymentModuleService.refundPayment({
329 payment_id: "pay_123",
330 amount: 10,
331 refund_reason_id: "rr_123",
332 note: "Customer requested refund",
333 metadata: {
334 reason: "damaged_goods",
335 return_id: "ret_456",
336 },
337 })
338 ```
339
340 </CodeTab>
341 </CodeTabs>
342
343 <Note>
344
345 The `metadata` property is available since Medusa [v2.15.0](https://github.com/medusajs/medusa/releases/tag/v2.15.0).
346
347 </Note>