@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,836 +1,906 @@
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 PayPalPaymentProvider extends PayPalProviderBase {
35
- static identifier = "paypal"
36
-
37
- protected readonly sessionPrefix = "pp"
38
- protected readonly idempotencyPrefix = "pp"
39
-
40
- async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
41
- const providerId = (input.data as Record<string, any> | undefined)?.provider_id
42
- try {
43
- const currencyOverride = await this.resolveCurrencyOverride()
44
- const currencyCode = normalizeCurrencyCode(
45
- input.currency_code || currencyOverride || "EUR"
46
- )
47
- assertPayPalCurrencySupported({
48
- currencyCode,
49
- paypalCurrencyOverride: currencyOverride,
50
- })
51
- return {
52
- id: this.generateSessionId(),
53
- data: {
54
- ...(input.data || {}),
55
- ...(providerId ? { provider_id: providerId } : {}),
56
- amount: input.amount,
57
- currency_code: currencyCode,
58
- },
59
- }
60
- } catch (error) {
61
- await this.recordFailure("initiate_failed", {
62
- error: this.serializeError(error),
63
- currency_code: input.currency_code,
64
- amount: input.amount,
65
- provider_id: providerId,
66
- data: input.data ?? null,
67
- })
68
- throw error
69
- }
70
- }
71
-
72
- async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
73
- const currencyOverride = await this.resolveCurrencyOverride()
74
- const currencyCode = normalizeCurrencyCode(
75
- input.currency_code || currencyOverride || "EUR"
76
- )
77
- assertPayPalCurrencySupported({
78
- currencyCode,
79
- paypalCurrencyOverride: currencyOverride,
80
- })
81
- const providerId = (input.data as Record<string, any> | undefined)?.provider_id
82
- return {
83
- data: {
84
- ...(input.data || {}),
85
- ...this.invalidateStaleOrder(input, currencyCode),
86
- ...(providerId ? { provider_id: providerId } : {}),
87
- amount: input.amount,
88
- currency_code: currencyCode,
89
- },
90
- }
91
- }
92
-
93
- async authorizePayment(
94
- input: AuthorizePaymentInput
95
- ): Promise<AuthorizePaymentOutput> {
96
- const { data } = await this.normalizePaymentData(input)
97
- const existingPayPal = (data.paypal || {}) as Record<string, any>
98
-
99
- // Session already carries a settled capture: trust it without a network
100
- // round-trip. The stored capture object is only written after a COMPLETED
101
- // gate (capture-order route / capturePayment), but re-verify its status
102
- // here so a PENDING/DECLINED capture patched in by a webhook is never
103
- // booked as captured money.
104
- const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
105
- if (storedCaptureStatus === "COMPLETED") {
106
- console.info("[PayPal] authorizePayment: session already captured (COMPLETED)")
107
- return {
108
- status: "captured",
109
- data: {
110
- ...(input.data || {}),
111
- captured_at: (data as any).captured_at || new Date().toISOString(),
112
- },
113
- }
114
- }
115
-
116
- const orderId = String(existingPayPal.order_id || data.order_id || "")
117
- if (orderId) {
118
- try {
119
- console.info("[PayPal] authorizePayment: fetching live order status for", orderId)
120
- const order = await this.getOrderDetails(orderId)
121
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
122
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
123
-
124
- // Derive the returned status from what actually happened at PayPal —
125
- // NOT from the mere presence of a capture/authorization id and NOT
126
- // from the merchant's configured paymentAction. A PENDING capture
127
- // (eCheck / pending review) must not be booked as captured, and a
128
- // DENIED/DECLINED one must fail the authorization outright.
129
- if (capture?.id) {
130
- const captureStatus = this.mapCaptureStatus(capture?.status)
131
- if (captureStatus === "captured") {
132
- return {
133
- status: "captured",
134
- data: {
135
- ...(input.data || {}),
136
- paypal: {
137
- ...existingPayPal,
138
- order_id: orderId,
139
- order,
140
- authorization_id: authorization?.id || existingPayPal.authorization_id,
141
- capture_id: capture.id,
142
- capture,
143
- },
144
- captured_at: new Date().toISOString(),
145
- },
146
- }
147
- }
148
- if (captureStatus === "pending") {
149
- // Funds are in flight (eCheck etc.): place the order as authorized
150
- // so checkout completes, but never mark it captured — the
151
- // CAPTURE.COMPLETED webhook settles it later.
152
- return {
153
- status: "authorized",
154
- data: {
155
- ...(input.data || {}),
156
- paypal: {
157
- ...existingPayPal,
158
- order_id: orderId,
159
- order,
160
- capture_id: capture.id,
161
- },
162
- authorized_at: new Date().toISOString(),
163
- },
164
- }
165
- }
166
- if (captureStatus === "error" || captureStatus === "canceled") {
167
- return {
168
- status: "error",
169
- data: {
170
- ...(input.data || {}),
171
- paypal: { ...existingPayPal, order_id: orderId, order },
172
- },
173
- }
174
- }
175
- }
176
-
177
- if (authorization?.id) {
178
- const authStatus = this.mapAuthorizationStatus(authorization?.status)
179
- if (authStatus === "authorized") {
180
- return {
181
- status: "authorized",
182
- data: {
183
- ...(input.data || {}),
184
- paypal: {
185
- ...existingPayPal,
186
- order_id: orderId,
187
- order,
188
- authorization_id: authorization.id,
189
- },
190
- authorized_at: new Date().toISOString(),
191
- },
192
- }
193
- }
194
- if (authStatus === "error" || authStatus === "canceled") {
195
- return {
196
- status: "error",
197
- data: {
198
- ...(input.data || {}),
199
- paypal: { ...existingPayPal, order_id: orderId, order },
200
- },
201
- }
202
- }
203
- }
204
-
205
- // Only a buyer-APPROVED order counts as authorized. CREATED/SAVED
206
- // means the buyer never approved the payment — treating those as
207
- // authorized would let a cart complete with no funds authorized at
208
- // PayPal at all.
209
- if (String(order?.status || "").toUpperCase() === "APPROVED") {
210
- console.info("[PayPal] authorizePayment: order approved, marking authorized")
211
- return {
212
- status: "authorized",
213
- data: {
214
- ...(input.data || {}),
215
- paypal: {
216
- ...existingPayPal,
217
- order_id: orderId,
218
- order,
219
- },
220
- authorized_at: new Date().toISOString(),
221
- },
222
- }
223
- }
224
- } catch (e: any) {
225
- console.warn("[PayPal] authorizePayment: order lookup failed:", e?.message)
226
- // Fall back to the session's own record when PayPal is unreachable so a
227
- // transient lookup error doesn't fail a checkout that already has a
228
- // real authorization/capture behind it. `captured_at` is only ever
229
- // stamped after a COMPLETED gate; a bare capture_id (e.g. patched in by
230
- // a webhook) or authorization id maps to "authorized" — the order is
231
- // placed without claiming settled funds.
232
- if ((data as any).captured_at) {
233
- return {
234
- status: "captured",
235
- data: { ...(input.data || {}), captured_at: (data as any).captured_at },
236
- }
237
- }
238
- if (
239
- existingPayPal.capture_id ||
240
- existingPayPal.authorization_id ||
241
- (data as any).authorized_at
242
- ) {
243
- return {
244
- status: "authorized",
245
- data: {
246
- ...(input.data || {}),
247
- authorized_at: (data as any).authorized_at || new Date().toISOString(),
248
- },
249
- }
250
- }
251
- }
252
- }
253
-
254
- // No usable PayPal order on the session: nothing can be authorized. The
255
- // previous fallback created a brand-new PayPal order here and immediately
256
- // called /v2/checkout/orders/{id}/authorize on it — but an order no buyer
257
- // has approved can never be authorized (PayPal rejects it with
258
- // ORDER_NOT_APPROVED), so that path only produced confusing 422s and
259
- // orphaned PayPal orders. Fail with a clear, actionable error instead.
260
- await this.recordFailure("authorize_failed", {
261
- cart_id: data.cart_id,
262
- payment_collection_id: data.payment_collection_id,
263
- message: "no approved PayPal order on session",
264
- })
265
- throw new MedusaError(
266
- MedusaError.Types.NOT_ALLOWED,
267
- "No approved PayPal payment was found for this session. The buyer must approve the payment with PayPal before the cart can be completed."
268
- )
269
- }
270
-
271
- async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
272
- const data = (input.data || {}) as Record<string, any>
273
- const paypalData = (data.paypal || {}) as Record<string, any>
274
- const orderId = String(paypalData.order_id || data.order_id || "")
275
- if (!orderId) {
276
- return { data: { ...(input.data || {}) } }
277
- }
278
-
279
- const order = await this.getOrderDetails(orderId)
280
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
281
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
282
-
283
- return {
284
- data: {
285
- ...(input.data || {}),
286
- paypal: {
287
- ...((input.data || {}).paypal as Record<string, unknown>),
288
- order,
289
- authorization_id: authorization?.id || paypalData.authorization_id,
290
- capture_id: capture?.id || paypalData.capture_id,
291
- },
292
- },
293
- }
294
- }
295
-
296
- async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
297
- const data = (input.data || {}) as Record<string, any>
298
- const paypalData = (data.paypal || {}) as Record<string, any>
299
- const orderId = String(paypalData.order_id || data.order_id || "")
300
- if (!orderId) {
301
- return { status: "pending", data: { ...(input.data || {}) } }
302
- }
303
-
304
- try {
305
- const order = await this.getOrderDetails(orderId)
306
- const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
307
- const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
308
- const mappedStatus =
309
- this.mapCaptureStatus(capture?.status) ||
310
- this.mapAuthorizationStatus(authorization?.status) ||
311
- this.mapOrderStatus(order?.status) ||
312
- "pending"
313
-
314
- await this.recordSuccess("status_success")
315
- return {
316
- status: mappedStatus,
317
- data: {
318
- ...(input.data || {}),
319
- paypal: {
320
- ...((input.data || {}).paypal as Record<string, unknown>),
321
- order,
322
- authorization_id: authorization?.id || paypalData.authorization_id,
323
- capture_id: capture?.id || paypalData.capture_id,
324
- },
325
- },
326
- }
327
- } catch (error: any) {
328
- await this.recordFailure("status_failed", {
329
- order_id: orderId,
330
- message: error?.message,
331
- })
332
- throw error
333
- }
334
- }
335
-
336
- async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
337
- const data = (input.data || {}) as Record<string, any>
338
- const paypalData = (data.paypal || {}) as Record<string, any>
339
- const orderId = String(paypalData.order_id || data.order_id || "")
340
- let authorizationId = String(
341
- paypalData.authorization_id || data.authorization_id || ""
342
- )
343
- if (!orderId) {
344
- throw new Error("PayPal order_id is required to capture payment")
345
- }
346
-
347
- if (paypalData.capture_id || paypalData.capture) {
348
- return {
349
- data: {
350
- ...(input.data || {}),
351
- paypal: {
352
- ...((input.data || {}).paypal as Record<string, unknown>),
353
- capture_id: paypalData.capture_id,
354
- capture: paypalData.capture,
355
- },
356
- captured_at: new Date().toISOString(),
357
- },
358
- }
359
- }
360
-
361
- const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(input)
362
- // The requested (possibly partial) capture amount lives on the Medusa
363
- // capture row, not in the provider input — resolve it so partial captures
364
- // don't charge the full session total.
365
- const amount = await this.resolveRequestedCaptureAmount(input, sessionAmount)
366
- // Include the amount in the idempotency suffix: PayPal deduplicates by
367
- // PayPal-Request-Id, so two sequential partial captures of the same order
368
- // that share an upstream idempotency_key would otherwise collide and the
369
- // second capture would silently return the first one's result.
370
- const requestId = this.getIdempotencyKey(input, `capture-${orderId}-${amount}`)
371
- let debugId: string | null = null
372
-
373
- try {
374
- const { accessToken, base } = await this.getPayPalAccessToken()
375
- const order = await this.getOrderDetails(orderId).catch(() => null)
376
- const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
377
- if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
378
- return {
379
- data: {
380
- ...(input.data || {}),
381
- paypal: {
382
- ...((input.data || {}).paypal as Record<string, unknown>),
383
- capture_id: existingCapture.id,
384
- capture: existingCapture,
385
- },
386
- captured_at: new Date().toISOString(),
387
- },
388
- }
389
- }
390
-
391
- const resolvedIntent = String(
392
- order?.intent || paypalData.order?.intent || data.intent || ""
393
- ).toUpperCase()
394
-
395
- if (!authorizationId && resolvedIntent === "AUTHORIZE") {
396
- const authorizeResp = await paypalFetch(
397
- `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
398
- {
399
- method: "POST",
400
- headers: {
401
- Authorization: `Bearer ${accessToken}`,
402
- "Content-Type": "application/json",
403
- "PayPal-Request-Id": `${requestId}-auth`,
404
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
405
- },
406
- }
407
- )
408
- const authorizeText = await authorizeResp.text()
409
- debugId = authorizeResp.headers.get("paypal-debug-id")
410
- if (!authorizeResp.ok) {
411
- throw new Error(
412
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
413
- debugId ? ` debug_id=${debugId}` : ""
414
- }`
415
- )
416
- }
417
- const authorization = JSON.parse(authorizeText)
418
- authorizationId =
419
- authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
420
- }
421
-
422
- const isFinalCapture =
423
- paypalData.is_final_capture ??
424
- data.is_final_capture ??
425
- data.final_capture ??
426
- undefined
427
- const captureValue = amount > 0
428
- ? formatAmountForPayPal(amount, currencyCode || "EUR")
429
- : null
430
-
431
- // `amount` and `is_final_capture` are only valid on the authorizations
432
- // capture endpoint. The orders capture endpoint always captures the FULL
433
- // order and silently ignores an `amount` body — so sending a partial
434
- // amount there would over-capture while we record the (smaller) requested
435
- // value. Route partial captures to the authorization, and fail closed if a
436
- // partial capture is attempted against a capture-intent order.
437
- let capturePayload: Record<string, unknown>
438
- let captureUrl: string
439
- if (authorizationId) {
440
- captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
441
- capturePayload = {
442
- ...(captureValue
443
- ? { amount: { currency_code: currencyCode || "EUR", value: captureValue } }
444
- : {}),
445
- ...(typeof isFinalCapture === "boolean" ? { is_final_capture: isFinalCapture } : {}),
446
- }
447
- } else {
448
- captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
449
- capturePayload = {}
450
- const orderTotal = order?.purchase_units?.[0]?.amount?.value
451
- if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
452
- throw new Error(
453
- `PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
454
- `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
455
- `AUTHORIZE to capture a partial amount.`
456
- )
457
- }
458
- }
459
-
460
- // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
461
- // capture idempotent, so a retry after a network blip re-uses the same
462
- // capture instead of double-charging.
463
- const ppResp = await paypalFetchWithRetry(captureUrl, {
464
- method: "POST",
465
- headers: {
466
- Authorization: `Bearer ${accessToken}`,
467
- "Content-Type": "application/json",
468
- "PayPal-Request-Id": requestId,
469
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
470
- },
471
- body: JSON.stringify(capturePayload),
472
- })
473
-
474
- const ppText = await ppResp.text()
475
- debugId = ppResp.headers.get("paypal-debug-id")
476
- if (!ppResp.ok) {
477
- throw new Error(
478
- `PayPal capture error (${ppResp.status}): ${ppText}${
479
- debugId ? ` debug_id=${debugId}` : ""
480
- }`
481
- )
482
- }
483
-
484
- const capture = JSON.parse(ppText)
485
-
486
- // A 2xx response does NOT mean the funds were captured. PayPal returns 201
487
- // for captures that are PENDING (e.g. pending review / eCheck), DECLINED,
488
- // or FAILED. Recording any of these as "captured" books money that never
489
- // settled, so only a COMPLETED capture is treated as success.
490
- const captureStatus = extractCaptureStatus(capture)
491
- if (captureStatus !== "COMPLETED") {
492
- throw new Error(
493
- `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
494
- `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
495
- )
496
- }
497
-
498
- const captureId =
499
- capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
500
- const existingCaptures = Array.isArray(paypalData.captures) ? paypalData.captures : []
501
- const captureEntry = {
502
- id: captureId,
503
- status: capture?.status,
504
- amount: capture?.amount,
505
- raw: capture,
506
- }
507
-
508
- await this.recordSuccess("capture_success")
509
- await this.recordPaymentEvent("capture", {
510
- order_id: orderId,
511
- capture_id: captureId,
512
- authorization_id: authorizationId || undefined,
513
- amount,
514
- currency_code: currencyCode,
515
- request_id: requestId,
516
- })
517
-
518
- return {
519
- data: {
520
- ...(input.data || {}),
521
- paypal: {
522
- ...((input.data || {}).paypal as Record<string, unknown>),
523
- order_id: orderId,
524
- capture_id: captureId,
525
- capture,
526
- authorization_id: authorizationId || paypalData.authorization_id,
527
- captures: [...existingCaptures, captureEntry],
528
- },
529
- captured_at: new Date().toISOString(),
530
- },
531
- }
532
- } catch (error: any) {
533
- await this.recordFailure("capture_failed", {
534
- order_id: orderId,
535
- request_id: requestId,
536
- debug_id: debugId,
537
- message: error?.message,
538
- })
539
- throw error instanceof MedusaError
540
- ? error
541
- : new MedusaError(
542
- MedusaError.Types.INVALID_DATA,
543
- error?.message || "PayPal capture failed."
544
- )
545
- }
546
- }
547
-
548
- async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
549
- const data = (input.data || {}) as Record<string, any>
550
- const paypalData = (data.paypal || {}) as Record<string, any>
551
- const captureId = String(paypalData.capture_id || data.capture_id || "")
552
- const refundReason = String(
553
- paypalData.refund_reason || data.refund_reason || data.reason || ""
554
- ).trim()
555
- const refundReasonCode = String(
556
- paypalData.refund_reason_code || data.refund_reason_code || data.reason_code || ""
557
- ).trim()
558
- if (!captureId) {
559
- throw new MedusaError(
560
- MedusaError.Types.INVALID_DATA,
561
- "PayPal capture_id is required to refund payment. No capture found in session data."
562
- )
563
- }
564
-
565
- // Medusa passes the refund amount as a BigNumberInput (BigNumber instance or
566
- // serialized { value, precision }); coerce it to a number so partial refunds
567
- // send the correct value instead of silently refunding the full capture.
568
- const refundAmount = toAmountNumber(input.amount)
569
-
570
- // Include the amount in the idempotency suffix so two sequential partial
571
- // refunds of the same capture are not deduplicated by PayPal into one.
572
- const requestId = this.getIdempotencyKey(
573
- input,
574
- `refund-${captureId}-${refundAmount}`
575
- )
576
-
577
- const currencyOverride = await this.resolveCurrencyOverride()
578
- const currencyCode = normalizeCurrencyCode(
579
- data.currency_code || currencyOverride || "EUR"
580
- )
581
-
582
- const refundValue = refundAmount > 0
583
- ? formatAmountForPayPal(refundAmount, currencyCode)
584
- : null
585
-
586
- let debugId: string | null = null
587
-
588
- try {
589
- const { accessToken, base } = await this.getPayPalAccessToken()
590
- const refundPayload: Record<string, any> =
591
- refundValue
592
- ? {
593
- amount: {
594
- currency_code: currencyCode || "EUR",
595
- value: refundValue,
596
- },
597
- }
598
- : {}
599
-
600
- if (refundReason) {
601
- // PayPal rejects a note_to_payer longer than 255 characters with a 422
602
- // (which would otherwise fail the whole refund); truncate defensively.
603
- refundPayload.note_to_payer = refundReason.slice(0, 255)
604
- }
605
-
606
- // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
607
- // the refund amount) makes the refund idempotent, so a retry after a
608
- // network blip re-uses the same refund instead of double-refunding.
609
- const ppResp = await paypalFetchWithRetry(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
610
- method: "POST",
611
- headers: {
612
- Authorization: `Bearer ${accessToken}`,
613
- "Content-Type": "application/json",
614
- "PayPal-Request-Id": requestId,
615
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
616
- },
617
- body: JSON.stringify(refundPayload),
618
- })
619
-
620
- const ppText = await ppResp.text()
621
- debugId = ppResp.headers.get("paypal-debug-id")
622
- if (!ppResp.ok) {
623
- throw new Error(
624
- `PayPal refund error (${ppResp.status}): ${ppText}${
625
- debugId ? ` debug_id=${debugId}` : ""
626
- }`
627
- )
628
- }
629
-
630
- const refund = JSON.parse(ppText)
631
-
632
- // As with captures, a 2xx response does not guarantee the refund stuck.
633
- // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
634
- // recorded as a successful refund. PENDING is accepted: PayPal processes
635
- // refunds asynchronously and a pending refund will settle.
636
- const refundStatus = String(refund?.status || "").toUpperCase()
637
- if (isRefundFailureStatus(refundStatus)) {
638
- throw new Error(
639
- `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
640
- (debugId ? ` debug_id=${debugId}` : "")
641
- )
642
- }
643
-
644
- const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
645
- const refundEntry = {
646
- id: refund?.id,
647
- status: refund?.status,
648
- amount: refund?.amount,
649
- reason: refundReason || refund?.note_to_payer,
650
- reason_code: refundReasonCode || refund?.reason_code,
651
- raw: refund,
652
- }
653
-
654
- await this.recordSuccess("refund_success")
655
- await this.recordPaymentEvent("refund", {
656
- capture_id: captureId,
657
- refund_id: refund?.id,
658
- amount: refundAmount,
659
- currency_code: currencyCode,
660
- request_id: requestId,
661
- reason: refundReason,
662
- reason_code: refundReasonCode,
663
- })
664
-
665
- return {
666
- data: {
667
- ...(input.data || {}),
668
- paypal: {
669
- ...((input.data || {}).paypal as Record<string, unknown>),
670
- refund_id: refund?.id,
671
- refund_status: refund?.status,
672
- refund_reason: refundReason || refund?.note_to_payer,
673
- refund_reason_code: refundReasonCode || refund?.reason_code,
674
- refunds: [...existingRefunds, refundEntry],
675
- refund,
676
- },
677
- refunded_at: new Date().toISOString(),
678
- },
679
- }
680
- } catch (error: any) {
681
- await this.recordFailure("refund_failed", {
682
- capture_id: captureId,
683
- request_id: requestId,
684
- debug_id: debugId,
685
- message: error?.message,
686
- })
687
- throw error instanceof MedusaError
688
- ? error
689
- : new MedusaError(
690
- MedusaError.Types.INVALID_DATA,
691
- error?.message || "PayPal refund failed."
692
- )
693
- }
694
- }
695
-
696
- async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
697
- const data = (input.data || {}) as Record<string, any>
698
- const paypalData = (data.paypal || {}) as Record<string, any>
699
- const orderId = String(paypalData.order_id || data.order_id || "")
700
- const captureId = String(paypalData.capture_id || data.capture_id || "")
701
- const storedAuthorizationId = String(
702
- paypalData.authorization_id || data.authorization_id || ""
703
- )
704
- let debugId: string | null = null
705
-
706
- try {
707
- const order = orderId ? await this.getOrderDetails(orderId) : null
708
- const intent = String(order?.intent || "").toUpperCase()
709
- const authorizationId =
710
- order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
711
- storedAuthorizationId
712
-
713
- if (intent === "AUTHORIZE" && authorizationId) {
714
- const { accessToken, base } = await this.getPayPalAccessToken()
715
- const requestId = this.getIdempotencyKey(input, `void-${authorizationId}`)
716
-
717
- const resp = await paypalFetch(
718
- `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
719
- {
720
- method: "POST",
721
- headers: {
722
- Authorization: `Bearer ${accessToken}`,
723
- "Content-Type": "application/json",
724
- "PayPal-Request-Id": requestId,
725
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
726
- },
727
- }
728
- )
729
-
730
- if (!resp.ok) {
731
- const text = await resp.text()
732
- debugId = resp.headers.get("paypal-debug-id")
733
- throw new Error(
734
- `PayPal void error (${resp.status}): ${text}${
735
- debugId ? ` debug_id=${debugId}` : ""
736
- }`
737
- )
738
- }
739
-
740
- await this.recordSuccess("void_success")
741
- await this.recordPaymentEvent("void", {
742
- order_id: orderId,
743
- authorization_id: authorizationId,
744
- })
745
- } else if (captureId) {
746
- const { accessToken, base } = await this.getPayPalAccessToken()
747
- const requestId = this.getIdempotencyKey(input, `cancel-refund-${captureId}`)
748
-
749
- const resp = await paypalFetch(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
750
- method: "POST",
751
- headers: {
752
- Authorization: `Bearer ${accessToken}`,
753
- "Content-Type": "application/json",
754
- "PayPal-Request-Id": requestId,
755
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
756
- },
757
- body: JSON.stringify({}),
758
- })
759
-
760
- if (!resp.ok) {
761
- const text = await resp.text()
762
- debugId = resp.headers.get("paypal-debug-id")
763
- throw new Error(
764
- `PayPal refund error (${resp.status}): ${text}${
765
- debugId ? ` debug_id=${debugId}` : ""
766
- }`
767
- )
768
- }
769
-
770
- const refund = await resp.json().catch(() => ({}))
771
-
772
- // As with refundPayment: a 2xx response does not guarantee the refund
773
- // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
774
- // `canceled_at` for a refund that never went through would record a
775
- // cancellation while the merchant keeps the funds.
776
- const cancelRefundStatus = String(refund?.status || "").toUpperCase()
777
- if (isRefundFailureStatus(cancelRefundStatus)) {
778
- throw new Error(
779
- `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
780
- )
781
- }
782
-
783
- const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
784
- const refundEntry = {
785
- id: refund?.id,
786
- status: refund?.status,
787
- amount: refund?.amount,
788
- raw: refund,
789
- }
790
-
791
- await this.recordSuccess("cancel_refund_success")
792
-
793
- return {
794
- data: {
795
- ...(input.data || {}),
796
- paypal: {
797
- ...((input.data || {}).paypal as Record<string, unknown>),
798
- order: order || undefined,
799
- authorization_id: authorizationId || storedAuthorizationId,
800
- capture_id: captureId || paypalData.capture_id,
801
- refund_id: refund?.id,
802
- refund_status: refund?.status,
803
- refunds: [...existingRefunds, refundEntry],
804
- },
805
- canceled_at: new Date().toISOString(),
806
- },
807
- }
808
- }
809
-
810
- return {
811
- data: {
812
- ...(input.data || {}),
813
- paypal: {
814
- ...((input.data || {}).paypal as Record<string, unknown>),
815
- order: order || undefined,
816
- authorization_id: authorizationId || storedAuthorizationId,
817
- capture_id: captureId || paypalData.capture_id,
818
- },
819
- canceled_at: new Date().toISOString(),
820
- },
821
- }
822
- } catch (error: any) {
823
- await this.recordFailure("cancel_failed", {
824
- order_id: orderId,
825
- capture_id: captureId,
826
- debug_id: debugId,
827
- message: error?.message,
828
- })
829
- throw error
830
- }
831
- }
832
-
833
- }
834
-
835
- export default PayPalPaymentProvider
836
- export { PayPalPaymentProvider }
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 wallet (Smart Buttons) payment provider — `pp_paypal_paypal`.
36
+ *
37
+ * The storefront creates and approves the PayPal order through the
38
+ * `/store/paypal/create-order` + `/store/paypal/capture-order` routes; this
39
+ * provider then authorizes/captures/refunds/cancels against the order id
40
+ * stored on the payment session.
41
+ */
42
+ class PayPalPaymentProvider extends PayPalProviderBase {
43
+ static identifier = "paypal"
44
+
45
+ protected readonly sessionPrefix = "pp"
46
+ protected readonly idempotencyPrefix = "pp"
47
+
48
+ async initiatePayment(
49
+ input: InitiatePaymentInput
50
+ ): Promise<InitiatePaymentOutput> {
51
+ const providerId = (input.data as Record<string, any> | undefined)
52
+ ?.provider_id
53
+ try {
54
+ const currencyOverride = await this.resolveCurrencyOverride()
55
+ const currencyCode = normalizeCurrencyCode(
56
+ input.currency_code || currencyOverride || "EUR"
57
+ )
58
+ assertPayPalCurrencySupported({
59
+ currencyCode,
60
+ paypalCurrencyOverride: currencyOverride,
61
+ })
62
+ return {
63
+ id: this.generateSessionId(),
64
+ data: {
65
+ ...(input.data || {}),
66
+ ...(providerId ? { provider_id: providerId } : {}),
67
+ amount: input.amount,
68
+ currency_code: currencyCode,
69
+ },
70
+ }
71
+ } catch (error) {
72
+ await this.recordFailure("initiate_failed", {
73
+ error: this.serializeError(error),
74
+ currency_code: input.currency_code,
75
+ amount: input.amount,
76
+ provider_id: providerId,
77
+ data: input.data ?? null,
78
+ })
79
+ throw error
80
+ }
81
+ }
82
+
83
+ async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
84
+ const currencyOverride = await this.resolveCurrencyOverride()
85
+ const currencyCode = normalizeCurrencyCode(
86
+ input.currency_code || currencyOverride || "EUR"
87
+ )
88
+ assertPayPalCurrencySupported({
89
+ currencyCode,
90
+ paypalCurrencyOverride: currencyOverride,
91
+ })
92
+ const providerId = (input.data as Record<string, any> | undefined)
93
+ ?.provider_id
94
+ return {
95
+ data: {
96
+ ...(input.data || {}),
97
+ ...this.invalidateStaleOrder(input, currencyCode),
98
+ ...(providerId ? { provider_id: providerId } : {}),
99
+ amount: input.amount,
100
+ currency_code: currencyCode,
101
+ },
102
+ }
103
+ }
104
+
105
+ async authorizePayment(
106
+ input: AuthorizePaymentInput
107
+ ): Promise<AuthorizePaymentOutput> {
108
+ const { data } = await this.normalizePaymentData(input)
109
+ const existingPayPal = (data.paypal || {}) as Record<string, any>
110
+
111
+ // Session already carries a settled capture: trust it without a network
112
+ // round-trip. The stored capture object is only written after a COMPLETED
113
+ // gate (capture-order route / capturePayment), but re-verify its status
114
+ // here so a PENDING/DECLINED capture patched in by a webhook is never
115
+ // booked as captured money.
116
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
117
+ if (storedCaptureStatus === "COMPLETED") {
118
+ console.info(
119
+ "[PayPal] authorizePayment: session already captured (COMPLETED)"
120
+ )
121
+ return {
122
+ status: "captured",
123
+ data: {
124
+ ...(input.data || {}),
125
+ captured_at: (data as any).captured_at || new Date().toISOString(),
126
+ },
127
+ }
128
+ }
129
+
130
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
131
+ if (orderId) {
132
+ try {
133
+ console.info(
134
+ "[PayPal] authorizePayment: fetching live order status for",
135
+ orderId
136
+ )
137
+ const order = await this.getOrderDetails(orderId)
138
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
139
+ const authorization =
140
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
141
+
142
+ // Derive the returned status from what actually happened at PayPal —
143
+ // NOT from the mere presence of a capture/authorization id and NOT
144
+ // from the merchant's configured paymentAction. A PENDING capture
145
+ // (eCheck / pending review) must not be booked as captured, and a
146
+ // DENIED/DECLINED one must fail the authorization outright.
147
+ if (capture?.id) {
148
+ const captureStatus = this.mapCaptureStatus(capture?.status)
149
+ if (captureStatus === "captured") {
150
+ return {
151
+ status: "captured",
152
+ data: {
153
+ ...(input.data || {}),
154
+ paypal: {
155
+ ...existingPayPal,
156
+ order_id: orderId,
157
+ order,
158
+ authorization_id:
159
+ authorization?.id || existingPayPal.authorization_id,
160
+ capture_id: capture.id,
161
+ capture,
162
+ },
163
+ captured_at: new Date().toISOString(),
164
+ },
165
+ }
166
+ }
167
+ if (captureStatus === "pending") {
168
+ // Funds are in flight (eCheck etc.): place the order as authorized
169
+ // so checkout completes, but never mark it captured — the
170
+ // CAPTURE.COMPLETED webhook settles it later.
171
+ return {
172
+ status: "authorized",
173
+ data: {
174
+ ...(input.data || {}),
175
+ paypal: {
176
+ ...existingPayPal,
177
+ order_id: orderId,
178
+ order,
179
+ capture_id: capture.id,
180
+ },
181
+ authorized_at: new Date().toISOString(),
182
+ },
183
+ }
184
+ }
185
+ if (captureStatus === "error" || captureStatus === "canceled") {
186
+ return {
187
+ status: "error",
188
+ data: {
189
+ ...(input.data || {}),
190
+ paypal: { ...existingPayPal, order_id: orderId, order },
191
+ },
192
+ }
193
+ }
194
+ }
195
+
196
+ if (authorization?.id) {
197
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
198
+ if (authStatus === "authorized") {
199
+ return {
200
+ status: "authorized",
201
+ data: {
202
+ ...(input.data || {}),
203
+ paypal: {
204
+ ...existingPayPal,
205
+ order_id: orderId,
206
+ order,
207
+ authorization_id: authorization.id,
208
+ },
209
+ authorized_at: new Date().toISOString(),
210
+ },
211
+ }
212
+ }
213
+ if (authStatus === "error" || authStatus === "canceled") {
214
+ return {
215
+ status: "error",
216
+ data: {
217
+ ...(input.data || {}),
218
+ paypal: { ...existingPayPal, order_id: orderId, order },
219
+ },
220
+ }
221
+ }
222
+ }
223
+
224
+ // Only a buyer-APPROVED order counts as authorized. CREATED/SAVED
225
+ // means the buyer never approved the payment — treating those as
226
+ // authorized would let a cart complete with no funds authorized at
227
+ // PayPal at all.
228
+ if (String(order?.status || "").toUpperCase() === "APPROVED") {
229
+ console.info(
230
+ "[PayPal] authorizePayment: order approved, marking authorized"
231
+ )
232
+ return {
233
+ status: "authorized",
234
+ data: {
235
+ ...(input.data || {}),
236
+ paypal: {
237
+ ...existingPayPal,
238
+ order_id: orderId,
239
+ order,
240
+ },
241
+ authorized_at: new Date().toISOString(),
242
+ },
243
+ }
244
+ }
245
+ } catch (e: any) {
246
+ console.warn(
247
+ "[PayPal] authorizePayment: order lookup failed:",
248
+ e?.message
249
+ )
250
+ // Fall back to the session's own record when PayPal is unreachable so a
251
+ // transient lookup error doesn't fail a checkout that already has a
252
+ // real authorization/capture behind it. `captured_at` is only ever
253
+ // stamped after a COMPLETED gate; a bare capture_id (e.g. patched in by
254
+ // a webhook) or authorization id maps to "authorized" — the order is
255
+ // placed without claiming settled funds.
256
+ if ((data as any).captured_at) {
257
+ return {
258
+ status: "captured",
259
+ data: {
260
+ ...(input.data || {}),
261
+ captured_at: (data as any).captured_at,
262
+ },
263
+ }
264
+ }
265
+ if (
266
+ existingPayPal.capture_id ||
267
+ existingPayPal.authorization_id ||
268
+ (data as any).authorized_at
269
+ ) {
270
+ return {
271
+ status: "authorized",
272
+ data: {
273
+ ...(input.data || {}),
274
+ authorized_at:
275
+ (data as any).authorized_at || new Date().toISOString(),
276
+ },
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ // No usable PayPal order on the session: nothing can be authorized. The
283
+ // previous fallback created a brand-new PayPal order here and immediately
284
+ // called /v2/checkout/orders/{id}/authorize on it — but an order no buyer
285
+ // has approved can never be authorized (PayPal rejects it with
286
+ // ORDER_NOT_APPROVED), so that path only produced confusing 422s and
287
+ // orphaned PayPal orders. Fail with a clear, actionable error instead.
288
+ await this.recordFailure("authorize_failed", {
289
+ cart_id: data.cart_id,
290
+ payment_collection_id: data.payment_collection_id,
291
+ message: "no approved PayPal order on session",
292
+ })
293
+ throw new MedusaError(
294
+ MedusaError.Types.NOT_ALLOWED,
295
+ "No approved PayPal payment was found for this session. The buyer must approve the payment with PayPal before the cart can be completed."
296
+ )
297
+ }
298
+
299
+ async retrievePayment(
300
+ input: RetrievePaymentInput
301
+ ): Promise<RetrievePaymentOutput> {
302
+ const data = (input.data || {}) as Record<string, any>
303
+ const paypalData = (data.paypal || {}) as Record<string, any>
304
+ const orderId = String(paypalData.order_id || data.order_id || "")
305
+ if (!orderId) {
306
+ return { data: { ...(input.data || {}) } }
307
+ }
308
+
309
+ const order = await this.getOrderDetails(orderId)
310
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
311
+ const authorization =
312
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
313
+
314
+ return {
315
+ data: {
316
+ ...(input.data || {}),
317
+ paypal: {
318
+ ...((input.data || {}).paypal as Record<string, unknown>),
319
+ order,
320
+ authorization_id: authorization?.id || paypalData.authorization_id,
321
+ capture_id: capture?.id || paypalData.capture_id,
322
+ },
323
+ },
324
+ }
325
+ }
326
+
327
+ async getPaymentStatus(
328
+ input: GetPaymentStatusInput
329
+ ): Promise<GetPaymentStatusOutput> {
330
+ const data = (input.data || {}) as Record<string, any>
331
+ const paypalData = (data.paypal || {}) as Record<string, any>
332
+ const orderId = String(paypalData.order_id || data.order_id || "")
333
+ if (!orderId) {
334
+ return { status: "pending", data: { ...(input.data || {}) } }
335
+ }
336
+
337
+ try {
338
+ const order = await this.getOrderDetails(orderId)
339
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
340
+ const authorization =
341
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
342
+ const mappedStatus =
343
+ this.mapCaptureStatus(capture?.status) ||
344
+ this.mapAuthorizationStatus(authorization?.status) ||
345
+ this.mapOrderStatus(order?.status) ||
346
+ "pending"
347
+
348
+ await this.recordSuccess("status_success")
349
+ return {
350
+ status: mappedStatus,
351
+ data: {
352
+ ...(input.data || {}),
353
+ paypal: {
354
+ ...((input.data || {}).paypal as Record<string, unknown>),
355
+ order,
356
+ authorization_id: authorization?.id || paypalData.authorization_id,
357
+ capture_id: capture?.id || paypalData.capture_id,
358
+ },
359
+ },
360
+ }
361
+ } catch (error: any) {
362
+ await this.recordFailure("status_failed", {
363
+ order_id: orderId,
364
+ message: error?.message,
365
+ })
366
+ throw error
367
+ }
368
+ }
369
+
370
+ async capturePayment(
371
+ input: CapturePaymentInput
372
+ ): Promise<CapturePaymentOutput> {
373
+ const data = (input.data || {}) as Record<string, any>
374
+ const paypalData = (data.paypal || {}) as Record<string, any>
375
+ const orderId = String(paypalData.order_id || data.order_id || "")
376
+ let authorizationId = String(
377
+ paypalData.authorization_id || data.authorization_id || ""
378
+ )
379
+ if (!orderId) {
380
+ throw new Error("PayPal order_id is required to capture payment")
381
+ }
382
+
383
+ if (paypalData.capture_id || paypalData.capture) {
384
+ return {
385
+ data: {
386
+ ...(input.data || {}),
387
+ paypal: {
388
+ ...((input.data || {}).paypal as Record<string, unknown>),
389
+ capture_id: paypalData.capture_id,
390
+ capture: paypalData.capture,
391
+ },
392
+ captured_at: new Date().toISOString(),
393
+ },
394
+ }
395
+ }
396
+
397
+ const { amount: sessionAmount, currencyCode } =
398
+ await this.normalizePaymentData(input)
399
+ // The requested (possibly partial) capture amount lives on the Medusa
400
+ // capture row, not in the provider input — resolve it so partial captures
401
+ // don't charge the full session total.
402
+ const amount = await this.resolveRequestedCaptureAmount(
403
+ input,
404
+ sessionAmount
405
+ )
406
+ // Include the amount in the idempotency suffix: PayPal deduplicates by
407
+ // PayPal-Request-Id, so two sequential partial captures of the same order
408
+ // that share an upstream idempotency_key would otherwise collide and the
409
+ // second capture would silently return the first one's result.
410
+ const requestId = this.getIdempotencyKey(
411
+ input,
412
+ `capture-${orderId}-${amount}`
413
+ )
414
+ let debugId: string | null = null
415
+
416
+ try {
417
+ const { accessToken, base } = await this.getPayPalAccessToken()
418
+ const order = await this.getOrderDetails(orderId).catch(() => null)
419
+ const existingCapture =
420
+ order?.purchase_units?.[0]?.payments?.captures?.[0]
421
+ if (existingCapture?.id && isCaptureCompleted(existingCapture)) {
422
+ return {
423
+ data: {
424
+ ...(input.data || {}),
425
+ paypal: {
426
+ ...((input.data || {}).paypal as Record<string, unknown>),
427
+ capture_id: existingCapture.id,
428
+ capture: existingCapture,
429
+ },
430
+ captured_at: new Date().toISOString(),
431
+ },
432
+ }
433
+ }
434
+
435
+ const resolvedIntent = String(
436
+ order?.intent || paypalData.order?.intent || data.intent || ""
437
+ ).toUpperCase()
438
+
439
+ if (!authorizationId && resolvedIntent === "AUTHORIZE") {
440
+ const authorizeResp = await paypalFetch(
441
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
442
+ {
443
+ method: "POST",
444
+ headers: {
445
+ Authorization: `Bearer ${accessToken}`,
446
+ "Content-Type": "application/json",
447
+ "PayPal-Request-Id": `${requestId}-auth`,
448
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
449
+ },
450
+ }
451
+ )
452
+ const authorizeText = await authorizeResp.text()
453
+ debugId = authorizeResp.headers.get("paypal-debug-id")
454
+ if (!authorizeResp.ok) {
455
+ throw new Error(
456
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
457
+ debugId ? ` debug_id=${debugId}` : ""
458
+ }`
459
+ )
460
+ }
461
+ const authorization = JSON.parse(authorizeText)
462
+ authorizationId =
463
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
464
+ }
465
+
466
+ const isFinalCapture =
467
+ paypalData.is_final_capture ??
468
+ data.is_final_capture ??
469
+ data.final_capture ??
470
+ undefined
471
+ const captureValue =
472
+ amount > 0 ? formatAmountForPayPal(amount, currencyCode || "EUR") : null
473
+
474
+ // `amount` and `is_final_capture` are only valid on the authorizations
475
+ // capture endpoint. The orders capture endpoint always captures the FULL
476
+ // order and silently ignores an `amount` body — so sending a partial
477
+ // amount there would over-capture while we record the (smaller) requested
478
+ // value. Route partial captures to the authorization, and fail closed if a
479
+ // partial capture is attempted against a capture-intent order.
480
+ let capturePayload: Record<string, unknown>
481
+ let captureUrl: string
482
+ if (authorizationId) {
483
+ captureUrl = `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/capture`
484
+ capturePayload = {
485
+ ...(captureValue
486
+ ? {
487
+ amount: {
488
+ currency_code: currencyCode || "EUR",
489
+ value: captureValue,
490
+ },
491
+ }
492
+ : {}),
493
+ ...(typeof isFinalCapture === "boolean"
494
+ ? { is_final_capture: isFinalCapture }
495
+ : {}),
496
+ }
497
+ } else {
498
+ captureUrl = `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/capture`
499
+ capturePayload = {}
500
+ const orderTotal = order?.purchase_units?.[0]?.amount?.value
501
+ if (captureValue && orderTotal && captureValue !== String(orderTotal)) {
502
+ throw new Error(
503
+ `PayPal partial capture (${captureValue} ${currencyCode || "EUR"}) is not supported for ` +
504
+ `capture-intent orders (order total ${orderTotal}). Create the order with intent ` +
505
+ `AUTHORIZE to capture a partial amount.`
506
+ )
507
+ }
508
+ }
509
+
510
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
511
+ // capture idempotent, so a retry after a network blip re-uses the same
512
+ // capture instead of double-charging.
513
+ const ppResp = await paypalFetchWithRetry(captureUrl, {
514
+ method: "POST",
515
+ headers: {
516
+ Authorization: `Bearer ${accessToken}`,
517
+ "Content-Type": "application/json",
518
+ "PayPal-Request-Id": requestId,
519
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
520
+ },
521
+ body: JSON.stringify(capturePayload),
522
+ })
523
+
524
+ const ppText = await ppResp.text()
525
+ debugId = ppResp.headers.get("paypal-debug-id")
526
+ if (!ppResp.ok) {
527
+ throw new Error(
528
+ `PayPal capture error (${ppResp.status}): ${ppText}${
529
+ debugId ? ` debug_id=${debugId}` : ""
530
+ }`
531
+ )
532
+ }
533
+
534
+ const capture = JSON.parse(ppText)
535
+
536
+ // A 2xx response does NOT mean the funds were captured. PayPal returns 201
537
+ // for captures that are PENDING (e.g. pending review / eCheck), DECLINED,
538
+ // or FAILED. Recording any of these as "captured" books money that never
539
+ // settled, so only a COMPLETED capture is treated as success.
540
+ const captureStatus = extractCaptureStatus(capture)
541
+ if (captureStatus !== "COMPLETED") {
542
+ throw new Error(
543
+ `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"}). ` +
544
+ `The payment was not captured.${debugId ? ` debug_id=${debugId}` : ""}`
545
+ )
546
+ }
547
+
548
+ const captureId =
549
+ capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id
550
+ const existingCaptures = Array.isArray(paypalData.captures)
551
+ ? paypalData.captures
552
+ : []
553
+ const captureEntry = {
554
+ id: captureId,
555
+ status: capture?.status,
556
+ amount: capture?.amount,
557
+ raw: capture,
558
+ }
559
+
560
+ await this.recordSuccess("capture_success")
561
+ await this.recordPaymentEvent("capture", {
562
+ order_id: orderId,
563
+ capture_id: captureId,
564
+ authorization_id: authorizationId || undefined,
565
+ amount,
566
+ currency_code: currencyCode,
567
+ request_id: requestId,
568
+ })
569
+
570
+ return {
571
+ data: {
572
+ ...(input.data || {}),
573
+ paypal: {
574
+ ...((input.data || {}).paypal as Record<string, unknown>),
575
+ order_id: orderId,
576
+ capture_id: captureId,
577
+ capture,
578
+ authorization_id: authorizationId || paypalData.authorization_id,
579
+ captures: [...existingCaptures, captureEntry],
580
+ },
581
+ captured_at: new Date().toISOString(),
582
+ },
583
+ }
584
+ } catch (error: any) {
585
+ await this.recordFailure("capture_failed", {
586
+ order_id: orderId,
587
+ request_id: requestId,
588
+ debug_id: debugId,
589
+ message: error?.message,
590
+ })
591
+ throw error instanceof MedusaError
592
+ ? error
593
+ : new MedusaError(
594
+ MedusaError.Types.INVALID_DATA,
595
+ error?.message || "PayPal capture failed."
596
+ )
597
+ }
598
+ }
599
+
600
+ async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
601
+ const data = (input.data || {}) as Record<string, any>
602
+ const paypalData = (data.paypal || {}) as Record<string, any>
603
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
604
+ const refundReason = String(
605
+ paypalData.refund_reason || data.refund_reason || data.reason || ""
606
+ ).trim()
607
+ const refundReasonCode = String(
608
+ paypalData.refund_reason_code ||
609
+ data.refund_reason_code ||
610
+ data.reason_code ||
611
+ ""
612
+ ).trim()
613
+ if (!captureId) {
614
+ throw new MedusaError(
615
+ MedusaError.Types.INVALID_DATA,
616
+ "PayPal capture_id is required to refund payment. No capture found in session data."
617
+ )
618
+ }
619
+
620
+ // Medusa passes the refund amount as a BigNumberInput (BigNumber instance or
621
+ // serialized { value, precision }); coerce it to a number so partial refunds
622
+ // send the correct value instead of silently refunding the full capture.
623
+ const refundAmount = toAmountNumber(input.amount)
624
+
625
+ // Include the amount in the idempotency suffix so two sequential partial
626
+ // refunds of the same capture are not deduplicated by PayPal into one.
627
+ const requestId = this.getIdempotencyKey(
628
+ input,
629
+ `refund-${captureId}-${refundAmount}`
630
+ )
631
+
632
+ const currencyOverride = await this.resolveCurrencyOverride()
633
+ const currencyCode = normalizeCurrencyCode(
634
+ data.currency_code || currencyOverride || "EUR"
635
+ )
636
+
637
+ const refundValue =
638
+ refundAmount > 0
639
+ ? formatAmountForPayPal(refundAmount, currencyCode)
640
+ : null
641
+
642
+ let debugId: string | null = null
643
+
644
+ try {
645
+ const { accessToken, base } = await this.getPayPalAccessToken()
646
+ const refundPayload: Record<string, any> = refundValue
647
+ ? {
648
+ amount: {
649
+ currency_code: currencyCode || "EUR",
650
+ value: refundValue,
651
+ },
652
+ }
653
+ : {}
654
+
655
+ if (refundReason) {
656
+ // PayPal rejects a note_to_payer longer than 255 characters with a 422
657
+ // (which would otherwise fail the whole refund); truncate defensively.
658
+ refundPayload.note_to_payer = refundReason.slice(0, 255)
659
+ }
660
+
661
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
662
+ // the refund amount) makes the refund idempotent, so a retry after a
663
+ // network blip re-uses the same refund instead of double-refunding.
664
+ const ppResp = await paypalFetchWithRetry(
665
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
666
+ {
667
+ method: "POST",
668
+ headers: {
669
+ Authorization: `Bearer ${accessToken}`,
670
+ "Content-Type": "application/json",
671
+ "PayPal-Request-Id": requestId,
672
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
673
+ },
674
+ body: JSON.stringify(refundPayload),
675
+ }
676
+ )
677
+
678
+ const ppText = await ppResp.text()
679
+ debugId = ppResp.headers.get("paypal-debug-id")
680
+ if (!ppResp.ok) {
681
+ throw new Error(
682
+ `PayPal refund error (${ppResp.status}): ${ppText}${
683
+ debugId ? ` debug_id=${debugId}` : ""
684
+ }`
685
+ )
686
+ }
687
+
688
+ const refund = JSON.parse(ppText)
689
+
690
+ // As with captures, a 2xx response does not guarantee the refund stuck.
691
+ // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
692
+ // recorded as a successful refund. PENDING is accepted: PayPal processes
693
+ // refunds asynchronously and a pending refund will settle.
694
+ const refundStatus = String(refund?.status || "").toUpperCase()
695
+ if (isRefundFailureStatus(refundStatus)) {
696
+ throw new Error(
697
+ `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
698
+ (debugId ? ` debug_id=${debugId}` : "")
699
+ )
700
+ }
701
+
702
+ const existingRefunds = Array.isArray(paypalData.refunds)
703
+ ? paypalData.refunds
704
+ : []
705
+ const refundEntry = {
706
+ id: refund?.id,
707
+ status: refund?.status,
708
+ amount: refund?.amount,
709
+ reason: refundReason || refund?.note_to_payer,
710
+ reason_code: refundReasonCode || refund?.reason_code,
711
+ raw: refund,
712
+ }
713
+
714
+ await this.recordSuccess("refund_success")
715
+ await this.recordPaymentEvent("refund", {
716
+ capture_id: captureId,
717
+ refund_id: refund?.id,
718
+ amount: refundAmount,
719
+ currency_code: currencyCode,
720
+ request_id: requestId,
721
+ reason: refundReason,
722
+ reason_code: refundReasonCode,
723
+ })
724
+
725
+ return {
726
+ data: {
727
+ ...(input.data || {}),
728
+ paypal: {
729
+ ...((input.data || {}).paypal as Record<string, unknown>),
730
+ refund_id: refund?.id,
731
+ refund_status: refund?.status,
732
+ refund_reason: refundReason || refund?.note_to_payer,
733
+ refund_reason_code: refundReasonCode || refund?.reason_code,
734
+ refunds: [...existingRefunds, refundEntry],
735
+ refund,
736
+ },
737
+ refunded_at: new Date().toISOString(),
738
+ },
739
+ }
740
+ } catch (error: any) {
741
+ await this.recordFailure("refund_failed", {
742
+ capture_id: captureId,
743
+ request_id: requestId,
744
+ debug_id: debugId,
745
+ message: error?.message,
746
+ })
747
+ throw error instanceof MedusaError
748
+ ? error
749
+ : new MedusaError(
750
+ MedusaError.Types.INVALID_DATA,
751
+ error?.message || "PayPal refund failed."
752
+ )
753
+ }
754
+ }
755
+
756
+ async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
757
+ const data = (input.data || {}) as Record<string, any>
758
+ const paypalData = (data.paypal || {}) as Record<string, any>
759
+ const orderId = String(paypalData.order_id || data.order_id || "")
760
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
761
+ const storedAuthorizationId = String(
762
+ paypalData.authorization_id || data.authorization_id || ""
763
+ )
764
+ let debugId: string | null = null
765
+
766
+ try {
767
+ const order = orderId ? await this.getOrderDetails(orderId) : null
768
+ const intent = String(order?.intent || "").toUpperCase()
769
+ const authorizationId =
770
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
771
+ storedAuthorizationId
772
+
773
+ if (intent === "AUTHORIZE" && authorizationId) {
774
+ const { accessToken, base } = await this.getPayPalAccessToken()
775
+ const requestId = this.getIdempotencyKey(
776
+ input,
777
+ `void-${authorizationId}`
778
+ )
779
+
780
+ const resp = await paypalFetch(
781
+ `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
782
+ {
783
+ method: "POST",
784
+ headers: {
785
+ Authorization: `Bearer ${accessToken}`,
786
+ "Content-Type": "application/json",
787
+ "PayPal-Request-Id": requestId,
788
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
789
+ },
790
+ }
791
+ )
792
+
793
+ if (!resp.ok) {
794
+ const text = await resp.text()
795
+ debugId = resp.headers.get("paypal-debug-id")
796
+ throw new Error(
797
+ `PayPal void error (${resp.status}): ${text}${
798
+ debugId ? ` debug_id=${debugId}` : ""
799
+ }`
800
+ )
801
+ }
802
+
803
+ await this.recordSuccess("void_success")
804
+ await this.recordPaymentEvent("void", {
805
+ order_id: orderId,
806
+ authorization_id: authorizationId,
807
+ })
808
+ } else if (captureId) {
809
+ const { accessToken, base } = await this.getPayPalAccessToken()
810
+ const requestId = this.getIdempotencyKey(
811
+ input,
812
+ `cancel-refund-${captureId}`
813
+ )
814
+
815
+ const resp = await paypalFetch(
816
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
817
+ {
818
+ method: "POST",
819
+ headers: {
820
+ Authorization: `Bearer ${accessToken}`,
821
+ "Content-Type": "application/json",
822
+ "PayPal-Request-Id": requestId,
823
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
824
+ },
825
+ body: JSON.stringify({}),
826
+ }
827
+ )
828
+
829
+ if (!resp.ok) {
830
+ const text = await resp.text()
831
+ debugId = resp.headers.get("paypal-debug-id")
832
+ throw new Error(
833
+ `PayPal refund error (${resp.status}): ${text}${
834
+ debugId ? ` debug_id=${debugId}` : ""
835
+ }`
836
+ )
837
+ }
838
+
839
+ const refund = await resp.json().catch(() => ({}))
840
+
841
+ // As with refundPayment: a 2xx response does not guarantee the refund
842
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
843
+ // `canceled_at` for a refund that never went through would record a
844
+ // cancellation while the merchant keeps the funds.
845
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
846
+ if (isRefundFailureStatus(cancelRefundStatus)) {
847
+ throw new Error(
848
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
849
+ )
850
+ }
851
+
852
+ const existingRefunds = Array.isArray(paypalData.refunds)
853
+ ? paypalData.refunds
854
+ : []
855
+ const refundEntry = {
856
+ id: refund?.id,
857
+ status: refund?.status,
858
+ amount: refund?.amount,
859
+ raw: refund,
860
+ }
861
+
862
+ await this.recordSuccess("cancel_refund_success")
863
+
864
+ return {
865
+ data: {
866
+ ...(input.data || {}),
867
+ paypal: {
868
+ ...((input.data || {}).paypal as Record<string, unknown>),
869
+ order: order || undefined,
870
+ authorization_id: authorizationId || storedAuthorizationId,
871
+ capture_id: captureId || paypalData.capture_id,
872
+ refund_id: refund?.id,
873
+ refund_status: refund?.status,
874
+ refunds: [...existingRefunds, refundEntry],
875
+ },
876
+ canceled_at: new Date().toISOString(),
877
+ },
878
+ }
879
+ }
880
+
881
+ return {
882
+ data: {
883
+ ...(input.data || {}),
884
+ paypal: {
885
+ ...((input.data || {}).paypal as Record<string, unknown>),
886
+ order: order || undefined,
887
+ authorization_id: authorizationId || storedAuthorizationId,
888
+ capture_id: captureId || paypalData.capture_id,
889
+ },
890
+ canceled_at: new Date().toISOString(),
891
+ },
892
+ }
893
+ } catch (error: any) {
894
+ await this.recordFailure("cancel_failed", {
895
+ order_id: orderId,
896
+ capture_id: captureId,
897
+ debug_id: debugId,
898
+ message: error?.message,
899
+ })
900
+ throw error
901
+ }
902
+ }
903
+ }
904
+
905
+ export default PayPalPaymentProvider
906
+ export { PayPalPaymentProvider }