@easypayment/medusa-payment-paypal 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/.medusa/server/src/admin/index.js +390 -136
  2. package/.medusa/server/src/admin/index.mjs +390 -136
  3. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts +1 -0
  4. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  5. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js +5 -1
  6. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  7. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts +1 -0
  8. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts.map +1 -1
  9. package/.medusa/server/src/api/admin/paypal/disconnect/route.js +1 -0
  10. package/.medusa/server/src/api/admin/paypal/disconnect/route.js.map +1 -1
  11. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts +2 -0
  12. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts.map +1 -1
  13. package/.medusa/server/src/api/admin/paypal/environment/route.js +2 -0
  14. package/.medusa/server/src/api/admin/paypal/environment/route.js.map +1 -1
  15. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +9 -0
  16. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
  17. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +9 -4
  18. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
  19. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts +7 -1
  20. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts.map +1 -1
  21. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js +9 -2
  22. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js.map +1 -1
  23. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts +1 -0
  24. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts.map +1 -1
  25. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js +1 -0
  26. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js.map +1 -1
  27. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts +1 -0
  28. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts.map +1 -1
  29. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js +10 -3
  30. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js.map +1 -1
  31. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts +2 -0
  32. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts.map +1 -1
  33. package/.medusa/server/src/api/admin/paypal/settings/route.js +9 -2
  34. package/.medusa/server/src/api/admin/paypal/settings/route.js.map +1 -1
  35. package/.medusa/server/src/api/admin/paypal/status/route.d.ts +4 -0
  36. package/.medusa/server/src/api/admin/paypal/status/route.d.ts.map +1 -1
  37. package/.medusa/server/src/api/admin/paypal/status/route.js +9 -1
  38. package/.medusa/server/src/api/admin/paypal/status/route.js.map +1 -1
  39. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts +4 -0
  40. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  41. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +5 -0
  42. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  43. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts +8 -0
  44. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  45. package/.medusa/server/src/api/store/paypal/capture-order/route.js +23 -3
  46. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  47. package/.medusa/server/src/api/store/paypal/config/route.d.ts +5 -0
  48. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  49. package/.medusa/server/src/api/store/paypal/config/route.js +12 -5
  50. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  51. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +8 -0
  52. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  53. package/.medusa/server/src/api/store/paypal/create-order/route.js +54 -20
  54. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  55. package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
  56. package/.medusa/server/src/api/store/paypal/onboard-return/route.js +19 -19
  57. package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
  58. package/.medusa/server/src/api/store/paypal/settings/route.d.ts +1 -0
  59. package/.medusa/server/src/api/store/paypal/settings/route.d.ts.map +1 -1
  60. package/.medusa/server/src/api/store/paypal/settings/route.js +4 -1
  61. package/.medusa/server/src/api/store/paypal/settings/route.js.map +1 -1
  62. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts +7 -0
  63. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
  64. package/.medusa/server/src/api/store/paypal/webhook/route.js +34 -3
  65. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
  66. package/.medusa/server/src/api/store/paypal-complete/route.d.ts +8 -0
  67. package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -1
  68. package/.medusa/server/src/api/store/paypal-complete/route.js +33 -6
  69. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  70. package/.medusa/server/src/api/utils/rate-limit.d.ts +4 -0
  71. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  72. package/.medusa/server/src/api/utils/rate-limit.js +9 -4
  73. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  74. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts +5 -0
  75. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  76. package/.medusa/server/src/jobs/paypal-webhook-retry.js +13 -2
  77. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  78. package/.medusa/server/src/modules/paypal/index.d.ts +1 -0
  79. package/.medusa/server/src/modules/paypal/index.d.ts.map +1 -1
  80. package/.medusa/server/src/modules/paypal/index.js +1 -0
  81. package/.medusa/server/src/modules/paypal/index.js.map +1 -1
  82. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js +22 -22
  83. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js +11 -11
  84. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js +18 -18
  85. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js +16 -16
  86. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js +20 -20
  87. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js +14 -14
  88. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js +15 -15
  89. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts.map +1 -1
  90. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js.map +1 -1
  91. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts.map +1 -1
  92. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js.map +1 -1
  93. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts.map +1 -1
  94. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js.map +1 -1
  95. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js +6 -6
  96. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts +5 -0
  97. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts.map +1 -1
  98. package/.medusa/server/src/modules/paypal/models/paypal_connection.js +5 -0
  99. package/.medusa/server/src/modules/paypal/models/paypal_connection.js.map +1 -1
  100. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts +4 -0
  101. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts.map +1 -1
  102. package/.medusa/server/src/modules/paypal/models/paypal_metric.js +4 -0
  103. package/.medusa/server/src/modules/paypal/models/paypal_metric.js.map +1 -1
  104. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts +5 -0
  105. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts.map +1 -1
  106. package/.medusa/server/src/modules/paypal/models/paypal_settings.js +5 -0
  107. package/.medusa/server/src/modules/paypal/models/paypal_settings.js.map +1 -1
  108. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts +7 -0
  109. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts.map +1 -1
  110. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js +7 -0
  111. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js.map +1 -1
  112. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  113. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  114. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +14 -6
  115. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  116. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +55 -32
  117. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  118. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -1
  119. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -1
  120. package/.medusa/server/src/modules/paypal/payment-provider/index.js +6 -4
  121. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -1
  122. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +8 -0
  123. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  124. package/.medusa/server/src/modules/paypal/payment-provider/service.js +39 -12
  125. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  126. package/.medusa/server/src/modules/paypal/service.d.ts +72 -2
  127. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  128. package/.medusa/server/src/modules/paypal/service.js +159 -33
  129. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  130. package/.medusa/server/src/modules/paypal/types/config.d.ts +2 -0
  131. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  132. package/.medusa/server/src/modules/paypal/types/config.js +5 -2
  133. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  134. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -0
  135. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
  136. package/.medusa/server/src/modules/paypal/utils/amounts.js +15 -5
  137. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
  138. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  139. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +3 -1
  140. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  141. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +9 -0
  142. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -1
  143. package/.medusa/server/src/modules/paypal/utils/currencies.js +13 -0
  144. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -1
  145. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +12 -0
  146. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  147. package/.medusa/server/src/modules/paypal/utils/payment-session.js +4 -3
  148. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  149. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +1 -0
  150. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -1
  151. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +1 -0
  152. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -1
  153. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts +11 -0
  154. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  155. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +17 -1
  156. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  157. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +6 -0
  158. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -1
  159. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +6 -0
  160. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -1
  161. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts +2 -0
  162. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
  163. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +6 -1
  164. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
  165. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +43 -0
  166. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  167. package/.medusa/server/src/modules/paypal/webhook-processor.js +57 -5
  168. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  169. package/.medusa/server/src/providers/paypal/index.d.ts +1 -0
  170. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -1
  171. package/.medusa/server/src/providers/paypal/index.js +1 -0
  172. package/.medusa/server/src/providers/paypal/index.js.map +1 -1
  173. package/.medusa/server/src/providers/paypal_card/index.d.ts +1 -0
  174. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -1
  175. package/.medusa/server/src/providers/paypal_card/index.js +1 -0
  176. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -1
  177. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  178. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -1
  179. package/.medusa/server/src/subscribers/paypal-order-invoice.js +9 -1
  180. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -1
  181. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +1 -0
  182. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  183. package/.medusa/server/src/subscribers/paypal-webhook-process.js +17 -4
  184. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  185. package/CHANGELOG.md +19 -0
  186. package/README.md +184 -175
  187. package/package.json +24 -5
  188. package/src/admin/index.ts +1 -1
  189. package/src/admin/routes/settings/paypal/_components/FieldRow.tsx +38 -29
  190. package/src/admin/routes/settings/paypal/_components/SectionCard.tsx +29 -26
  191. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +49 -48
  192. package/src/admin/routes/settings/paypal/_components/Toast.tsx +63 -52
  193. package/src/admin/routes/settings/paypal/_utils/adminFetch.ts +52 -32
  194. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +246 -139
  195. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +208 -123
  196. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +9 -5
  197. package/src/admin/routes/settings/paypal/connection/page.tsx +974 -908
  198. package/src/admin/routes/settings/paypal/google-pay/page.tsx +9 -5
  199. package/src/admin/routes/settings/paypal/page.tsx +14 -13
  200. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +9 -5
  201. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +304 -273
  202. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +48 -39
  203. package/src/api/admin/paypal/disconnect/route.ts +15 -14
  204. package/src/api/admin/paypal/environment/route.ts +34 -32
  205. package/src/api/admin/paypal/onboard-complete/route.ts +61 -50
  206. package/src/api/admin/paypal/onboarding-link/route.ts +91 -76
  207. package/src/api/admin/paypal/onboarding-status/route.ts +21 -20
  208. package/src/api/admin/paypal/save-credentials/route.ts +48 -37
  209. package/src/api/admin/paypal/settings/route.ts +63 -45
  210. package/src/api/admin/paypal/status/route.ts +29 -17
  211. package/src/api/hooks/paypal/onboard-return/route.ts +15 -15
  212. package/src/api/hooks/paypal/webhook/route.ts +17 -17
  213. package/src/api/middlewares.ts +61 -61
  214. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +63 -54
  215. package/src/api/store/paypal/capture-order/route.ts +416 -370
  216. package/src/api/store/paypal/config/route.ts +121 -115
  217. package/src/api/store/paypal/create-order/route.ts +586 -539
  218. package/src/api/store/paypal/onboard-return/route.ts +116 -113
  219. package/src/api/store/paypal/settings/route.ts +29 -19
  220. package/src/api/store/paypal/webhook/route.ts +380 -314
  221. package/src/api/store/paypal-complete/route.ts +157 -128
  222. package/src/api/utils/rate-limit.ts +143 -129
  223. package/src/index.ts +1 -1
  224. package/src/jobs/paypal-webhook-retry.ts +257 -241
  225. package/src/modules/paypal/index.ts +9 -8
  226. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -33
  227. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -22
  228. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -29
  229. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -27
  230. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -31
  231. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -25
  232. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -26
  233. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +15 -11
  234. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +15 -11
  235. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +15 -11
  236. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -17
  237. package/src/modules/paypal/migrations/20270202000000_align_nullable_defaults.ts +44 -44
  238. package/src/modules/paypal/migrations/20270301000000_add_webhook_transmission_id_index.ts +15 -15
  239. package/src/modules/paypal/models/paypal_connection.ts +28 -23
  240. package/src/modules/paypal/models/paypal_metric.ts +13 -9
  241. package/src/modules/paypal/models/paypal_settings.ts +13 -8
  242. package/src/modules/paypal/models/paypal_webhook_event.ts +26 -19
  243. package/src/modules/paypal/payment-provider/base-provider.ts +287 -275
  244. package/src/modules/paypal/payment-provider/card-service.ts +927 -855
  245. package/src/modules/paypal/payment-provider/index.ts +14 -15
  246. package/src/modules/paypal/payment-provider/service.ts +906 -836
  247. package/src/modules/paypal/payment-provider/status-utils.ts +59 -59
  248. package/src/modules/paypal/payment-provider/webhook-utils.ts +109 -109
  249. package/src/modules/paypal/service.ts +362 -115
  250. package/src/modules/paypal/types/config.ts +70 -65
  251. package/src/modules/paypal/utils/amounts.ts +123 -107
  252. package/src/modules/paypal/utils/core-workflow.ts +46 -46
  253. package/src/modules/paypal/utils/credential-resolver.ts +275 -271
  254. package/src/modules/paypal/utils/currencies.ts +97 -84
  255. package/src/modules/paypal/utils/partner.ts +8 -8
  256. package/src/modules/paypal/utils/payment-session.ts +144 -138
  257. package/src/modules/paypal/utils/paypal-auth.ts +6 -5
  258. package/src/modules/paypal/utils/paypal-fetch.ts +197 -181
  259. package/src/modules/paypal/utils/provider-ids.ts +21 -15
  260. package/src/modules/paypal/utils/secret-crypto.ts +226 -197
  261. package/src/modules/paypal/utils/webhook-verify.ts +61 -61
  262. package/src/modules/paypal/webhook-processor.ts +641 -573
  263. package/src/providers/paypal/index.ts +9 -8
  264. package/src/providers/paypal_card/index.ts +9 -8
  265. package/src/subscribers/paypal-order-invoice.ts +180 -173
  266. package/src/subscribers/paypal-webhook-process.ts +147 -131
  267. package/tsconfig.json +21 -31
@@ -1,855 +1,927 @@
1
- import { MedusaError } from "@medusajs/framework/utils"
2
- import type {
3
- AuthorizePaymentInput,
4
- AuthorizePaymentOutput,
5
- CapturePaymentInput,
6
- CapturePaymentOutput,
7
- CancelPaymentInput,
8
- CancelPaymentOutput,
9
- GetPaymentStatusInput,
10
- GetPaymentStatusOutput,
11
- InitiatePaymentInput,
12
- InitiatePaymentOutput,
13
- RefundPaymentInput,
14
- RefundPaymentOutput,
15
- RetrievePaymentInput,
16
- RetrievePaymentOutput,
17
- UpdatePaymentInput,
18
- UpdatePaymentOutput,
19
- } from "@medusajs/framework/types"
20
- import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
21
- import {
22
- assertPayPalCurrencySupported,
23
- normalizeCurrencyCode,
24
- } from "../utils/currencies"
25
- import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
26
- import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
27
- import {
28
- extractCaptureStatus,
29
- isCaptureCompleted,
30
- isRefundFailureStatus,
31
- } from "./status-utils"
32
- import { PayPalProviderBase } from "./base-provider"
33
-
34
- class PayPalAdvancedCardProvider extends PayPalProviderBase {
35
- static identifier = "paypal_card"
36
-
37
- protected readonly sessionPrefix = "pp_card"
38
- protected readonly idempotencyPrefix = "pp-card"
39
-
40
- async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
41
- const currencyOverride = await this.resolveCurrencyOverride()
42
- const currencyCode = normalizeCurrencyCode(
43
- input.currency_code || currencyOverride || "EUR"
44
- )
45
- assertPayPalCurrencySupported({
46
- currencyCode,
47
- paypalCurrencyOverride: currencyOverride,
48
- })
49
-
50
- return {
51
- id: this.generateSessionId(),
52
- data: {
53
- ...(input.data || {}),
54
- amount: input.amount,
55
- currency_code: currencyCode,
56
- },
57
- }
58
- }
59
-
60
- async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
61
- const currencyOverride = await this.resolveCurrencyOverride()
62
- const currencyCode = normalizeCurrencyCode(
63
- input.currency_code || currencyOverride || "EUR"
64
- )
65
- assertPayPalCurrencySupported({
66
- currencyCode,
67
- paypalCurrencyOverride: currencyOverride,
68
- })
69
- // Preserve the provider_id passthrough exactly like the wallet provider —
70
- // dropping it here would make the two providers' session data diverge.
71
- const providerId = (input.data as Record<string, any> | undefined)?.provider_id
72
-
73
- return {
74
- data: {
75
- ...(input.data || {}),
76
- ...this.invalidateStaleOrder(input, currencyCode),
77
- ...(providerId ? { provider_id: providerId } : {}),
78
- amount: input.amount,
79
- currency_code: currencyCode,
80
- },
81
- }
82
- }
83
-
84
- async authorizePayment(_input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
85
- const { data } = await this.normalizePaymentData(_input)
86
- const requestId = this.getIdempotencyKey(_input, "authorize")
87
- const { advancedCardSettings } = await this.resolveSettings()
88
- const disabledCards = Array.isArray(advancedCardSettings.disabledCards)
89
- ? advancedCardSettings.disabledCards.map((card: string) => String(card).toLowerCase())
90
- : []
91
- const cardBrand = String(
92
- data.card_brand || data.cardBrand || data?.paypal?.card_brand || ""
93
- ).toLowerCase()
94
- if (cardBrand && disabledCards.includes(cardBrand)) {
95
- throw new Error(`Card brand ${cardBrand} is disabled by admin settings.`)
96
- }
97
-
98
- const existingPayPal = (data.paypal || {}) as Record<string, any>
99
-
100
- // Session already carries a settled capture: trust it without a network
101
- // round-trip, but only when the stored capture is actually COMPLETED — a
102
- // PENDING/DECLINED capture must never be booked as captured money.
103
- const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
104
- if (storedCaptureStatus === "COMPLETED") {
105
- return {
106
- status: "captured",
107
- data: {
108
- ...(_input.data || {}),
109
- captured_at: (data as any).captured_at || new Date().toISOString(),
110
- },
111
- }
112
- }
113
-
114
- const orderId = String(existingPayPal.order_id || data.order_id || "")
115
- if (!orderId) {
116
- // Nothing to authorize: a PayPal order only exists after the buyer
117
- // submitted their card via the storefront (create-order + card fields).
118
- // The previous fallback created a fresh order here and immediately
119
- // called /authorize on it, which PayPal always rejects (no payment
120
- // source, and 422 UNSUPPORTED_INTENT for CAPTURE-intent orders).
121
- await this.recordFailure("authorize_failed", {
122
- cart_id: data.cart_id,
123
- payment_collection_id: data.payment_collection_id,
124
- message: "no PayPal order on card session",
125
- })
126
- throw new MedusaError(
127
- MedusaError.Types.NOT_ALLOWED,
128
- "No PayPal order was found for this payment session. The buyer must submit and approve their card payment before the cart can be completed."
129
- )
130
- }
131
-
132
- let order: Record<string, any> | null = null
133
- try {
134
- order = (await this.getOrderDetails(orderId)) as Record<string, any> | null
135
- } catch (e: any) {
136
- console.warn("[PayPal] card authorizePayment: order lookup failed:", e?.message)
137
- // Fall back to the session's own record on a transient lookup failure so
138
- // checkout isn't blocked when a real authorization/capture exists.
139
- if ((data as any).captured_at) {
140
- return {
141
- status: "captured",
142
- data: { ...(_input.data || {}), captured_at: (data as any).captured_at },
143
- }
144
- }
145
- if (
146
- existingPayPal.capture_id ||
147
- existingPayPal.authorization_id ||
148
- (data as any).authorized_at
149
- ) {
150
- return {
151
- status: "authorized",
152
- data: {
153
- ...(_input.data || {}),
154
- authorized_at: (data as any).authorized_at || new Date().toISOString(),
155
- },
156
- }
157
- }
158
- throw e
159
- }
160
-
161
- if (!order) {
162
- throw new Error("Unable to resolve PayPal order details for authorization.")
163
- }
164
-
165
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
166
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
167
-
168
- // Derive the status from what actually happened at PayPal, never from the
169
- // mere presence of a capture/authorization or from the configured
170
- // paymentAction: a PENDING (eCheck) capture is not settled money and a
171
- // DENIED/DECLINED one must fail the authorization.
172
- if (capture?.id) {
173
- const captureStatus = this.mapCaptureStatus(capture?.status)
174
- if (captureStatus === "captured") {
175
- return {
176
- status: "captured",
177
- data: {
178
- ...(data || {}),
179
- paypal: {
180
- ...existingPayPal,
181
- order_id: orderId,
182
- order,
183
- capture_id: capture.id,
184
- capture,
185
- },
186
- captured_at: new Date().toISOString(),
187
- },
188
- }
189
- }
190
- if (captureStatus === "pending") {
191
- return {
192
- status: "authorized",
193
- data: {
194
- ...(data || {}),
195
- paypal: {
196
- ...existingPayPal,
197
- order_id: orderId,
198
- order,
199
- capture_id: capture.id,
200
- },
201
- authorized_at: new Date().toISOString(),
202
- },
203
- }
204
- }
205
- if (captureStatus === "error" || captureStatus === "canceled") {
206
- return {
207
- status: "error",
208
- data: {
209
- ...(data || {}),
210
- paypal: { ...existingPayPal, order_id: orderId, order },
211
- },
212
- }
213
- }
214
- }
215
-
216
- if (authorization?.id) {
217
- const authStatus = this.mapAuthorizationStatus(authorization?.status)
218
- if (authStatus === "authorized") {
219
- return {
220
- status: "authorized",
221
- data: {
222
- ...(data || {}),
223
- paypal: {
224
- ...existingPayPal,
225
- order_id: orderId,
226
- order,
227
- authorization_id: authorization.id,
228
- authorizations:
229
- order?.purchase_units?.[0]?.payments?.authorizations || [],
230
- },
231
- authorized_at: new Date().toISOString(),
232
- },
233
- }
234
- }
235
- if (authStatus === "error" || authStatus === "canceled") {
236
- return {
237
- status: "error",
238
- data: {
239
- ...(data || {}),
240
- paypal: { ...existingPayPal, order_id: orderId, order },
241
- },
242
- }
243
- }
244
- }
245
-
246
- const orderStatus = String(order?.status || "").toUpperCase()
247
- const orderIntent = String(order?.intent || "").toUpperCase()
248
-
249
- if (orderStatus === "APPROVED") {
250
- if (orderIntent === "AUTHORIZE") {
251
- // Approved AUTHORIZE-intent order with no authorization yet: create it.
252
- const { accessToken, base } = await this.getPayPalAccessToken()
253
- const authorizeResp = await paypalFetch(
254
- `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
255
- {
256
- method: "POST",
257
- headers: {
258
- Authorization: `Bearer ${accessToken}`,
259
- "Content-Type": "application/json",
260
- "PayPal-Request-Id": `${requestId}-auth`,
261
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
262
- },
263
- }
264
- )
265
- const authorizeText = await authorizeResp.text()
266
- const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
267
- if (!authorizeResp.ok) {
268
- throw new Error(
269
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
270
- authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
271
- }`
272
- )
273
- }
274
- const authorized = JSON.parse(authorizeText) as Record<string, any>
275
- const authorizationId =
276
- authorized?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
277
- return {
278
- status: "authorized",
279
- data: {
280
- ...(data || {}),
281
- paypal: {
282
- ...existingPayPal,
283
- order_id: orderId,
284
- order: authorized || order,
285
- authorization_id: authorizationId,
286
- authorizations:
287
- authorized?.purchase_units?.[0]?.payments?.authorizations || [],
288
- },
289
- authorized_at: new Date().toISOString(),
290
- },
291
- }
292
- }
293
-
294
- // Approved CAPTURE-intent order: the buyer approved but the capture has
295
- // not happened yet (e.g. the storefront capture call failed). Report
296
- // "authorized" so the order can complete; capturePayment then routes the
297
- // actual capture by intent. Calling /authorize here — as the previous
298
- // code did for every intent — always fails with 422 UNSUPPORTED_INTENT
299
- // and permanently stuck the checkout.
300
- return {
301
- status: "authorized",
302
- data: {
303
- ...(data || {}),
304
- paypal: {
305
- ...existingPayPal,
306
- order_id: orderId,
307
- order,
308
- },
309
- authorized_at: new Date().toISOString(),
310
- },
311
- }
312
- }
313
-
314
- // CREATED / SAVED / PAYER_ACTION_REQUIRED etc.: the buyer never approved
315
- // the payment — nothing is authorized at PayPal.
316
- await this.recordFailure("authorize_failed", {
317
- order_id: orderId,
318
- order_status: orderStatus,
319
- message: "PayPal order not approved by buyer",
320
- })
321
- throw new MedusaError(
322
- MedusaError.Types.NOT_ALLOWED,
323
- `PayPal order ${orderId} has not been approved by the buyer (status ${orderStatus || "UNKNOWN"}). The payment cannot be authorized.`
324
- )
325
- }
326
-
327
- async capturePayment(_input: CapturePaymentInput): Promise<CapturePaymentOutput> {
328
- const data = (_input.data || {}) as Record<string, any>
329
- const paypalData = (data.paypal || {}) as Record<string, any>
330
- const orderId = String(paypalData.order_id || data.order_id || "")
331
- let authorizationId = String(paypalData.authorization_id || data.authorization_id || "")
332
- if (!orderId) {
333
- throw new Error("PayPal order_id is required to capture payment")
334
- }
335
-
336
- if (paypalData.capture_id || paypalData.capture) {
337
- return {
338
- data: {
339
- ...(data || {}),
340
- paypal: {
341
- ...paypalData,
342
- capture_id: paypalData.capture_id,
343
- capture: paypalData.capture,
344
- },
345
- captured_at: new Date().toISOString(),
346
- },
347
- }
348
- }
349
-
350
- const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(_input)
351
- // The requested (possibly partial) capture amount lives on the Medusa
352
- // capture row, not in the provider input — resolve it so partial captures
353
- // don't charge the full session total.
354
- const amount = await this.resolveRequestedCaptureAmount(_input, sessionAmount)
355
- // Include the amount in the idempotency suffix: PayPal deduplicates by
356
- // PayPal-Request-Id, so two sequential partial captures of the same order
357
- // that share an upstream idempotency_key would otherwise collide and the
358
- // second capture would silently return the first one's result.
359
- const requestId = this.getIdempotencyKey(_input, `capture-${orderId}-${amount}`)
360
- let debugId: string | null = null
361
-
362
- try {
363
- const { accessToken, base } = await this.getPayPalAccessToken()
364
- const order = await this.getOrderDetails(orderId).catch(() => null)
365
- const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
366
- if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
367
- return {
368
- data: {
369
- ...(data || {}),
370
- paypal: {
371
- ...paypalData,
372
- capture_id: existingCapture.id,
373
- capture: existingCapture,
374
- },
375
- captured_at: new Date().toISOString(),
376
- },
377
- }
378
- }
379
-
380
- const resolvedIntent = String(
381
- order?.intent || paypalData.order?.intent || data.intent || ""
382
- ).toUpperCase()
383
- if (!authorizationId && resolvedIntent === "AUTHORIZE") {
384
- const authorizeResp = await paypalFetch(`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`, {
385
- method: "POST",
386
- headers: {
387
- Authorization: `Bearer ${accessToken}`,
388
- "Content-Type": "application/json",
389
- "PayPal-Request-Id": `${requestId}-auth`,
390
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
391
- },
392
- })
393
- const authorizeText = await authorizeResp.text()
394
- debugId = authorizeResp.headers.get("paypal-debug-id")
395
- if (!authorizeResp.ok) {
396
- throw new Error(
397
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
398
- debugId ? ` debug_id=${debugId}` : ""
399
- }`
400
- )
401
- }
402
- const authorization = JSON.parse(authorizeText)
403
- authorizationId =
404
- authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
405
- }
406
-
407
- const isFinalCapture =
408
- paypalData.is_final_capture ??
409
- data.is_final_capture ??
410
- data.final_capture ??
411
- undefined
412
- const captureValue = amount > 0
413
- ? formatAmountForPayPal(amount, currencyCode || "EUR")
414
- : null
415
-
416
- // `amount` and `is_final_capture` are only honored on the authorizations
417
- // capture endpoint. The orders capture endpoint always captures the FULL
418
- // order and silently ignores an `amount` body — so a partial amount there
419
- // would over-capture while we record the smaller requested value. Route
420
- // partial captures through the authorization, and fail closed if a partial
421
- // capture is attempted against a capture-intent order.
422
- let capturePayload: Record<string, unknown>
423
- let captureUrl: string
424
- if (authorizationId) {
425
- captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
426
- capturePayload = {
427
- ...(captureValue
428
- ? { amount: { currency_code: currencyCode || "EUR", value: captureValue } }
429
- : {}),
430
- ...(typeof isFinalCapture === "boolean" ? { is_final_capture: isFinalCapture } : {}),
431
- }
432
- } else {
433
- captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
434
- capturePayload = {}
435
- const orderTotal = order?.purchase_units?.[0]?.amount?.value
436
- if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
437
- throw new Error(
438
- `PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
439
- `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
440
- `AUTHORIZE to capture a partial amount.`
441
- )
442
- }
443
- }
444
-
445
- // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the capture
446
- // idempotent, so a retry after a network blip re-uses the same capture
447
- // instead of double-charging.
448
- const ppResp = await paypalFetchWithRetry(captureUrl, {
449
- method: "POST",
450
- headers: {
451
- Authorization: `Bearer ${accessToken}`,
452
- "Content-Type": "application/json",
453
- "PayPal-Request-Id": requestId,
454
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
455
- },
456
- body: JSON.stringify(capturePayload),
457
- })
458
-
459
- const ppText = await ppResp.text()
460
- debugId = ppResp.headers.get("paypal-debug-id")
461
- if (!ppResp.ok) {
462
- throw new Error(
463
- `PayPal capture error (${ppResp.status}): ${ppText}${
464
- debugId ? ` debug_id=${debugId}` : ""
465
- }`
466
- )
467
- }
468
-
469
- const capture = JSON.parse(ppText)
470
-
471
- // A 2xx response does NOT mean the funds were captured. PayPal returns 201
472
- // for captures that are PENDING (pending review / eCheck), DECLINED, or
473
- // FAILED. Recording any of these as "captured" books money that never
474
- // settled, so only a COMPLETED capture is treated as success.
475
- const captureStatus = extractCaptureStatus(capture)
476
- if (captureStatus !== "COMPLETED") {
477
- throw new Error(
478
- `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
479
- `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
480
- )
481
- }
482
-
483
- const captureId =
484
- capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
485
- const existingCaptures = Array.isArray(paypalData.captures) ? paypalData.captures : []
486
- const captureEntry = {
487
- id: captureId,
488
- status: capture?.status,
489
- amount: capture?.amount,
490
- raw: capture,
491
- }
492
-
493
- await this.recordSuccess("capture_success")
494
- await this.recordPaymentEvent("capture", {
495
- order_id: orderId,
496
- capture_id: captureId,
497
- authorization_id: authorizationId || undefined,
498
- amount,
499
- currency_code: currencyCode,
500
- request_id: requestId,
501
- })
502
-
503
- return {
504
- data: {
505
- ...(data || {}),
506
- paypal: {
507
- ...paypalData,
508
- order_id: orderId,
509
- capture_id: captureId,
510
- capture,
511
- authorization_id: authorizationId || paypalData.authorization_id,
512
- captures: [...existingCaptures, captureEntry],
513
- },
514
- captured_at: new Date().toISOString(),
515
- },
516
- }
517
- } catch (error: any) {
518
- await this.recordFailure("capture_failed", {
519
- order_id: orderId,
520
- request_id: requestId,
521
- debug_id: debugId,
522
- message: error?.message,
523
- })
524
- // Surface the real reason: Medusa masks non-MedusaErrors as a generic
525
- // "unknown error" in production, hiding the PayPal failure.
526
- throw error instanceof MedusaError
527
- ? error
528
- : new MedusaError(
529
- MedusaError.Types.INVALID_DATA,
530
- error?.message || "PayPal capture failed."
531
- )
532
- }
533
- }
534
-
535
- async cancelPayment(_input: CancelPaymentInput): Promise<CancelPaymentOutput> {
536
- const data = (_input.data || {}) as Record<string, any>
537
- const paypalData = (data.paypal || {}) as Record<string, any>
538
- const orderId = String(paypalData.order_id || data.order_id || "")
539
- const captureId = String(paypalData.capture_id || data.capture_id || "")
540
- const storedAuthorizationId = String(
541
- paypalData.authorization_id || data.authorization_id || ""
542
- )
543
-
544
- try {
545
- const order = orderId ? await this.getOrderDetails(orderId) : null
546
- const intent = String(order?.intent || "").toUpperCase()
547
- const authorizationId =
548
- order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
549
- storedAuthorizationId
550
-
551
- if (intent === "AUTHORIZE" && authorizationId) {
552
- const { accessToken, base } = await this.getPayPalAccessToken()
553
- const requestId = this.getIdempotencyKey(_input, `void-${authorizationId}`)
554
-
555
- const resp = await paypalFetch(
556
- `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
557
- {
558
- method: "POST",
559
- headers: {
560
- Authorization: `Bearer ${accessToken}`,
561
- "Content-Type": "application/json",
562
- "PayPal-Request-Id": requestId,
563
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
564
- },
565
- }
566
- )
567
-
568
- if (!resp.ok) {
569
- const text = await resp.text()
570
- const debugId = resp.headers.get("paypal-debug-id")
571
- throw new Error(
572
- `PayPal void error (${resp.status}): ${text}${
573
- debugId ? ` debug_id=${debugId}` : ""
574
- }`
575
- )
576
- }
577
-
578
- await this.recordSuccess("void_success")
579
- await this.recordPaymentEvent("void", {
580
- order_id: orderId,
581
- authorization_id: authorizationId,
582
- })
583
- } else if (captureId) {
584
- const { accessToken, base } = await this.getPayPalAccessToken()
585
- const requestId = this.getIdempotencyKey(_input, `cancel-refund-${captureId}`)
586
-
587
- const resp = await paypalFetch(
588
- `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
589
- {
590
- method: "POST",
591
- headers: {
592
- Authorization: `Bearer ${accessToken}`,
593
- "Content-Type": "application/json",
594
- "PayPal-Request-Id": requestId,
595
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
596
- },
597
- body: JSON.stringify({}),
598
- }
599
- )
600
-
601
- if (!resp.ok) {
602
- const text = await resp.text()
603
- const debugId = resp.headers.get("paypal-debug-id")
604
- throw new Error(
605
- `PayPal refund error (${resp.status}): ${text}${
606
- debugId ? ` debug_id=${debugId}` : ""
607
- }`
608
- )
609
- }
610
-
611
- const refund = await resp.json().catch(() => ({}))
612
-
613
- // As with refundPayment: a 2xx response does not guarantee the refund
614
- // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
615
- // `canceled_at` for a refund that never went through would record a
616
- // cancellation while the merchant keeps the funds.
617
- const cancelRefundStatus = String(refund?.status || "").toUpperCase()
618
- if (isRefundFailureStatus(cancelRefundStatus)) {
619
- throw new Error(
620
- `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
621
- )
622
- }
623
-
624
- const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
625
- const refundEntry = {
626
- id: refund?.id,
627
- status: refund?.status,
628
- amount: refund?.amount,
629
- raw: refund,
630
- }
631
-
632
- await this.recordSuccess("cancel_refund_success")
633
-
634
- return {
635
- data: {
636
- ...(data || {}),
637
- paypal: {
638
- ...paypalData,
639
- order: order || undefined,
640
- authorization_id: authorizationId || storedAuthorizationId,
641
- capture_id: captureId || paypalData.capture_id,
642
- refund_id: refund?.id,
643
- refund_status: refund?.status,
644
- refunds: [...existingRefunds, refundEntry],
645
- },
646
- canceled_at: new Date().toISOString(),
647
- },
648
- }
649
- }
650
-
651
- return {
652
- data: {
653
- ...(data || {}),
654
- paypal: {
655
- ...paypalData,
656
- order: order || undefined,
657
- authorization_id: authorizationId || storedAuthorizationId,
658
- capture_id: captureId || paypalData.capture_id,
659
- },
660
- canceled_at: new Date().toISOString(),
661
- },
662
- }
663
- } catch (error: any) {
664
- await this.recordFailure("cancel_failed", {
665
- order_id: orderId,
666
- capture_id: captureId,
667
- message: error?.message,
668
- })
669
- throw error
670
- }
671
- }
672
-
673
- async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
674
- const data = (_input.data || {}) as Record<string, any>
675
- const paypalData = (data.paypal || {}) as Record<string, any>
676
- const captureId = String(paypalData.capture_id || data.capture_id || "")
677
- if (!captureId) {
678
- throw new MedusaError(
679
- MedusaError.Types.INVALID_DATA,
680
- "PayPal capture_id is required to refund payment. No capture found in session data."
681
- )
682
- }
683
-
684
- // Use the refund amount Medusa passes (top-level input), not the session
685
- // amount in `data` — otherwise a partial refund would refund the full order.
686
- // Medusa passes it as a BigNumberInput, so coerce it to a number; a naive
687
- // Number() of the object form yields NaN and silently refunds the full
688
- // capture.
689
- const amount = toAmountNumber(_input.amount)
690
- const requestId = this.getIdempotencyKey(_input, `refund-${captureId}-${amount}`)
691
- const currencyOverride = await this.resolveCurrencyOverride()
692
- const currencyCode = normalizeCurrencyCode(
693
- data.currency_code || currencyOverride || "EUR"
694
- )
695
-
696
- try {
697
- const { accessToken, base } = await this.getPayPalAccessToken()
698
- const refundPayload: Record<string, any> =
699
- amount > 0
700
- ? {
701
- amount: {
702
- currency_code: currencyCode,
703
- value: formatAmountForPayPal(amount, currencyCode),
704
- },
705
- }
706
- : {}
707
-
708
- // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
709
- // the refund amount) makes the refund idempotent, so a retry after a
710
- // network blip re-uses the same refund instead of double-refunding.
711
- const resp = await paypalFetchWithRetry(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
712
- method: "POST",
713
- headers: {
714
- Authorization: `Bearer ${accessToken}`,
715
- "Content-Type": "application/json",
716
- "PayPal-Request-Id": requestId,
717
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
718
- },
719
- body: JSON.stringify(refundPayload),
720
- })
721
-
722
- const text = await resp.text()
723
- if (!resp.ok) {
724
- const debugId = resp.headers.get("paypal-debug-id")
725
- throw new MedusaError(
726
- MedusaError.Types.UNEXPECTED_STATE,
727
- `PayPal refund error (${resp.status}): ${text}${
728
- debugId ? ` debug_id=${debugId}` : ""
729
- }`
730
- )
731
- }
732
-
733
- const refund = JSON.parse(text)
734
-
735
- // As with captures, a 2xx response does not guarantee the refund stuck.
736
- // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
737
- // recorded as a successful refund. PENDING is accepted: PayPal processes
738
- // refunds asynchronously and a pending refund will settle.
739
- const refundStatus = String(refund?.status || "").toUpperCase()
740
- if (isRefundFailureStatus(refundStatus)) {
741
- const refundDebugId = resp.headers.get("paypal-debug-id")
742
- throw new MedusaError(
743
- MedusaError.Types.UNEXPECTED_STATE,
744
- `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
745
- (refundDebugId ? ` debug_id=${refundDebugId}` : "")
746
- )
747
- }
748
-
749
- const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
750
- const refundEntry = {
751
- id: refund?.id,
752
- status: refund?.status,
753
- amount: refund?.amount,
754
- raw: refund,
755
- }
756
-
757
- await this.recordSuccess("refund_success")
758
- await this.recordPaymentEvent("refund", {
759
- capture_id: captureId,
760
- refund_id: refund?.id,
761
- amount,
762
- currency_code: currencyCode,
763
- request_id: requestId,
764
- })
765
-
766
- return {
767
- data: {
768
- ...(data || {}),
769
- paypal: {
770
- ...paypalData,
771
- refund_id: refund?.id,
772
- refund_status: refund?.status,
773
- refunds: [...existingRefunds, refundEntry],
774
- refund,
775
- },
776
- refunded_at: new Date().toISOString(),
777
- },
778
- }
779
- } catch (error: any) {
780
- await this.recordFailure("refund_failed", {
781
- capture_id: captureId,
782
- request_id: requestId,
783
- message: error?.message,
784
- })
785
- // Surface the real reason: Medusa masks any non-MedusaError as a generic
786
- // "An unknown error occurred." in production, hiding the PayPal failure.
787
- throw error instanceof MedusaError
788
- ? error
789
- : new MedusaError(
790
- MedusaError.Types.UNEXPECTED_STATE,
791
- error?.message || "PayPal refund failed."
792
- )
793
- }
794
- }
795
-
796
- async retrievePayment(_input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
797
- const data = (_input.data || {}) as Record<string, any>
798
- const paypalData = (data.paypal || {}) as Record<string, any>
799
- const orderId = String(paypalData.order_id || data.order_id || "")
800
- if (!orderId) {
801
- return { data: { ...(data || {}) } }
802
- }
803
-
804
- const order = await this.getOrderDetails(orderId)
805
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
806
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
807
-
808
- return {
809
- data: {
810
- ...(data || {}),
811
- paypal: {
812
- ...paypalData,
813
- order,
814
- authorization_id: authorization?.id || paypalData.authorization_id,
815
- capture_id: capture?.id || paypalData.capture_id,
816
- },
817
- },
818
- }
819
- }
820
-
821
- async getPaymentStatus(_input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
822
- const data = (_input.data || {}) as Record<string, any>
823
- const paypalData = (data.paypal || {}) as Record<string, any>
824
- const orderId = String(paypalData.order_id || data.order_id || "")
825
- if (!orderId) {
826
- return { status: "pending", data: { ...(data || {}) } }
827
- }
828
-
829
- const order = await this.getOrderDetails(orderId)
830
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
831
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
832
- const mappedStatus =
833
- this.mapCaptureStatus(capture?.status) ||
834
- this.mapAuthorizationStatus(authorization?.status) ||
835
- this.mapOrderStatus(order?.status) ||
836
- "pending"
837
-
838
- return {
839
- status: mappedStatus,
840
- data: {
841
- ...(data || {}),
842
- paypal: {
843
- ...paypalData,
844
- order,
845
- authorization_id: authorization?.id || paypalData.authorization_id,
846
- capture_id: capture?.id || paypalData.capture_id,
847
- },
848
- },
849
- }
850
- }
851
-
852
- }
853
-
854
- export default PayPalAdvancedCardProvider
855
- export { PayPalAdvancedCardProvider }
1
+ import { MedusaError } from "@medusajs/framework/utils"
2
+ import type {
3
+ AuthorizePaymentInput,
4
+ AuthorizePaymentOutput,
5
+ CapturePaymentInput,
6
+ CapturePaymentOutput,
7
+ CancelPaymentInput,
8
+ CancelPaymentOutput,
9
+ GetPaymentStatusInput,
10
+ GetPaymentStatusOutput,
11
+ InitiatePaymentInput,
12
+ InitiatePaymentOutput,
13
+ RefundPaymentInput,
14
+ RefundPaymentOutput,
15
+ RetrievePaymentInput,
16
+ RetrievePaymentOutput,
17
+ UpdatePaymentInput,
18
+ UpdatePaymentOutput,
19
+ } from "@medusajs/framework/types"
20
+ import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
21
+ import {
22
+ assertPayPalCurrencySupported,
23
+ normalizeCurrencyCode,
24
+ } from "../utils/currencies"
25
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
26
+ import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
27
+ import {
28
+ extractCaptureStatus,
29
+ isCaptureCompleted,
30
+ isRefundFailureStatus,
31
+ } from "./status-utils"
32
+ import { PayPalProviderBase } from "./base-provider"
33
+
34
+ /**
35
+ * PayPal Advanced (hosted) Card Fields payment provider —
36
+ * `pp_paypal_card_paypal_card`.
37
+ *
38
+ * Shares the order-based flow of the wallet provider but adds admin-configured
39
+ * card-brand restrictions and 3-D Secure handling. Card orders are created
40
+ * with a `payment_source.card` verification method (see create-order).
41
+ */
42
+ class PayPalAdvancedCardProvider extends PayPalProviderBase {
43
+ static identifier = "paypal_card"
44
+
45
+ protected readonly sessionPrefix = "pp_card"
46
+ protected readonly idempotencyPrefix = "pp-card"
47
+
48
+ async initiatePayment(
49
+ input: InitiatePaymentInput
50
+ ): Promise<InitiatePaymentOutput> {
51
+ const currencyOverride = await this.resolveCurrencyOverride()
52
+ const currencyCode = normalizeCurrencyCode(
53
+ input.currency_code || currencyOverride || "EUR"
54
+ )
55
+ assertPayPalCurrencySupported({
56
+ currencyCode,
57
+ paypalCurrencyOverride: currencyOverride,
58
+ })
59
+
60
+ return {
61
+ id: this.generateSessionId(),
62
+ data: {
63
+ ...(input.data || {}),
64
+ amount: input.amount,
65
+ currency_code: currencyCode,
66
+ },
67
+ }
68
+ }
69
+
70
+ async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
71
+ const currencyOverride = await this.resolveCurrencyOverride()
72
+ const currencyCode = normalizeCurrencyCode(
73
+ input.currency_code || currencyOverride || "EUR"
74
+ )
75
+ assertPayPalCurrencySupported({
76
+ currencyCode,
77
+ paypalCurrencyOverride: currencyOverride,
78
+ })
79
+ // Preserve the provider_id passthrough exactly like the wallet provider —
80
+ // dropping it here would make the two providers' session data diverge.
81
+ const providerId = (input.data as Record<string, any> | undefined)
82
+ ?.provider_id
83
+
84
+ return {
85
+ data: {
86
+ ...(input.data || {}),
87
+ ...this.invalidateStaleOrder(input, currencyCode),
88
+ ...(providerId ? { provider_id: providerId } : {}),
89
+ amount: input.amount,
90
+ currency_code: currencyCode,
91
+ },
92
+ }
93
+ }
94
+
95
+ async authorizePayment(
96
+ input: AuthorizePaymentInput
97
+ ): Promise<AuthorizePaymentOutput> {
98
+ const { data } = await this.normalizePaymentData(input)
99
+ const requestId = this.getIdempotencyKey(input, "authorize")
100
+ const { advancedCardSettings } = await this.resolveSettings()
101
+ const disabledCards = Array.isArray(advancedCardSettings.disabledCards)
102
+ ? advancedCardSettings.disabledCards.map((card: string) =>
103
+ String(card).toLowerCase()
104
+ )
105
+ : []
106
+ const cardBrand = String(
107
+ data.card_brand || data.cardBrand || data?.paypal?.card_brand || ""
108
+ ).toLowerCase()
109
+ if (cardBrand && disabledCards.includes(cardBrand)) {
110
+ throw new Error(`Card brand ${cardBrand} is disabled by admin settings.`)
111
+ }
112
+
113
+ const existingPayPal = (data.paypal || {}) as Record<string, any>
114
+
115
+ // Session already carries a settled capture: trust it without a network
116
+ // round-trip, but only when the stored capture is actually COMPLETED — a
117
+ // PENDING/DECLINED capture must never be booked as captured money.
118
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
119
+ if (storedCaptureStatus === "COMPLETED") {
120
+ return {
121
+ status: "captured",
122
+ data: {
123
+ ...(input.data || {}),
124
+ captured_at: (data as any).captured_at || new Date().toISOString(),
125
+ },
126
+ }
127
+ }
128
+
129
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
130
+ if (!orderId) {
131
+ // Nothing to authorize: a PayPal order only exists after the buyer
132
+ // submitted their card via the storefront (create-order + card fields).
133
+ // The previous fallback created a fresh order here and immediately
134
+ // called /authorize on it, which PayPal always rejects (no payment
135
+ // source, and 422 UNSUPPORTED_INTENT for CAPTURE-intent orders).
136
+ await this.recordFailure("authorize_failed", {
137
+ cart_id: data.cart_id,
138
+ payment_collection_id: data.payment_collection_id,
139
+ message: "no PayPal order on card session",
140
+ })
141
+ throw new MedusaError(
142
+ MedusaError.Types.NOT_ALLOWED,
143
+ "No PayPal order was found for this payment session. The buyer must submit and approve their card payment before the cart can be completed."
144
+ )
145
+ }
146
+
147
+ let order: Record<string, any> | null = null
148
+ try {
149
+ order = (await this.getOrderDetails(orderId)) as Record<
150
+ string,
151
+ any
152
+ > | null
153
+ } catch (e: any) {
154
+ console.warn(
155
+ "[PayPal] card authorizePayment: order lookup failed:",
156
+ e?.message
157
+ )
158
+ // Fall back to the session's own record on a transient lookup failure so
159
+ // checkout isn't blocked when a real authorization/capture exists.
160
+ if ((data as any).captured_at) {
161
+ return {
162
+ status: "captured",
163
+ data: {
164
+ ...(input.data || {}),
165
+ captured_at: (data as any).captured_at,
166
+ },
167
+ }
168
+ }
169
+ if (
170
+ existingPayPal.capture_id ||
171
+ existingPayPal.authorization_id ||
172
+ (data as any).authorized_at
173
+ ) {
174
+ return {
175
+ status: "authorized",
176
+ data: {
177
+ ...(input.data || {}),
178
+ authorized_at:
179
+ (data as any).authorized_at || new Date().toISOString(),
180
+ },
181
+ }
182
+ }
183
+ throw e
184
+ }
185
+
186
+ if (!order) {
187
+ throw new Error(
188
+ "Unable to resolve PayPal order details for authorization."
189
+ )
190
+ }
191
+
192
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
193
+ const authorization =
194
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
195
+
196
+ // Derive the status from what actually happened at PayPal, never from the
197
+ // mere presence of a capture/authorization or from the configured
198
+ // paymentAction: a PENDING (eCheck) capture is not settled money and a
199
+ // DENIED/DECLINED one must fail the authorization.
200
+ if (capture?.id) {
201
+ const captureStatus = this.mapCaptureStatus(capture?.status)
202
+ if (captureStatus === "captured") {
203
+ return {
204
+ status: "captured",
205
+ data: {
206
+ ...(data || {}),
207
+ paypal: {
208
+ ...existingPayPal,
209
+ order_id: orderId,
210
+ order,
211
+ capture_id: capture.id,
212
+ capture,
213
+ },
214
+ captured_at: new Date().toISOString(),
215
+ },
216
+ }
217
+ }
218
+ if (captureStatus === "pending") {
219
+ return {
220
+ status: "authorized",
221
+ data: {
222
+ ...(data || {}),
223
+ paypal: {
224
+ ...existingPayPal,
225
+ order_id: orderId,
226
+ order,
227
+ capture_id: capture.id,
228
+ },
229
+ authorized_at: new Date().toISOString(),
230
+ },
231
+ }
232
+ }
233
+ if (captureStatus === "error" || captureStatus === "canceled") {
234
+ return {
235
+ status: "error",
236
+ data: {
237
+ ...(data || {}),
238
+ paypal: { ...existingPayPal, order_id: orderId, order },
239
+ },
240
+ }
241
+ }
242
+ }
243
+
244
+ if (authorization?.id) {
245
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
246
+ if (authStatus === "authorized") {
247
+ return {
248
+ status: "authorized",
249
+ data: {
250
+ ...(data || {}),
251
+ paypal: {
252
+ ...existingPayPal,
253
+ order_id: orderId,
254
+ order,
255
+ authorization_id: authorization.id,
256
+ authorizations:
257
+ order?.purchase_units?.[0]?.payments?.authorizations || [],
258
+ },
259
+ authorized_at: new Date().toISOString(),
260
+ },
261
+ }
262
+ }
263
+ if (authStatus === "error" || authStatus === "canceled") {
264
+ return {
265
+ status: "error",
266
+ data: {
267
+ ...(data || {}),
268
+ paypal: { ...existingPayPal, order_id: orderId, order },
269
+ },
270
+ }
271
+ }
272
+ }
273
+
274
+ const orderStatus = String(order?.status || "").toUpperCase()
275
+ const orderIntent = String(order?.intent || "").toUpperCase()
276
+
277
+ if (orderStatus === "APPROVED") {
278
+ if (orderIntent === "AUTHORIZE") {
279
+ // Approved AUTHORIZE-intent order with no authorization yet: create it.
280
+ const { accessToken, base } = await this.getPayPalAccessToken()
281
+ const authorizeResp = await paypalFetch(
282
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
283
+ {
284
+ method: "POST",
285
+ headers: {
286
+ Authorization: `Bearer ${accessToken}`,
287
+ "Content-Type": "application/json",
288
+ "PayPal-Request-Id": `${requestId}-auth`,
289
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
290
+ },
291
+ }
292
+ )
293
+ const authorizeText = await authorizeResp.text()
294
+ const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
295
+ if (!authorizeResp.ok) {
296
+ throw new Error(
297
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
298
+ authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
299
+ }`
300
+ )
301
+ }
302
+ const authorized = JSON.parse(authorizeText) as Record<string, any>
303
+ const authorizationId =
304
+ authorized?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
305
+ return {
306
+ status: "authorized",
307
+ data: {
308
+ ...(data || {}),
309
+ paypal: {
310
+ ...existingPayPal,
311
+ order_id: orderId,
312
+ order: authorized || order,
313
+ authorization_id: authorizationId,
314
+ authorizations:
315
+ authorized?.purchase_units?.[0]?.payments?.authorizations || [],
316
+ },
317
+ authorized_at: new Date().toISOString(),
318
+ },
319
+ }
320
+ }
321
+
322
+ // Approved CAPTURE-intent order: the buyer approved but the capture has
323
+ // not happened yet (e.g. the storefront capture call failed). Report
324
+ // "authorized" so the order can complete; capturePayment then routes the
325
+ // actual capture by intent. Calling /authorize here — as the previous
326
+ // code did for every intent — always fails with 422 UNSUPPORTED_INTENT
327
+ // and permanently stuck the checkout.
328
+ return {
329
+ status: "authorized",
330
+ data: {
331
+ ...(data || {}),
332
+ paypal: {
333
+ ...existingPayPal,
334
+ order_id: orderId,
335
+ order,
336
+ },
337
+ authorized_at: new Date().toISOString(),
338
+ },
339
+ }
340
+ }
341
+
342
+ // CREATED / SAVED / PAYER_ACTION_REQUIRED etc.: the buyer never approved
343
+ // the payment — nothing is authorized at PayPal.
344
+ await this.recordFailure("authorize_failed", {
345
+ order_id: orderId,
346
+ order_status: orderStatus,
347
+ message: "PayPal order not approved by buyer",
348
+ })
349
+ throw new MedusaError(
350
+ MedusaError.Types.NOT_ALLOWED,
351
+ `PayPal order ${orderId} has not been approved by the buyer (status ${orderStatus || "UNKNOWN"}). The payment cannot be authorized.`
352
+ )
353
+ }
354
+
355
+ async capturePayment(
356
+ input: CapturePaymentInput
357
+ ): Promise<CapturePaymentOutput> {
358
+ const data = (input.data || {}) as Record<string, any>
359
+ const paypalData = (data.paypal || {}) as Record<string, any>
360
+ const orderId = String(paypalData.order_id || data.order_id || "")
361
+ let authorizationId = String(
362
+ paypalData.authorization_id || data.authorization_id || ""
363
+ )
364
+ if (!orderId) {
365
+ throw new Error("PayPal order_id is required to capture payment")
366
+ }
367
+
368
+ if (paypalData.capture_id || paypalData.capture) {
369
+ return {
370
+ data: {
371
+ ...(data || {}),
372
+ paypal: {
373
+ ...paypalData,
374
+ capture_id: paypalData.capture_id,
375
+ capture: paypalData.capture,
376
+ },
377
+ captured_at: new Date().toISOString(),
378
+ },
379
+ }
380
+ }
381
+
382
+ const { amount: sessionAmount, currencyCode } =
383
+ await this.normalizePaymentData(input)
384
+ // The requested (possibly partial) capture amount lives on the Medusa
385
+ // capture row, not in the provider input — resolve it so partial captures
386
+ // don't charge the full session total.
387
+ const amount = await this.resolveRequestedCaptureAmount(
388
+ input,
389
+ sessionAmount
390
+ )
391
+ // Include the amount in the idempotency suffix: PayPal deduplicates by
392
+ // PayPal-Request-Id, so two sequential partial captures of the same order
393
+ // that share an upstream idempotency_key would otherwise collide and the
394
+ // second capture would silently return the first one's result.
395
+ const requestId = this.getIdempotencyKey(
396
+ input,
397
+ `capture-${orderId}-${amount}`
398
+ )
399
+ let debugId: string | null = null
400
+
401
+ try {
402
+ const { accessToken, base } = await this.getPayPalAccessToken()
403
+ const order = await this.getOrderDetails(orderId).catch(() => null)
404
+ const existingCapture =
405
+ order?.purchase_units?.[0]?.payments?.captures?.[0]
406
+ if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
407
+ return {
408
+ data: {
409
+ ...(data || {}),
410
+ paypal: {
411
+ ...paypalData,
412
+ capture_id: existingCapture.id,
413
+ capture: existingCapture,
414
+ },
415
+ captured_at: new Date().toISOString(),
416
+ },
417
+ }
418
+ }
419
+
420
+ const resolvedIntent = String(
421
+ order?.intent || paypalData.order?.intent || data.intent || ""
422
+ ).toUpperCase()
423
+ if (!authorizationId && resolvedIntent === "AUTHORIZE") {
424
+ const authorizeResp = await paypalFetch(
425
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
426
+ {
427
+ method: "POST",
428
+ headers: {
429
+ Authorization: `Bearer ${accessToken}`,
430
+ "Content-Type": "application/json",
431
+ "PayPal-Request-Id": `${requestId}-auth`,
432
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
433
+ },
434
+ }
435
+ )
436
+ const authorizeText = await authorizeResp.text()
437
+ debugId = authorizeResp.headers.get("paypal-debug-id")
438
+ if (!authorizeResp.ok) {
439
+ throw new Error(
440
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
441
+ debugId ? ` debug_id=${debugId}` : ""
442
+ }`
443
+ )
444
+ }
445
+ const authorization = JSON.parse(authorizeText)
446
+ authorizationId =
447
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
448
+ }
449
+
450
+ const isFinalCapture =
451
+ paypalData.is_final_capture ??
452
+ data.is_final_capture ??
453
+ data.final_capture ??
454
+ undefined
455
+ const captureValue =
456
+ amount > 0 ? formatAmountForPayPal(amount, currencyCode || "EUR") : null
457
+
458
+ // `amount` and `is_final_capture` are only honored on the authorizations
459
+ // capture endpoint. The orders capture endpoint always captures the FULL
460
+ // order and silently ignores an `amount` body — so a partial amount there
461
+ // would over-capture while we record the smaller requested value. Route
462
+ // partial captures through the authorization, and fail closed if a partial
463
+ // capture is attempted against a capture-intent order.
464
+ let capturePayload: Record<string, unknown>
465
+ let captureUrl: string
466
+ if (authorizationId) {
467
+ captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
468
+ capturePayload = {
469
+ ...(captureValue
470
+ ? {
471
+ amount: {
472
+ currency_code: currencyCode || "EUR",
473
+ value: captureValue,
474
+ },
475
+ }
476
+ : {}),
477
+ ...(typeof isFinalCapture === "boolean"
478
+ ? { is_final_capture: isFinalCapture }
479
+ : {}),
480
+ }
481
+ } else {
482
+ captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
483
+ capturePayload = {}
484
+ const orderTotal = order?.purchase_units?.[0]?.amount?.value
485
+ if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
486
+ throw new Error(
487
+ `PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
488
+ `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
489
+ `AUTHORIZE to capture a partial amount.`
490
+ )
491
+ }
492
+ }
493
+
494
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the capture
495
+ // idempotent, so a retry after a network blip re-uses the same capture
496
+ // instead of double-charging.
497
+ const ppResp = await paypalFetchWithRetry(captureUrl, {
498
+ method: "POST",
499
+ headers: {
500
+ Authorization: `Bearer ${accessToken}`,
501
+ "Content-Type": "application/json",
502
+ "PayPal-Request-Id": requestId,
503
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
504
+ },
505
+ body: JSON.stringify(capturePayload),
506
+ })
507
+
508
+ const ppText = await ppResp.text()
509
+ debugId = ppResp.headers.get("paypal-debug-id")
510
+ if (!ppResp.ok) {
511
+ throw new Error(
512
+ `PayPal capture error (${ppResp.status}): ${ppText}${
513
+ debugId ? ` debug_id=${debugId}` : ""
514
+ }`
515
+ )
516
+ }
517
+
518
+ const capture = JSON.parse(ppText)
519
+
520
+ // A 2xx response does NOT mean the funds were captured. PayPal returns 201
521
+ // for captures that are PENDING (pending review / eCheck), DECLINED, or
522
+ // FAILED. Recording any of these as "captured" books money that never
523
+ // settled, so only a COMPLETED capture is treated as success.
524
+ const captureStatus = extractCaptureStatus(capture)
525
+ if (captureStatus !== "COMPLETED") {
526
+ throw new Error(
527
+ `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
528
+ `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
529
+ )
530
+ }
531
+
532
+ const captureId =
533
+ capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
534
+ const existingCaptures = Array.isArray(paypalData.captures)
535
+ ? paypalData.captures
536
+ : []
537
+ const captureEntry = {
538
+ id: captureId,
539
+ status: capture?.status,
540
+ amount: capture?.amount,
541
+ raw: capture,
542
+ }
543
+
544
+ await this.recordSuccess("capture_success")
545
+ await this.recordPaymentEvent("capture", {
546
+ order_id: orderId,
547
+ capture_id: captureId,
548
+ authorization_id: authorizationId || undefined,
549
+ amount,
550
+ currency_code: currencyCode,
551
+ request_id: requestId,
552
+ })
553
+
554
+ return {
555
+ data: {
556
+ ...(data || {}),
557
+ paypal: {
558
+ ...paypalData,
559
+ order_id: orderId,
560
+ capture_id: captureId,
561
+ capture,
562
+ authorization_id: authorizationId || paypalData.authorization_id,
563
+ captures: [...existingCaptures, captureEntry],
564
+ },
565
+ captured_at: new Date().toISOString(),
566
+ },
567
+ }
568
+ } catch (error: any) {
569
+ await this.recordFailure("capture_failed", {
570
+ order_id: orderId,
571
+ request_id: requestId,
572
+ debug_id: debugId,
573
+ message: error?.message,
574
+ })
575
+ // Surface the real reason: Medusa masks non-MedusaErrors as a generic
576
+ // "unknown error" in production, hiding the PayPal failure.
577
+ throw error instanceof MedusaError
578
+ ? error
579
+ : new MedusaError(
580
+ MedusaError.Types.INVALID_DATA,
581
+ error?.message || "PayPal capture failed."
582
+ )
583
+ }
584
+ }
585
+
586
+ async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
587
+ const data = (input.data || {}) as Record<string, any>
588
+ const paypalData = (data.paypal || {}) as Record<string, any>
589
+ const orderId = String(paypalData.order_id || data.order_id || "")
590
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
591
+ const storedAuthorizationId = String(
592
+ paypalData.authorization_id || data.authorization_id || ""
593
+ )
594
+
595
+ try {
596
+ const order = orderId ? await this.getOrderDetails(orderId) : null
597
+ const intent = String(order?.intent || "").toUpperCase()
598
+ const authorizationId =
599
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
600
+ storedAuthorizationId
601
+
602
+ if (intent === "AUTHORIZE" && authorizationId) {
603
+ const { accessToken, base } = await this.getPayPalAccessToken()
604
+ const requestId = this.getIdempotencyKey(
605
+ input,
606
+ `void-${authorizationId}`
607
+ )
608
+
609
+ const resp = await paypalFetch(
610
+ `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
611
+ {
612
+ method: "POST",
613
+ headers: {
614
+ Authorization: `Bearer ${accessToken}`,
615
+ "Content-Type": "application/json",
616
+ "PayPal-Request-Id": requestId,
617
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
618
+ },
619
+ }
620
+ )
621
+
622
+ if (!resp.ok) {
623
+ const text = await resp.text()
624
+ const debugId = resp.headers.get("paypal-debug-id")
625
+ throw new Error(
626
+ `PayPal void error (${resp.status}): ${text}${
627
+ debugId ? ` debug_id=${debugId}` : ""
628
+ }`
629
+ )
630
+ }
631
+
632
+ await this.recordSuccess("void_success")
633
+ await this.recordPaymentEvent("void", {
634
+ order_id: orderId,
635
+ authorization_id: authorizationId,
636
+ })
637
+ } else if (captureId) {
638
+ const { accessToken, base } = await this.getPayPalAccessToken()
639
+ const requestId = this.getIdempotencyKey(
640
+ input,
641
+ `cancel-refund-${captureId}`
642
+ )
643
+
644
+ const resp = await paypalFetch(
645
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
646
+ {
647
+ method: "POST",
648
+ headers: {
649
+ Authorization: `Bearer ${accessToken}`,
650
+ "Content-Type": "application/json",
651
+ "PayPal-Request-Id": requestId,
652
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
653
+ },
654
+ body: JSON.stringify({}),
655
+ }
656
+ )
657
+
658
+ if (!resp.ok) {
659
+ const text = await resp.text()
660
+ const debugId = resp.headers.get("paypal-debug-id")
661
+ throw new Error(
662
+ `PayPal refund error (${resp.status}): ${text}${
663
+ debugId ? ` debug_id=${debugId}` : ""
664
+ }`
665
+ )
666
+ }
667
+
668
+ const refund = await resp.json().catch(() => ({}))
669
+
670
+ // As with refundPayment: a 2xx response does not guarantee the refund
671
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
672
+ // `canceled_at` for a refund that never went through would record a
673
+ // cancellation while the merchant keeps the funds.
674
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
675
+ if (isRefundFailureStatus(cancelRefundStatus)) {
676
+ throw new Error(
677
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
678
+ )
679
+ }
680
+
681
+ const existingRefunds = Array.isArray(paypalData.refunds)
682
+ ? paypalData.refunds
683
+ : []
684
+ const refundEntry = {
685
+ id: refund?.id,
686
+ status: refund?.status,
687
+ amount: refund?.amount,
688
+ raw: refund,
689
+ }
690
+
691
+ await this.recordSuccess("cancel_refund_success")
692
+
693
+ return {
694
+ data: {
695
+ ...(data || {}),
696
+ paypal: {
697
+ ...paypalData,
698
+ order: order || undefined,
699
+ authorization_id: authorizationId || storedAuthorizationId,
700
+ capture_id: captureId || paypalData.capture_id,
701
+ refund_id: refund?.id,
702
+ refund_status: refund?.status,
703
+ refunds: [...existingRefunds, refundEntry],
704
+ },
705
+ canceled_at: new Date().toISOString(),
706
+ },
707
+ }
708
+ }
709
+
710
+ return {
711
+ data: {
712
+ ...(data || {}),
713
+ paypal: {
714
+ ...paypalData,
715
+ order: order || undefined,
716
+ authorization_id: authorizationId || storedAuthorizationId,
717
+ capture_id: captureId || paypalData.capture_id,
718
+ },
719
+ canceled_at: new Date().toISOString(),
720
+ },
721
+ }
722
+ } catch (error: any) {
723
+ await this.recordFailure("cancel_failed", {
724
+ order_id: orderId,
725
+ capture_id: captureId,
726
+ message: error?.message,
727
+ })
728
+ throw error
729
+ }
730
+ }
731
+
732
+ async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
733
+ const data = (input.data || {}) as Record<string, any>
734
+ const paypalData = (data.paypal || {}) as Record<string, any>
735
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
736
+ if (!captureId) {
737
+ throw new MedusaError(
738
+ MedusaError.Types.INVALID_DATA,
739
+ "PayPal capture_id is required to refund payment. No capture found in session data."
740
+ )
741
+ }
742
+
743
+ // Use the refund amount Medusa passes (top-level input), not the session
744
+ // amount in `data` — otherwise a partial refund would refund the full order.
745
+ // Medusa passes it as a BigNumberInput, so coerce it to a number; a naive
746
+ // Number() of the object form yields NaN and silently refunds the full
747
+ // capture.
748
+ const amount = toAmountNumber(input.amount)
749
+ const requestId = this.getIdempotencyKey(
750
+ input,
751
+ `refund-${captureId}-${amount}`
752
+ )
753
+ const currencyOverride = await this.resolveCurrencyOverride()
754
+ const currencyCode = normalizeCurrencyCode(
755
+ data.currency_code || currencyOverride || "EUR"
756
+ )
757
+
758
+ try {
759
+ const { accessToken, base } = await this.getPayPalAccessToken()
760
+ const refundPayload: Record<string, any> =
761
+ amount > 0
762
+ ? {
763
+ amount: {
764
+ currency_code: currencyCode,
765
+ value: formatAmountForPayPal(amount, currencyCode),
766
+ },
767
+ }
768
+ : {}
769
+
770
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
771
+ // the refund amount) makes the refund idempotent, so a retry after a
772
+ // network blip re-uses the same refund instead of double-refunding.
773
+ const resp = await paypalFetchWithRetry(
774
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
775
+ {
776
+ method: "POST",
777
+ headers: {
778
+ Authorization: `Bearer ${accessToken}`,
779
+ "Content-Type": "application/json",
780
+ "PayPal-Request-Id": requestId,
781
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
782
+ },
783
+ body: JSON.stringify(refundPayload),
784
+ }
785
+ )
786
+
787
+ const text = await resp.text()
788
+ if (!resp.ok) {
789
+ const debugId = resp.headers.get("paypal-debug-id")
790
+ throw new MedusaError(
791
+ MedusaError.Types.UNEXPECTED_STATE,
792
+ `PayPal refund error (${resp.status}): ${text}${
793
+ debugId ? ` debug_id=${debugId}` : ""
794
+ }`
795
+ )
796
+ }
797
+
798
+ const refund = JSON.parse(text)
799
+
800
+ // As with captures, a 2xx response does not guarantee the refund stuck.
801
+ // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
802
+ // recorded as a successful refund. PENDING is accepted: PayPal processes
803
+ // refunds asynchronously and a pending refund will settle.
804
+ const refundStatus = String(refund?.status || "").toUpperCase()
805
+ if (isRefundFailureStatus(refundStatus)) {
806
+ const refundDebugId = resp.headers.get("paypal-debug-id")
807
+ throw new MedusaError(
808
+ MedusaError.Types.UNEXPECTED_STATE,
809
+ `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
810
+ (refundDebugId ? ` debug_id=${refundDebugId}` : "")
811
+ )
812
+ }
813
+
814
+ const existingRefunds = Array.isArray(paypalData.refunds)
815
+ ? paypalData.refunds
816
+ : []
817
+ const refundEntry = {
818
+ id: refund?.id,
819
+ status: refund?.status,
820
+ amount: refund?.amount,
821
+ raw: refund,
822
+ }
823
+
824
+ await this.recordSuccess("refund_success")
825
+ await this.recordPaymentEvent("refund", {
826
+ capture_id: captureId,
827
+ refund_id: refund?.id,
828
+ amount,
829
+ currency_code: currencyCode,
830
+ request_id: requestId,
831
+ })
832
+
833
+ return {
834
+ data: {
835
+ ...(data || {}),
836
+ paypal: {
837
+ ...paypalData,
838
+ refund_id: refund?.id,
839
+ refund_status: refund?.status,
840
+ refunds: [...existingRefunds, refundEntry],
841
+ refund,
842
+ },
843
+ refunded_at: new Date().toISOString(),
844
+ },
845
+ }
846
+ } catch (error: any) {
847
+ await this.recordFailure("refund_failed", {
848
+ capture_id: captureId,
849
+ request_id: requestId,
850
+ message: error?.message,
851
+ })
852
+ // Surface the real reason: Medusa masks any non-MedusaError as a generic
853
+ // "An unknown error occurred." in production, hiding the PayPal failure.
854
+ throw error instanceof MedusaError
855
+ ? error
856
+ : new MedusaError(
857
+ MedusaError.Types.UNEXPECTED_STATE,
858
+ error?.message || "PayPal refund failed."
859
+ )
860
+ }
861
+ }
862
+
863
+ async retrievePayment(
864
+ input: RetrievePaymentInput
865
+ ): Promise<RetrievePaymentOutput> {
866
+ const data = (input.data || {}) as Record<string, any>
867
+ const paypalData = (data.paypal || {}) as Record<string, any>
868
+ const orderId = String(paypalData.order_id || data.order_id || "")
869
+ if (!orderId) {
870
+ return { data: { ...(data || {}) } }
871
+ }
872
+
873
+ const order = await this.getOrderDetails(orderId)
874
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
875
+ const authorization =
876
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
877
+
878
+ return {
879
+ data: {
880
+ ...(data || {}),
881
+ paypal: {
882
+ ...paypalData,
883
+ order,
884
+ authorization_id: authorization?.id || paypalData.authorization_id,
885
+ capture_id: capture?.id || paypalData.capture_id,
886
+ },
887
+ },
888
+ }
889
+ }
890
+
891
+ async getPaymentStatus(
892
+ input: GetPaymentStatusInput
893
+ ): Promise<GetPaymentStatusOutput> {
894
+ const data = (input.data || {}) as Record<string, any>
895
+ const paypalData = (data.paypal || {}) as Record<string, any>
896
+ const orderId = String(paypalData.order_id || data.order_id || "")
897
+ if (!orderId) {
898
+ return { status: "pending", data: { ...(data || {}) } }
899
+ }
900
+
901
+ const order = await this.getOrderDetails(orderId)
902
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
903
+ const authorization =
904
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
905
+ const mappedStatus =
906
+ this.mapCaptureStatus(capture?.status) ||
907
+ this.mapAuthorizationStatus(authorization?.status) ||
908
+ this.mapOrderStatus(order?.status) ||
909
+ "pending"
910
+
911
+ return {
912
+ status: mappedStatus,
913
+ data: {
914
+ ...(data || {}),
915
+ paypal: {
916
+ ...paypalData,
917
+ order,
918
+ authorization_id: authorization?.id || paypalData.authorization_id,
919
+ capture_id: capture?.id || paypalData.capture_id,
920
+ },
921
+ },
922
+ }
923
+ }
924
+ }
925
+
926
+ export default PayPalAdvancedCardProvider
927
+ export { PayPalAdvancedCardProvider }