1 import { setTimeout } from "timers/promises"
2 import stripe from "stripe"
3 import {
4 AuthorizePaymentInput,
5 AuthorizePaymentOutput,
6 CancelPaymentInput,
7 CancelPaymentOutput,
8 CapturePaymentInput,
9 CapturePaymentOutput,
10 RetrieveAccountHolderInput,
11 RetrieveAccountHolderOutput,
12 CreateAccountHolderInput,
13 CreateAccountHolderOutput,
14 DeleteAccountHolderInput,
15 DeleteAccountHolderOutput,
16 DeletePaymentMethodInput,
17 DeletePaymentMethodOutput,
18 DeletePaymentInput,
19 DeletePaymentOutput,
20 GetPaymentStatusInput,
21 GetPaymentStatusOutput,
22 InitiatePaymentInput,
23 InitiatePaymentOutput,
24 ListPaymentMethodsInput,
25 ListPaymentMethodsOutput,
26 ProviderWebhookPayload,
27 RefundPaymentInput,
28 RefundPaymentOutput,
29 RetrievePaymentInput,
30 RetrievePaymentOutput,
31 SavePaymentMethodInput,
32 SavePaymentMethodOutput,
33 UpdateAccountHolderInput,
34 UpdateAccountHolderOutput,
35 UpdatePaymentInput,
36 UpdatePaymentOutput,
37 WebhookActionResult,
38 } from "@medusajs/framework/types"
39 import {
40 AbstractPaymentProvider,
41 isDefined,
42 isPresent,
43 PaymentActions,
44 PaymentSessionStatus,
45 } from "@medusajs/framework/utils"
46 import { MedusaPaymentsOptions } from "../types"
47 import {
48 getAmountFromSmallestUnit,
49 getSmallestUnit,
50 } from "../utils/get-smallest-unit"
51 import {
52 CreateAccountHolderRequest,
53 CreatePaymentRequest,
54 MedusaAccountHolder,
55 MedusaPayment,
56 MedusaPaymentMethod,
57 MedusaPaymentMethodSession,
58 MedusaRefund,
59 RefundPaymentRequest,
60 UpdateAccountHolderRequest,
61 } from "../types/medusa-payments"
62
63 type HandledErrorType = { retry: true } | { retry: false; data: any }
64 class CloudServiceError extends Error {
65 type: string
66 originalType: string
67 data: any
68 message: string
69
70 constructor(type: string, originalType: string, data: any, message: string) {
71 super(message)
72 this.type = type
73 this.originalType = originalType
74 this.data = data
75 this.message = message
76 }
77 }
78
79 export class MedusaPaymentsProvider extends AbstractPaymentProvider<MedusaPaymentsOptions> {
80 static identifier = "medusa-payments"
81 protected readonly options_: MedusaPaymentsOptions
82 protected container_: Record<string, unknown>
83 // The stripe client is used to construct the webhook event, since we construct it the same way as Stripe does.
84 protected readonly stripeClient: stripe
85
86 // The provider is loaded in a different a bit differently - it is not passed as a provider but the options are passed to the module's configuration.
87 // Due to that, the validation needs to happen in the constructor
88 static validateOptions(options: MedusaPaymentsOptions): void {
89 return validateOptions(options)
90 }
91
92 constructor(cradle: Record<string, unknown>, options: MedusaPaymentsOptions) {
93 super(cradle, options)
94
95 validateOptions(options ?? {})
96 this.options_ = options
97 this.stripeClient = new stripe(options.api_key)
98 }
99
100 request<T>(
101 url: string,
102 options: Omit<RequestInit, "body"> & { body?: object }
103 ): Promise<T> {
104 const headers = {
105 "Content-Type": "application/json",
106 Authorization: `Basic ${this.options_.api_key}`,
107 "x-medusa-payment-account": this.options_.payment_account,
108 }
109 if (this.options_.environment_handle) {
110 headers["x-medusa-environment-handle"] = this.options_.environment_handle
111 }
112 if (this.options_.sandbox_handle) {
113 headers["x-medusa-sandbox-handle"] = this.options_.sandbox_handle
114 }
115
116 return fetch(`${this.options_.endpoint}${url}`, {
117 ...options,
118 body: options.body ? JSON.stringify(options.body) : undefined,
119 headers: {
120 ...options.headers,
121 ...headers,
122 },
123 }).then(async (res) => {
124 const body = await res.json().catch(() => ({}))
125
126 if (!res.ok) {
127 throw new CloudServiceError(
128 body.type,
129 body.originalType,
130 body.data,
131 body.message
132 )
133 }
134
135 return body
136 })
137 }
138
139 normalizePaymentParameters(
140 extra?: Record<string, string>
141 ): Partial<CreatePaymentRequest> {
142 const res = {
143 description: extra?.payment_description ?? "",
144 capture_method: extra?.capture_method as "automatic" | "manual",
145 setup_future_usage: extra?.setup_future_usage,
146 payment_method_types: extra?.payment_method_types,
147 payment_method_data: extra?.payment_method_data,
148 payment_method_options: extra?.payment_method_options,
149 automatic_payment_methods: extra?.automatic_payment_methods,
150 off_session: extra?.off_session,
151 confirm: extra?.confirm,
152 payment_method: extra?.payment_method,
153 return_url: extra?.return_url,
154 shared_payment_token: extra?.shared_payment_token,
155 } as Partial<CreatePaymentRequest>
156
157 return res
158 }
159
160 handleStripeError(error: CloudServiceError): HandledErrorType {
161 let medusaPayment: MedusaPayment | undefined
162
163 switch (error.type) {
164 case "MedusaCardError":
165 // Medusa has created a payment but it failed
166 // Extract and return payment object to be stored in payment_session
167 // Allows for reference to the failed intent and potential webhook reconciliation
168 medusaPayment = error.data as MedusaPayment | undefined
169 if (medusaPayment) {
170 return {
171 retry: false,
172 data: medusaPayment,
173 }
174 } else {
175 throw error
176 }
177 case "MedusaPaymentUnexpectedStateError":
178 medusaPayment = error.data as MedusaPayment | undefined
179 if (medusaPayment) {
180 return {
181 retry: false,
182 data: medusaPayment,
183 }
184 } else {
185 throw error
186 }
187 case "MedusaConnectionError":
188 case "MedusaRateLimitError":
189 // Connection or rate limit errors indicate an uncertain result
190 // Retry the operation
191 return {
192 retry: true,
193 }
194 case "MedusaAPIError": {
195 // API errors should be treated as indeterminate per Stripe documentation
196 // Rely on webhooks rather than assuming failure
197 return {
198 retry: false,
199 data: {
200 indeterminate_due_to: "medusa_api_error",
201 },
202 }
203 }
204 default:
205 throw error
206 }
207 }
208
209 async executeWithRetry<T>(
210 apiCall: () => Promise<T>,
211 maxRetries: number = 3,
212 baseDelay: number = 1000,
213 currentAttempt: number = 1
214 ): Promise<T> {
215 try {
216 return await apiCall()
217 } catch (error) {
218 const handledError = this.handleStripeError(error)
219
220 if (!handledError.retry) {
221 // If retry is false, we know data exists per the type definition
222 return handledError.data
223 }
224
225 if (handledError.retry && currentAttempt <= maxRetries) {
226 // Logic for retrying
227 const delay =
228 baseDelay *
229 Math.pow(2, currentAttempt - 1) *
230 (0.5 + Math.random() * 0.5)
231 await setTimeout(delay)
232 return this.executeWithRetry(
233 apiCall,
234 maxRetries,
235 baseDelay,
236 currentAttempt + 1
237 )
238 }
239
240 // Retries are exhausted
241 throw error
242 }
243 }
244
245 async getPaymentStatus(
246 input: GetPaymentStatusInput
247 ): Promise<GetPaymentStatusOutput> {
248 const id = input?.data?.id as string
249 if (!id) {
250 throw new Error(
251 "No payment intent ID provided while getting payment status"
252 )
253 }
254
255 const payment = await this.retrievePayment({ data: { id } })
256 const statusResponse = this.getStatus(
257 payment.data as unknown as MedusaPayment
258 )
259
260 return statusResponse
261 }
262
263 async initiatePayment({
264 currency_code,
265 amount,
266 data,
267 context,
268 }: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
269 const additionalParameters = this.normalizePaymentParameters(
270 data as Record<string, string>
271 )
272
273 const intentRequest = {
274 amount: getSmallestUnit(amount, currency_code),
275 currency: currency_code,
276 metadata: {
277 session_id: data?.session_id as string,
278 },
279 account_holder_id: context?.account_holder?.data?.id as
280 | string
281 | undefined,
282 idempotency_key: context?.idempotency_key,
283 ...additionalParameters,
284 } as CreatePaymentRequest
285
286 const payment = (await this.executeWithRetry(() => {
287 return this.request<{ payment: any }>("/payments", {
288 method: "POST",
289 body: intentRequest,
290 }).then((data) => data.payment)
291 })) as MedusaPayment
292
293 return {
294 id: payment.id,
295 ...this.getStatus(payment),
296 }
297 }
298
299 async authorizePayment(
300 input: AuthorizePaymentInput
301 ): Promise<AuthorizePaymentOutput> {
302 return this.getPaymentStatus(input)
303 }
304
305 async cancelPayment({
306 data,
307 context,
308 }: CancelPaymentInput): Promise<CancelPaymentOutput> {
309 const id = data?.id as string
310
311 if (!id) {
312 return { data: data }
313 }
314
315 const intent = (await this.executeWithRetry(() => {
316 return this.request<{ payment: any }>(`/payments/${id}/cancel`, {
317 method: "POST",
318 body: {
319 idempotency_key: context?.idempotency_key,
320 },
321 }).then((data) => data.payment)
322 })) as MedusaPayment
323
324 const status = this.getStatus(intent)
325 if (status.status !== PaymentSessionStatus.CANCELED) {
326 throw new Error(
327 `Payment with id ${id} could not be canceled. Status: ${status.status}`
328 )
329 }
330
331 return { data: intent as unknown as Record<string, unknown> }
332 }
333
334 async capturePayment({
335 data,
336 context,
337 }: CapturePaymentInput): Promise<CapturePaymentOutput> {
338 const id = data?.id as string
339
340 const intent = (await this.executeWithRetry(() => {
341 return this.request<{ payment: any }>(`/payments/${id}/capture`, {
342 method: "POST",
343 body: {
344 idempotency_key: context?.idempotency_key,
345 },
346 }).then((data) => data.payment)
347 })) as MedusaPayment
348
349 const status = this.getStatus(intent)
350 if (status.status !== PaymentSessionStatus.CAPTURED) {
351 throw new Error(
352 `Payment with id ${id} could not be captured. Status: ${status.status}`
353 )
354 }
355
356 return { data: intent as unknown as Record<string, unknown> }
357 }
358
359 async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
360 return await this.cancelPayment(input)
361 }
362
363 async refundPayment({
364 amount,
365 data,
366 context,
367 }: RefundPaymentInput): Promise<RefundPaymentOutput> {
368 const id = data?.id as string
369 if (!id) {
370 throw new Error("No payment intent ID provided while refunding payment")
371 }
372
373 const currencyCode = data?.currency as string
374
375 const response = (await this.executeWithRetry(() => {
376 return this.request<{ refund: any }>(`/payments/${id}/refund`, {
377 method: "POST",
378 body: {
379 amount: getSmallestUnit(amount, currencyCode),
380 idempotency_key: context?.idempotency_key,
381 } as RefundPaymentRequest,
382 }).then((data) => data.refund)
383 })) as MedusaRefund
384
385 return { data: response as unknown as Record<string, unknown> }
386 }
387
388 async retrievePayment({
389 data,
390 }: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
391 const id = data?.id as string
392
393 const intent = (await this.executeWithRetry(() => {
394 return this.request<{ payment: any }>(`/payments/${id}`, {
395 method: "GET",
396 }).then((data) => data.payment)
397 })) as MedusaPayment
398
399 intent.amount = getAmountFromSmallestUnit(intent.amount, intent.currency)
400
401 return { data: intent as unknown as Record<string, unknown> }
402 }
403
404 async updatePayment({
405 data,
406 currency_code,
407 amount,
408 context,
409 }: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
410 const amountNumeric = getSmallestUnit(amount, currency_code)
411 if (isPresent(amount) && data?.amount === amountNumeric) {
412 return this.getStatus(
413 data as unknown as MedusaPayment
414 ) as unknown as UpdatePaymentOutput
415 }
416
417 const id = data?.id as string
418
419 const sessionData = (await this.executeWithRetry(() => {
420 return this.request<{ payment: any }>(`/payments/${id}`, {
421 method: "POST",
422 body: {
423 amount: amountNumeric,
424 idempotency_key: context?.idempotency_key,
425 },
426 }).then((data) => data.payment)
427 })) as MedusaPayment
428
429 return this.getStatus(sessionData)
430 }
431
432 async retrieveAccountHolder({
433 id,
434 }: RetrieveAccountHolderInput): Promise<RetrieveAccountHolderOutput> {
435 if (!id) {
436 throw new Error(
437 "No account holder ID provided while getting account holder"
438 )
439 }
440
441 const res = (await this.executeWithRetry(() => {
442 return this.request<{ account_holder: any }>(`/account-holders/${id}`, {
443 method: "GET",
444 }).then((data) => data.account_holder)
445 })) as MedusaAccountHolder
446
447 return {
448 id: res.id,
449 data: res as unknown as Record<string, unknown>,
450 }
451 }
452
453 async createAccountHolder({
454 context,
455 }: CreateAccountHolderInput): Promise<CreateAccountHolderOutput> {
456 const { account_holder, customer, idempotency_key } = context
457
458 if (account_holder?.data?.id) {
459 return { id: account_holder.data.id as string }
460 }
461
462 if (!customer) {
463 throw new Error("No customer provided while creating account holder")
464 }
465
466 const shipping = customer.billing_address
467 ? {
468 address: {
469 city: customer.billing_address.city,
470 country: customer.billing_address.country_code,
471 line1: customer.billing_address.address_1,
472 line2: customer.billing_address.address_2,
473 postal_code: customer.billing_address.postal_code,
474 state: customer.billing_address.province,
475 },
476 }
477 : undefined
478
479 const accountHolder = (await this.executeWithRetry(() => {
480 return this.request<{ account_holder: any }>(`/account-holders`, {
481 method: "POST",
482 body: {
483 email: customer.email,
484 name:
485 customer.company_name ||
486 `${customer.first_name ?? ""} ${customer.last_name ?? ""}`.trim() ||
487 undefined,
488 phone: customer.phone as string | undefined,
489 ...shipping,
490 idempotency_key: idempotency_key,
491 } as CreateAccountHolderRequest,
492 }).then((data) => data.account_holder)
493 })) as MedusaAccountHolder
494
495 return {
496 id: accountHolder.id,
497 data: accountHolder as unknown as Record<string, unknown>,
498 }
499 }
500
501 async updateAccountHolder({
502 context,
503 }: UpdateAccountHolderInput): Promise<UpdateAccountHolderOutput> {
504 const { account_holder, customer, idempotency_key } = context
505
506 if (!account_holder?.data?.id) {
507 throw new Error(
508 "No account holder in context while updating account holder"
509 )
510 }
511
512 // If no customer context was provided, we simply don't update anything within the provider
513 if (!customer) {
514 return {}
515 }
516
517 const accountHolderId = account_holder.data.id as string
518
519 const shipping = customer.billing_address
520 ? {
521 address: {
522 city: customer.billing_address.city,
523 country: customer.billing_address.country_code,
524 line1: customer.billing_address.address_1,
525 line2: customer.billing_address.address_2,
526 postal_code: customer.billing_address.postal_code,
527 state: customer.billing_address.province,
528 },
529 }
530 : undefined
531
532 const accountHolder = (await this.executeWithRetry(() => {
533 return this.request<{ account_holder: any }>(
534 `/account-holders/${accountHolderId}`,
535 {
536 method: "POST",
537 body: {
538 email: customer.email,
539 name:
540 customer.company_name ||
541 `${customer.first_name ?? ""} ${
542 customer.last_name ?? ""
543 }`.trim() ||
544 undefined,
545 phone: customer.phone as string | undefined,
546 ...shipping,
547 idempotency_key: idempotency_key,
548 } as UpdateAccountHolderRequest,
549 }
550 ).then((data) => data.account_holder)
551 })) as MedusaAccountHolder
552
553 return {
554 data: accountHolder as unknown as Record<string, unknown>,
555 }
556 }
557
558 async deleteAccountHolder({
559 context,
560 }: DeleteAccountHolderInput): Promise<DeleteAccountHolderOutput> {
561 const { account_holder } = context
562 const accountHolderId = account_holder?.data?.id as string | undefined
563 if (!accountHolderId) {
564 throw new Error(
565 "No account holder in context while deleting account holder"
566 )
567 }
568
569 await this.executeWithRetry(() => {
570 return this.request<{ account_holder: any }>(
571 `/account-holders/${accountHolderId}`,
572 {
573 method: "DELETE",
574 }
575 )
576 })
577
578 return {}
579 }
580
581 async listPaymentMethods({
582 context,
583 }: ListPaymentMethodsInput): Promise<ListPaymentMethodsOutput> {
584 const accountHolderId = context?.account_holder?.data?.id as
585 | string
586 | undefined
587 if (!accountHolderId) {
588 return []
589 }
590
591 const paymentMethods = (await this.executeWithRetry(() => {
592 return this.request<{ payment_methods: any[] }>(
593 `/payment-methods?account_holder_id=${accountHolderId}`,
594 {
595 method: "GET",
596 }
597 ).then((data) => data.payment_methods)
598 })) as MedusaPaymentMethod[]
599
600 return paymentMethods.map((method) => ({
601 id: method.id,
602 data: method as unknown as Record<string, unknown>,
603 }))
604 }
605
606 async savePaymentMethod({
607 context,
608 data,
609 }: SavePaymentMethodInput): Promise<SavePaymentMethodOutput> {
610 const accountHolderId = context?.account_holder?.data?.id as
611 | string
612 | undefined
613
614 if (!accountHolderId) {
615 throw new Error("Account holder not set while saving a payment method")
616 }
617
618 const paymentMethodSession = (await this.executeWithRetry(() => {
619 return this.request<{ payment_method_session: any }>(`/payment-methods`, {
620 method: "POST",
621 body: {
622 account_holder_id: accountHolderId,
623 ...data,
624 idempotency_key: context?.idempotency_key,
625 },
626 }).then((data) => data.payment_method_session)
627 })) as MedusaPaymentMethodSession
628
629 return {
630 id: paymentMethodSession.id,
631 data: paymentMethodSession as unknown as Record<string, unknown>,
632 }
633 }
634
635 async deletePaymentMethod({
636 context,
637 data,
638 }: DeletePaymentMethodInput): Promise<DeletePaymentMethodOutput> {
639 const paymentMethodId = data?.id as string | undefined
640
641 if (!paymentMethodId) {
642 throw new Error(
643 "Payment method ID not set while deleting a payment method"
644 )
645 }
646
647 await this.executeWithRetry(() => {
648 return this.request<{ payment_method: any }>(
649 `/payment-methods/${paymentMethodId}`,
650 {
651 method: "DELETE",
652 body: {
653 idempotency_key: context?.idempotency_key,
654 },
655 }
656 )
657 })
658
659 return {}
660 }
661
662 private getStatus(payment: MedusaPayment) {
663 const paymenAsRecord = payment as unknown as Record<string, unknown>
664
665 switch (payment.status) {
666 case "requires_payment_method":
667 if (payment.last_payment_error) {
668 return { status: PaymentSessionStatus.ERROR, data: paymenAsRecord }
669 }
670 return { status: PaymentSessionStatus.PENDING, data: paymenAsRecord }
671 case "requires_confirmation":
672 case "processing":
673 return { status: PaymentSessionStatus.PENDING, data: paymenAsRecord }
674 case "requires_action":
675 return {
676 status: PaymentSessionStatus.REQUIRES_MORE,
677 data: paymenAsRecord,
678 }
679 case "canceled":
680 return { status: PaymentSessionStatus.CANCELED, data: paymenAsRecord }
681 case "requires_capture":
682 return { status: PaymentSessionStatus.AUTHORIZED, data: paymenAsRecord }
683 case "succeeded":
684 return { status: PaymentSessionStatus.CAPTURED, data: paymenAsRecord }
685 default:
686 return { status: PaymentSessionStatus.PENDING, data: paymenAsRecord }
687 }
688 }
689
690 async getWebhookActionAndData(
691 webhookData: ProviderWebhookPayload["payload"]
692 ): Promise<WebhookActionResult> {
693 const event = this.constructWebhookEvent(webhookData)
694 const intent = event.data.object as stripe.PaymentIntent
695
696 const { currency } = intent
697
698 switch (event.type) {
699 case "payment_intent.created":
700 case "payment_intent.processing":
701 return {
702 action: PaymentActions.PENDING,
703 data: {
704 session_id: intent.metadata.session_id,
705 amount: getAmountFromSmallestUnit(intent.amount, currency),
706 },
707 }
708 case "payment_intent.canceled":
709 return {
710 action: PaymentActions.CANCELED,
711 data: {
712 session_id: intent.metadata.session_id,
713 amount: getAmountFromSmallestUnit(intent.amount, currency),
714 },
715 }
716 case "payment_intent.payment_failed":
717 return {
718 action: PaymentActions.FAILED,
719 data: {
720 session_id: intent.metadata.session_id,
721 amount: getAmountFromSmallestUnit(intent.amount, currency),
722 },
723 }
724 case "payment_intent.requires_action":
725 return {
726 action: PaymentActions.REQUIRES_MORE,
727 data: {
728 session_id: intent.metadata.session_id,
729 amount: getAmountFromSmallestUnit(intent.amount, currency),
730 },
731 }
732 case "payment_intent.amount_capturable_updated":
733 return {
734 action: PaymentActions.AUTHORIZED,
735 data: {
736 session_id: intent.metadata.session_id,
737 amount: getAmountFromSmallestUnit(
738 intent.amount_capturable,
739 currency
740 ),
741 },
742 }
743 case "payment_intent.partially_funded":
744 return {
745 action: PaymentActions.REQUIRES_MORE,
746 data: {
747 session_id: intent.metadata.session_id,
748 amount: getAmountFromSmallestUnit(
749 intent.next_action?.display_bank_transfer_instructions
750 ?.amount_remaining ?? intent.amount,
751 currency
752 ),
753 },
754 }
755 case "payment_intent.succeeded":
756 return {
757 action: PaymentActions.SUCCESSFUL,
758 data: {
759 session_id: intent.metadata.session_id,
760 amount: getAmountFromSmallestUnit(intent.amount_received, currency),
761 },
762 }
763
764 default:
765 return { action: PaymentActions.NOT_SUPPORTED }
766 }
767 }
768
769 /**
770 * Constructs Medusa Payments Webhook event
771 * @param {object} data - the data of the webhook request: req.body
772 * ensures integrity of the webhook event
773 * @return {object} Medusa Payments Webhook event
774 */
775 constructWebhookEvent(data: ProviderWebhookPayload["payload"]) {
776 const signature = data.headers["medusa-payments-signature"] as string
777
778 const stripeEvent = this.stripeClient.webhooks.constructEvent(
779 data.rawData as string | Buffer,
780 signature,
781 this.options_.webhook_secret
782 )
783
784 return stripeEvent
785 }
786 }
787
788 const validateOptions = (options: MedusaPaymentsOptions): void => {
789 if (!isDefined(options.endpoint)) {
790 throw new Error(
791 "Required option `endpoint` is missing in Medusa payments plugin"
792 )
793 }
794 if (!isDefined(options.webhook_secret)) {
795 throw new Error(
796 "Required option `webhook_secret` is missing in Medusa payments plugin"
797 )
798 }
799 if (!isDefined(options.api_key)) {
800 throw new Error(
801 "Required option `api_key` is missing in Medusa payments plugin"
802 )
803 }
804 if (!isDefined(options.payment_account)) {
805 throw new Error(
806 "Required option `payment_account` is missing in Medusa payments plugin"
807 )
808 }
809
810 if (
811 !isDefined(options.environment_handle) &&
812 !isDefined(options.sandbox_handle)
813 ) {
814 throw new Error(
815 "Required option `environment_handle` or `sandbox_handle` is missing in Medusa payments plugin"
816 )
817 }
818 }