@easypayment/medusa-payment-paypal 1.2.3 → 1.2.5

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 (274) hide show
  1. package/.medusa/server/src/admin/index.js +392 -138
  2. package/.medusa/server/src/admin/index.mjs +392 -138
  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 +11 -1
  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 +80 -26
  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 +55 -8
  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 +24 -1
  113. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  114. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +296 -0
  115. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  116. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +14 -7
  117. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  118. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +40 -198
  119. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  120. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -1
  121. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -1
  122. package/.medusa/server/src/modules/paypal/payment-provider/index.js +6 -4
  123. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -1
  124. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +9 -2
  125. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  126. package/.medusa/server/src/modules/paypal/payment-provider/service.js +29 -181
  127. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  128. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts +21 -0
  129. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts.map +1 -1
  130. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js +54 -0
  131. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js.map +1 -1
  132. package/.medusa/server/src/modules/paypal/service.d.ts +72 -2
  133. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  134. package/.medusa/server/src/modules/paypal/service.js +159 -33
  135. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  136. package/.medusa/server/src/modules/paypal/types/config.d.ts +2 -0
  137. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  138. package/.medusa/server/src/modules/paypal/types/config.js +5 -2
  139. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  140. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -0
  141. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
  142. package/.medusa/server/src/modules/paypal/utils/amounts.js +15 -5
  143. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
  144. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  145. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  146. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +45 -1
  147. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  148. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +9 -0
  149. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -1
  150. package/.medusa/server/src/modules/paypal/utils/currencies.js +13 -0
  151. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -1
  152. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +12 -0
  153. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  154. package/.medusa/server/src/modules/paypal/utils/payment-session.js +4 -3
  155. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  156. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +1 -0
  157. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -1
  158. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +1 -0
  159. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -1
  160. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts +11 -0
  161. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  162. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +17 -1
  163. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  164. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +6 -0
  165. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -1
  166. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +6 -0
  167. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -1
  168. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts +2 -0
  169. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
  170. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +6 -1
  171. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
  172. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +43 -0
  173. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  174. package/.medusa/server/src/modules/paypal/webhook-processor.js +57 -5
  175. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  176. package/.medusa/server/src/providers/paypal/index.d.ts +1 -0
  177. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -1
  178. package/.medusa/server/src/providers/paypal/index.js +1 -0
  179. package/.medusa/server/src/providers/paypal/index.js.map +1 -1
  180. package/.medusa/server/src/providers/paypal_card/index.d.ts +1 -0
  181. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -1
  182. package/.medusa/server/src/providers/paypal_card/index.js +1 -0
  183. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -1
  184. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  185. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -1
  186. package/.medusa/server/src/subscribers/paypal-order-invoice.js +9 -1
  187. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -1
  188. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +1 -0
  189. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  190. package/.medusa/server/src/subscribers/paypal-webhook-process.js +17 -4
  191. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  192. package/CHANGELOG.md +65 -0
  193. package/README.md +184 -184
  194. package/package.json +7 -4
  195. package/src/admin/index.ts +1 -1
  196. package/src/admin/routes/settings/paypal/_components/FieldRow.tsx +38 -29
  197. package/src/admin/routes/settings/paypal/_components/SectionCard.tsx +29 -26
  198. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +49 -48
  199. package/src/admin/routes/settings/paypal/_components/Toast.tsx +63 -52
  200. package/src/admin/routes/settings/paypal/_utils/adminFetch.ts +52 -32
  201. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +246 -139
  202. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +208 -123
  203. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +9 -5
  204. package/src/admin/routes/settings/paypal/connection/page.tsx +974 -908
  205. package/src/admin/routes/settings/paypal/google-pay/page.tsx +9 -5
  206. package/src/admin/routes/settings/paypal/page.tsx +14 -13
  207. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +9 -5
  208. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +304 -273
  209. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +48 -39
  210. package/src/api/admin/paypal/disconnect/route.ts +15 -14
  211. package/src/api/admin/paypal/environment/route.ts +34 -32
  212. package/src/api/admin/paypal/onboard-complete/route.ts +61 -50
  213. package/src/api/admin/paypal/onboarding-link/route.ts +91 -76
  214. package/src/api/admin/paypal/onboarding-status/route.ts +21 -20
  215. package/src/api/admin/paypal/save-credentials/route.ts +48 -37
  216. package/src/api/admin/paypal/settings/route.ts +63 -45
  217. package/src/api/admin/paypal/status/route.ts +29 -17
  218. package/src/api/hooks/paypal/onboard-return/route.ts +15 -15
  219. package/src/api/hooks/paypal/webhook/route.ts +17 -17
  220. package/src/api/middlewares.ts +61 -61
  221. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +69 -54
  222. package/src/api/store/paypal/capture-order/route.ts +416 -370
  223. package/src/api/store/paypal/config/route.ts +121 -115
  224. package/src/api/store/paypal/create-order/route.ts +611 -539
  225. package/src/api/store/paypal/onboard-return/route.ts +116 -113
  226. package/src/api/store/paypal/settings/route.ts +29 -19
  227. package/src/api/store/paypal/webhook/route.ts +380 -314
  228. package/src/api/store/paypal-complete/route.ts +184 -128
  229. package/src/api/utils/rate-limit.ts +143 -129
  230. package/src/index.ts +1 -1
  231. package/src/jobs/paypal-webhook-retry.ts +257 -241
  232. package/src/modules/paypal/index.ts +9 -8
  233. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -33
  234. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -22
  235. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -29
  236. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -27
  237. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -31
  238. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -25
  239. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -26
  240. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +15 -11
  241. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +15 -11
  242. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +15 -11
  243. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -17
  244. package/src/modules/paypal/migrations/20270202000000_align_nullable_defaults.ts +44 -44
  245. package/src/modules/paypal/migrations/20270301000000_add_webhook_transmission_id_index.ts +15 -15
  246. package/src/modules/paypal/models/paypal_connection.ts +28 -23
  247. package/src/modules/paypal/models/paypal_metric.ts +13 -9
  248. package/src/modules/paypal/models/paypal_settings.ts +13 -8
  249. package/src/modules/paypal/models/paypal_webhook_event.ts +26 -19
  250. package/src/modules/paypal/payment-provider/base-provider.ts +700 -275
  251. package/src/modules/paypal/payment-provider/card-service.ts +693 -855
  252. package/src/modules/paypal/payment-provider/index.ts +14 -15
  253. package/src/modules/paypal/payment-provider/service.ts +673 -836
  254. package/src/modules/paypal/payment-provider/status-utils.ts +116 -59
  255. package/src/modules/paypal/payment-provider/webhook-utils.ts +109 -109
  256. package/src/modules/paypal/service.ts +362 -115
  257. package/src/modules/paypal/types/config.ts +70 -65
  258. package/src/modules/paypal/utils/amounts.ts +123 -107
  259. package/src/modules/paypal/utils/core-workflow.ts +46 -46
  260. package/src/modules/paypal/utils/credential-resolver.ts +315 -271
  261. package/src/modules/paypal/utils/currencies.ts +97 -84
  262. package/src/modules/paypal/utils/partner.ts +8 -8
  263. package/src/modules/paypal/utils/payment-session.ts +144 -138
  264. package/src/modules/paypal/utils/paypal-auth.ts +6 -5
  265. package/src/modules/paypal/utils/paypal-fetch.ts +197 -181
  266. package/src/modules/paypal/utils/provider-ids.ts +21 -15
  267. package/src/modules/paypal/utils/secret-crypto.ts +226 -197
  268. package/src/modules/paypal/utils/webhook-verify.ts +61 -61
  269. package/src/modules/paypal/webhook-processor.ts +641 -573
  270. package/src/providers/paypal/index.ts +9 -8
  271. package/src/providers/paypal_card/index.ts +9 -8
  272. package/src/subscribers/paypal-order-invoice.ts +180 -173
  273. package/src/subscribers/paypal-webhook-process.ts +147 -131
  274. package/tsconfig.json +21 -31
@@ -1,855 +1,693 @@
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
+ CancelPaymentInput,
6
+ CancelPaymentOutput,
7
+ GetPaymentStatusInput,
8
+ GetPaymentStatusOutput,
9
+ InitiatePaymentInput,
10
+ InitiatePaymentOutput,
11
+ RefundPaymentInput,
12
+ RefundPaymentOutput,
13
+ RetrievePaymentInput,
14
+ RetrievePaymentOutput,
15
+ UpdatePaymentInput,
16
+ UpdatePaymentOutput,
17
+ } from "@medusajs/framework/types"
18
+ import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
19
+ import {
20
+ assertPayPalCurrencySupported,
21
+ normalizeCurrencyCode,
22
+ } from "../utils/currencies"
23
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
24
+ import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
25
+ import { extractCaptureStatus, isRefundFailureStatus } from "./status-utils"
26
+ import { PayPalProviderBase } from "./base-provider"
27
+
28
+ /**
29
+ * PayPal Advanced (hosted) Card Fields payment provider —
30
+ * `pp_paypal_card_paypal_card`.
31
+ *
32
+ * Shares the order-based flow of the wallet provider but adds admin-configured
33
+ * card-brand restrictions and 3-D Secure handling. Card orders are created
34
+ * with a `payment_source.card` verification method (see create-order).
35
+ */
36
+ class PayPalAdvancedCardProvider extends PayPalProviderBase {
37
+ static identifier = "paypal_card"
38
+
39
+ protected readonly sessionPrefix = "pp_card"
40
+ protected readonly idempotencyPrefix = "pp-card"
41
+
42
+ async initiatePayment(
43
+ input: InitiatePaymentInput
44
+ ): Promise<InitiatePaymentOutput> {
45
+ const currencyOverride = await this.resolveCurrencyOverride()
46
+ const currencyCode = normalizeCurrencyCode(
47
+ input.currency_code || currencyOverride || "EUR"
48
+ )
49
+ assertPayPalCurrencySupported({
50
+ currencyCode,
51
+ paypalCurrencyOverride: currencyOverride,
52
+ })
53
+
54
+ return {
55
+ id: this.generateSessionId(),
56
+ data: {
57
+ ...(input.data || {}),
58
+ amount: input.amount,
59
+ currency_code: currencyCode,
60
+ },
61
+ }
62
+ }
63
+
64
+ async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
65
+ const currencyOverride = await this.resolveCurrencyOverride()
66
+ const currencyCode = normalizeCurrencyCode(
67
+ input.currency_code || currencyOverride || "EUR"
68
+ )
69
+ assertPayPalCurrencySupported({
70
+ currencyCode,
71
+ paypalCurrencyOverride: currencyOverride,
72
+ })
73
+ // Preserve the provider_id passthrough exactly like the wallet provider —
74
+ // dropping it here would make the two providers' session data diverge.
75
+ const providerId = (input.data as Record<string, any> | undefined)
76
+ ?.provider_id
77
+
78
+ return {
79
+ data: {
80
+ ...(input.data || {}),
81
+ ...this.invalidateStaleOrder(input, currencyCode),
82
+ ...(providerId ? { provider_id: providerId } : {}),
83
+ amount: input.amount,
84
+ currency_code: currencyCode,
85
+ },
86
+ }
87
+ }
88
+
89
+ async authorizePayment(
90
+ input: AuthorizePaymentInput
91
+ ): Promise<AuthorizePaymentOutput> {
92
+ const { data } = await this.normalizePaymentData(input)
93
+ const requestId = this.getIdempotencyKey(input, "authorize")
94
+ const { advancedCardSettings } = await this.resolveSettings()
95
+ const disabledCards = Array.isArray(advancedCardSettings.disabledCards)
96
+ ? advancedCardSettings.disabledCards.map((card: string) =>
97
+ String(card).toLowerCase()
98
+ )
99
+ : []
100
+ const cardBrand = String(
101
+ data.card_brand || data.cardBrand || data?.paypal?.card_brand || ""
102
+ ).toLowerCase()
103
+ if (cardBrand && disabledCards.includes(cardBrand)) {
104
+ throw new Error(`Card brand ${cardBrand} is disabled by admin settings.`)
105
+ }
106
+
107
+ const existingPayPal = (data.paypal || {}) as Record<string, any>
108
+
109
+ // Session already carries a settled capture: trust it without a network
110
+ // round-trip, but only when the stored capture is actually COMPLETED — a
111
+ // PENDING/DECLINED capture must never be booked as captured money.
112
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
113
+ if (storedCaptureStatus === "COMPLETED") {
114
+ return {
115
+ status: "captured",
116
+ data: {
117
+ ...(input.data || {}),
118
+ captured_at: (data as any).captured_at || new Date().toISOString(),
119
+ },
120
+ }
121
+ }
122
+
123
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
124
+ if (!orderId) {
125
+ // Nothing to authorize: a PayPal order only exists after the buyer
126
+ // submitted their card via the storefront (create-order + card fields).
127
+ // The previous fallback created a fresh order here and immediately
128
+ // called /authorize on it, which PayPal always rejects (no payment
129
+ // source, and 422 UNSUPPORTED_INTENT for CAPTURE-intent orders).
130
+ await this.recordFailure("authorize_failed", {
131
+ cart_id: data.cart_id,
132
+ payment_collection_id: data.payment_collection_id,
133
+ message: "no PayPal order on card session",
134
+ })
135
+ throw new MedusaError(
136
+ MedusaError.Types.NOT_ALLOWED,
137
+ "No PayPal order was found for this payment session. The buyer must submit and approve their card payment before the cart can be completed."
138
+ )
139
+ }
140
+
141
+ let order: Record<string, any> | null = null
142
+ try {
143
+ order = (await this.getOrderDetails(orderId)) as Record<
144
+ string,
145
+ any
146
+ > | null
147
+ } catch (e: any) {
148
+ console.warn(
149
+ "[PayPal] card authorizePayment: order lookup failed:",
150
+ e?.message
151
+ )
152
+ // Fall back to the session's own record on a transient lookup failure so
153
+ // checkout isn't blocked when a real authorization/capture exists.
154
+ if ((data as any).captured_at) {
155
+ return {
156
+ status: "captured",
157
+ data: {
158
+ ...(input.data || {}),
159
+ captured_at: (data as any).captured_at,
160
+ },
161
+ }
162
+ }
163
+ if (
164
+ existingPayPal.capture_id ||
165
+ existingPayPal.authorization_id ||
166
+ (data as any).authorized_at
167
+ ) {
168
+ return {
169
+ status: "authorized",
170
+ data: {
171
+ ...(input.data || {}),
172
+ authorized_at:
173
+ (data as any).authorized_at || new Date().toISOString(),
174
+ },
175
+ }
176
+ }
177
+ throw e
178
+ }
179
+
180
+ if (!order) {
181
+ throw new Error(
182
+ "Unable to resolve PayPal order details for authorization."
183
+ )
184
+ }
185
+
186
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
187
+ const authorization =
188
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
189
+
190
+ // Derive the status from what actually happened at PayPal, never from the
191
+ // mere presence of a capture/authorization or from the configured
192
+ // paymentAction: a PENDING (eCheck) capture is not settled money and a
193
+ // DENIED/DECLINED one must fail the authorization.
194
+ if (capture?.id) {
195
+ const captureStatus = this.mapCaptureStatus(capture?.status)
196
+ if (captureStatus === "captured") {
197
+ return {
198
+ status: "captured",
199
+ data: {
200
+ ...(data || {}),
201
+ paypal: {
202
+ ...existingPayPal,
203
+ order_id: orderId,
204
+ order,
205
+ capture_id: capture.id,
206
+ capture,
207
+ },
208
+ captured_at: new Date().toISOString(),
209
+ },
210
+ }
211
+ }
212
+ if (captureStatus === "pending") {
213
+ return {
214
+ status: "authorized",
215
+ data: {
216
+ ...(data || {}),
217
+ paypal: {
218
+ ...existingPayPal,
219
+ order_id: orderId,
220
+ order,
221
+ capture_id: capture.id,
222
+ },
223
+ authorized_at: new Date().toISOString(),
224
+ },
225
+ }
226
+ }
227
+ if (captureStatus === "error" || captureStatus === "canceled") {
228
+ return {
229
+ status: "error",
230
+ data: {
231
+ ...(data || {}),
232
+ paypal: { ...existingPayPal, order_id: orderId, order },
233
+ },
234
+ }
235
+ }
236
+ }
237
+
238
+ if (authorization?.id) {
239
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
240
+ if (authStatus === "authorized") {
241
+ return {
242
+ status: "authorized",
243
+ data: {
244
+ ...(data || {}),
245
+ paypal: {
246
+ ...existingPayPal,
247
+ order_id: orderId,
248
+ order,
249
+ authorization_id: authorization.id,
250
+ authorizations:
251
+ order?.purchase_units?.[0]?.payments?.authorizations || [],
252
+ },
253
+ authorized_at: new Date().toISOString(),
254
+ },
255
+ }
256
+ }
257
+ if (authStatus === "error" || authStatus === "canceled") {
258
+ return {
259
+ status: "error",
260
+ data: {
261
+ ...(data || {}),
262
+ paypal: { ...existingPayPal, order_id: orderId, order },
263
+ },
264
+ }
265
+ }
266
+ }
267
+
268
+ const orderStatus = String(order?.status || "").toUpperCase()
269
+ const orderIntent = String(order?.intent || "").toUpperCase()
270
+
271
+ if (orderStatus === "APPROVED") {
272
+ if (orderIntent === "AUTHORIZE") {
273
+ // Approved AUTHORIZE-intent order with no authorization yet: create it.
274
+ const { accessToken, base } = await this.getPayPalAccessToken()
275
+ const authorizeResp = await paypalFetch(
276
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
277
+ {
278
+ method: "POST",
279
+ headers: {
280
+ Authorization: `Bearer ${accessToken}`,
281
+ "Content-Type": "application/json",
282
+ "PayPal-Request-Id": `${requestId}-auth`,
283
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
284
+ },
285
+ }
286
+ )
287
+ const authorizeText = await authorizeResp.text()
288
+ const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
289
+ if (!authorizeResp.ok) {
290
+ throw new Error(
291
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
292
+ authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
293
+ }`
294
+ )
295
+ }
296
+ const authorized = JSON.parse(authorizeText) as Record<string, any>
297
+ const authorizationId =
298
+ authorized?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
299
+ return {
300
+ status: "authorized",
301
+ data: {
302
+ ...(data || {}),
303
+ paypal: {
304
+ ...existingPayPal,
305
+ order_id: orderId,
306
+ order: authorized || order,
307
+ authorization_id: authorizationId,
308
+ authorizations:
309
+ authorized?.purchase_units?.[0]?.payments?.authorizations || [],
310
+ },
311
+ authorized_at: new Date().toISOString(),
312
+ },
313
+ }
314
+ }
315
+
316
+ // Approved CAPTURE-intent order: the buyer approved but the capture has
317
+ // not happened yet (e.g. the storefront capture call failed). Report
318
+ // "authorized" so the order can complete; capturePayment then routes the
319
+ // actual capture by intent. Calling /authorize here — as the previous
320
+ // code did for every intent — always fails with 422 UNSUPPORTED_INTENT
321
+ // and permanently stuck the checkout.
322
+ return {
323
+ status: "authorized",
324
+ data: {
325
+ ...(data || {}),
326
+ paypal: {
327
+ ...existingPayPal,
328
+ order_id: orderId,
329
+ order,
330
+ },
331
+ authorized_at: new Date().toISOString(),
332
+ },
333
+ }
334
+ }
335
+
336
+ // CREATED / SAVED / PAYER_ACTION_REQUIRED etc.: the buyer never approved
337
+ // the payment — nothing is authorized at PayPal.
338
+ await this.recordFailure("authorize_failed", {
339
+ order_id: orderId,
340
+ order_status: orderStatus,
341
+ message: "PayPal order not approved by buyer",
342
+ })
343
+ throw new MedusaError(
344
+ MedusaError.Types.NOT_ALLOWED,
345
+ `PayPal order ${orderId} has not been approved by the buyer (status ${orderStatus || "UNKNOWN"}). The payment cannot be authorized.`
346
+ )
347
+ }
348
+
349
+ async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
350
+ const data = (input.data || {}) as Record<string, any>
351
+ const paypalData = (data.paypal || {}) as Record<string, any>
352
+ const orderId = String(paypalData.order_id || data.order_id || "")
353
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
354
+ const storedAuthorizationId = String(
355
+ paypalData.authorization_id || data.authorization_id || ""
356
+ )
357
+
358
+ try {
359
+ const order = orderId ? await this.getOrderDetails(orderId) : null
360
+ const intent = String(order?.intent || "").toUpperCase()
361
+ const authorizationId =
362
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
363
+ storedAuthorizationId
364
+
365
+ if (intent === "AUTHORIZE" && authorizationId) {
366
+ const { accessToken, base } = await this.getPayPalAccessToken()
367
+ const requestId = this.getIdempotencyKey(
368
+ input,
369
+ `void-${authorizationId}`
370
+ )
371
+
372
+ const resp = await paypalFetch(
373
+ `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
374
+ {
375
+ method: "POST",
376
+ headers: {
377
+ Authorization: `Bearer ${accessToken}`,
378
+ "Content-Type": "application/json",
379
+ "PayPal-Request-Id": requestId,
380
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
381
+ },
382
+ }
383
+ )
384
+
385
+ if (!resp.ok) {
386
+ const text = await resp.text()
387
+ const debugId = resp.headers.get("paypal-debug-id")
388
+ throw new Error(
389
+ `PayPal void error (${resp.status}): ${text}${
390
+ debugId ? ` debug_id=${debugId}` : ""
391
+ }`
392
+ )
393
+ }
394
+
395
+ await this.recordSuccess("void_success")
396
+ await this.recordPaymentEvent("void", {
397
+ order_id: orderId,
398
+ authorization_id: authorizationId,
399
+ })
400
+ } else if (captureId) {
401
+ const { accessToken, base } = await this.getPayPalAccessToken()
402
+ const requestId = this.getIdempotencyKey(
403
+ input,
404
+ `cancel-refund-${captureId}`
405
+ )
406
+
407
+ const resp = await paypalFetch(
408
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
409
+ {
410
+ method: "POST",
411
+ headers: {
412
+ Authorization: `Bearer ${accessToken}`,
413
+ "Content-Type": "application/json",
414
+ "PayPal-Request-Id": requestId,
415
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
416
+ },
417
+ body: JSON.stringify({}),
418
+ }
419
+ )
420
+
421
+ if (!resp.ok) {
422
+ const text = await resp.text()
423
+ const debugId = resp.headers.get("paypal-debug-id")
424
+ throw new Error(
425
+ `PayPal refund error (${resp.status}): ${text}${
426
+ debugId ? ` debug_id=${debugId}` : ""
427
+ }`
428
+ )
429
+ }
430
+
431
+ const refund = await resp.json().catch(() => ({}))
432
+
433
+ // As with refundPayment: a 2xx response does not guarantee the refund
434
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
435
+ // `canceled_at` for a refund that never went through would record a
436
+ // cancellation while the merchant keeps the funds.
437
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
438
+ if (isRefundFailureStatus(cancelRefundStatus)) {
439
+ throw new Error(
440
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
441
+ )
442
+ }
443
+
444
+ const existingRefunds = Array.isArray(paypalData.refunds)
445
+ ? paypalData.refunds
446
+ : []
447
+ const refundEntry = {
448
+ id: refund?.id,
449
+ status: refund?.status,
450
+ amount: refund?.amount,
451
+ raw: refund,
452
+ }
453
+
454
+ await this.recordSuccess("cancel_refund_success")
455
+
456
+ return {
457
+ data: {
458
+ ...(data || {}),
459
+ paypal: {
460
+ ...paypalData,
461
+ order: order || undefined,
462
+ authorization_id: authorizationId || storedAuthorizationId,
463
+ capture_id: captureId || paypalData.capture_id,
464
+ refund_id: refund?.id,
465
+ refund_status: refund?.status,
466
+ refunds: [...existingRefunds, refundEntry],
467
+ },
468
+ canceled_at: new Date().toISOString(),
469
+ },
470
+ }
471
+ }
472
+
473
+ return {
474
+ data: {
475
+ ...(data || {}),
476
+ paypal: {
477
+ ...paypalData,
478
+ order: order || undefined,
479
+ authorization_id: authorizationId || storedAuthorizationId,
480
+ capture_id: captureId || paypalData.capture_id,
481
+ },
482
+ canceled_at: new Date().toISOString(),
483
+ },
484
+ }
485
+ } catch (error: any) {
486
+ await this.recordFailure("cancel_failed", {
487
+ order_id: orderId,
488
+ capture_id: captureId,
489
+ message: error?.message,
490
+ })
491
+ throw error
492
+ }
493
+ }
494
+
495
+ async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
496
+ const data = (input.data || {}) as Record<string, any>
497
+ const paypalData = (data.paypal || {}) as Record<string, any>
498
+ const captureId = String(paypalData.capture_id || data.capture_id || "")
499
+ if (!captureId) {
500
+ throw new MedusaError(
501
+ MedusaError.Types.INVALID_DATA,
502
+ "PayPal capture_id is required to refund payment. No capture found in session data."
503
+ )
504
+ }
505
+
506
+ // Use the refund amount Medusa passes (top-level input), not the session
507
+ // amount in `data` — otherwise a partial refund would refund the full order.
508
+ // Medusa passes it as a BigNumberInput, so coerce it to a number; a naive
509
+ // Number() of the object form yields NaN and silently refunds the full
510
+ // capture.
511
+ const amount = toAmountNumber(input.amount)
512
+ const requestId = this.getIdempotencyKey(
513
+ input,
514
+ `refund-${captureId}-${amount}`
515
+ )
516
+ const currencyOverride = await this.resolveCurrencyOverride()
517
+ const currencyCode = normalizeCurrencyCode(
518
+ data.currency_code || currencyOverride || "EUR"
519
+ )
520
+
521
+ try {
522
+ const { accessToken, base } = await this.getPayPalAccessToken()
523
+ const refundPayload: Record<string, any> =
524
+ amount > 0
525
+ ? {
526
+ amount: {
527
+ currency_code: currencyCode,
528
+ value: formatAmountForPayPal(amount, currencyCode),
529
+ },
530
+ }
531
+ : {}
532
+
533
+ // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
534
+ // the refund amount) makes the refund idempotent, so a retry after a
535
+ // network blip re-uses the same refund instead of double-refunding.
536
+ const resp = await paypalFetchWithRetry(
537
+ `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
538
+ {
539
+ method: "POST",
540
+ headers: {
541
+ Authorization: `Bearer ${accessToken}`,
542
+ "Content-Type": "application/json",
543
+ // Full refund resource (amount, status, …) instead of the
544
+ // id/status/links stub, so the stored refund entry is usable.
545
+ Prefer: "return=representation",
546
+ "PayPal-Request-Id": requestId,
547
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
548
+ },
549
+ body: JSON.stringify(refundPayload),
550
+ }
551
+ )
552
+
553
+ const text = await resp.text()
554
+ if (!resp.ok) {
555
+ const debugId = resp.headers.get("paypal-debug-id")
556
+ throw new MedusaError(
557
+ MedusaError.Types.UNEXPECTED_STATE,
558
+ `PayPal refund error (${resp.status}): ${text}${
559
+ debugId ? ` debug_id=${debugId}` : ""
560
+ }`
561
+ )
562
+ }
563
+
564
+ const refund = JSON.parse(text)
565
+
566
+ // As with captures, a 2xx response does not guarantee the refund stuck.
567
+ // FAILED / CANCELLED / DENIED refunds also return 2xx and must not be
568
+ // recorded as a successful refund. PENDING is accepted: PayPal processes
569
+ // refunds asynchronously and a pending refund will settle.
570
+ const refundStatus = String(refund?.status || "").toUpperCase()
571
+ if (isRefundFailureStatus(refundStatus)) {
572
+ const refundDebugId = resp.headers.get("paypal-debug-id")
573
+ throw new MedusaError(
574
+ MedusaError.Types.UNEXPECTED_STATE,
575
+ `PayPal refund did not succeed (status=${refundStatus}). The refund was not issued.` +
576
+ (refundDebugId ? ` debug_id=${refundDebugId}` : "")
577
+ )
578
+ }
579
+
580
+ const existingRefunds = Array.isArray(paypalData.refunds)
581
+ ? paypalData.refunds
582
+ : []
583
+ const refundEntry = {
584
+ id: refund?.id,
585
+ status: refund?.status,
586
+ amount: refund?.amount,
587
+ raw: refund,
588
+ }
589
+
590
+ await this.recordSuccess("refund_success")
591
+ await this.recordPaymentEvent("refund", {
592
+ capture_id: captureId,
593
+ refund_id: refund?.id,
594
+ amount,
595
+ currency_code: currencyCode,
596
+ request_id: requestId,
597
+ })
598
+
599
+ return {
600
+ data: {
601
+ ...(data || {}),
602
+ paypal: {
603
+ ...paypalData,
604
+ refund_id: refund?.id,
605
+ refund_status: refund?.status,
606
+ refunds: [...existingRefunds, refundEntry],
607
+ refund,
608
+ },
609
+ refunded_at: new Date().toISOString(),
610
+ },
611
+ }
612
+ } catch (error: any) {
613
+ await this.recordFailure("refund_failed", {
614
+ capture_id: captureId,
615
+ request_id: requestId,
616
+ message: error?.message,
617
+ })
618
+ // Surface the real reason: Medusa masks any non-MedusaError as a generic
619
+ // "An unknown error occurred." in production, hiding the PayPal failure.
620
+ throw error instanceof MedusaError
621
+ ? error
622
+ : new MedusaError(
623
+ MedusaError.Types.UNEXPECTED_STATE,
624
+ error?.message || "PayPal refund failed."
625
+ )
626
+ }
627
+ }
628
+
629
+ async retrievePayment(
630
+ input: RetrievePaymentInput
631
+ ): Promise<RetrievePaymentOutput> {
632
+ const data = (input.data || {}) as Record<string, any>
633
+ const paypalData = (data.paypal || {}) as Record<string, any>
634
+ const orderId = String(paypalData.order_id || data.order_id || "")
635
+ if (!orderId) {
636
+ return { data: { ...(data || {}) } }
637
+ }
638
+
639
+ const order = await this.getOrderDetails(orderId)
640
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
641
+ const authorization =
642
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
643
+
644
+ return {
645
+ data: {
646
+ ...(data || {}),
647
+ paypal: {
648
+ ...paypalData,
649
+ order,
650
+ authorization_id: authorization?.id || paypalData.authorization_id,
651
+ capture_id: capture?.id || paypalData.capture_id,
652
+ },
653
+ },
654
+ }
655
+ }
656
+
657
+ async getPaymentStatus(
658
+ input: GetPaymentStatusInput
659
+ ): Promise<GetPaymentStatusOutput> {
660
+ const data = (input.data || {}) as Record<string, any>
661
+ const paypalData = (data.paypal || {}) as Record<string, any>
662
+ const orderId = String(paypalData.order_id || data.order_id || "")
663
+ if (!orderId) {
664
+ return { status: "pending", data: { ...(data || {}) } }
665
+ }
666
+
667
+ const order = await this.getOrderDetails(orderId)
668
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
669
+ const authorization =
670
+ order?.purchase_units?.[0]?.payments?.authorizations?.[0]
671
+ const mappedStatus =
672
+ this.mapCaptureStatus(capture?.status) ||
673
+ this.mapAuthorizationStatus(authorization?.status) ||
674
+ this.mapOrderStatus(order?.status) ||
675
+ "pending"
676
+
677
+ return {
678
+ status: mappedStatus,
679
+ data: {
680
+ ...(data || {}),
681
+ paypal: {
682
+ ...paypalData,
683
+ order,
684
+ authorization_id: authorization?.id || paypalData.authorization_id,
685
+ capture_id: capture?.id || paypalData.capture_id,
686
+ },
687
+ },
688
+ }
689
+ }
690
+ }
691
+
692
+ export default PayPalAdvancedCardProvider
693
+ export { PayPalAdvancedCardProvider }