@easypayment/medusa-payment-paypal 1.2.3 → 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 +387 -133
  2. package/.medusa/server/src/admin/index.mjs +387 -133
  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 +11 -0
  186. package/README.md +184 -184
  187. package/package.json +7 -4
  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,370 +1,416 @@
1
- import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
- import type { Logger } from "@medusajs/framework/types"
3
- import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
4
- import { randomUUID } from "crypto"
5
- import type PayPalModuleService from "../../../../modules/paypal/service"
6
- import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
7
- import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
8
- import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
9
- import { extractCaptureStatus } from "../../../../modules/paypal/payment-provider/status-utils"
10
- import {
11
- findPayPalSessionForCart,
12
- getStoredPayPalOrderId,
13
- updatePayPalSessionData,
14
- } from "../../../../modules/paypal/utils/payment-session"
15
-
16
- const PAYPAL_ORDER_ID_RE = /^[A-Z0-9]{10,25}$/
17
-
18
- type Body = {
19
- cart_id: string
20
- order_id: string
21
- }
22
-
23
- function resolveIdempotencyKey(req: MedusaRequest, suffix: string, fallback: string) {
24
- const header =
25
- req.headers["idempotency-key"] ||
26
- req.headers["Idempotency-Key"] ||
27
- req.headers["x-idempotency-key"] ||
28
- req.headers["X-Idempotency-Key"]
29
- const key = Array.isArray(header) ? header[0] : header
30
- if (key && String(key).trim()) {
31
- return `${String(key).trim()}-${suffix}`
32
- }
33
- return fallback || `pp-${suffix}-${randomUUID()}`
34
- }
35
-
36
- /**
37
- * Persist the capture onto the cart's PayPal session. Returns `true` when the
38
- * data was written (or there was nothing to write because no session exists),
39
- * and `false` when the write ultimately failed after retries. The caller must
40
- * NOT silently treat a `false` here as success: the funds were captured at
41
- * PayPal, so a persistence failure has to be recorded/alerted (the webhook and
42
- * paypal-complete's live re-derivation are the reconciliation backstop).
43
- */
44
- async function attachPayPalCaptureToSession(
45
- cartId: string,
46
- orderId: string,
47
- capture: any,
48
- scope: any
49
- ): Promise<boolean> {
50
- const session = await findPayPalSessionForCart(cartId, scope)
51
- if (!session) {
52
- console.warn("[PayPal] attachPayPalCaptureToSession: no session found for cart", cartId)
53
- return true
54
- }
55
-
56
- const captureId = capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id || capture?.id
57
-
58
- try {
59
- await updatePayPalSessionData(
60
- session.session_id,
61
- {
62
- paypal: {
63
- ...((session.session_data || {}).paypal || {}),
64
- order_id: orderId,
65
- capture_id: captureId,
66
- capture,
67
- },
68
- },
69
- scope
70
- )
71
- return true
72
- } catch (e: unknown) {
73
- console.error(
74
- "[PayPal] attachPayPalCaptureToSession failed:",
75
- e instanceof Error ? e.message : e
76
- )
77
- return false
78
- }
79
- }
80
-
81
- async function attachPayPalAuthorizationToSession(
82
- cartId: string,
83
- orderId: string,
84
- authorization: any,
85
- scope: any
86
- ): Promise<boolean> {
87
- const session = await findPayPalSessionForCart(cartId, scope)
88
- if (!session) {
89
- console.warn("[PayPal] attachPayPalAuthorizationToSession: no session found for cart", cartId)
90
- return true
91
- }
92
-
93
- const authorizationId = authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
94
-
95
- try {
96
- await updatePayPalSessionData(
97
- session.session_id,
98
- {
99
- paypal: {
100
- ...((session.session_data || {}).paypal || {}),
101
- order_id: orderId,
102
- authorization_id: authorizationId,
103
- authorization,
104
- },
105
- },
106
- scope
107
- )
108
- return true
109
- } catch (e: unknown) {
110
- console.error(
111
- "[PayPal] attachPayPalAuthorizationToSession failed:",
112
- e instanceof Error ? e.message : e
113
- )
114
- return false
115
- }
116
- }
117
-
118
- /**
119
- * Return the session's existing capture ONLY when it demonstrably COMPLETED.
120
- *
121
- * The session can carry a capture that never settled: the webhook processor
122
- * patches `capture_id` onto the session for every capture event, including
123
- * PAYMENT.CAPTURE.DENIED and PENDING. Blindly short-circuiting on any stored
124
- * capture would report success to the storefront for a payment that was
125
- * declined — the buyer would then hit "payment processed but order could not
126
- * be finalized" instead of being able to retry.
127
- *
128
- * - stored capture object with a known status: COMPLETED → return it,
129
- * anything else → null (fall through and attempt a real capture).
130
- * - bare `capture_id` (or a capture object whose status can't be read):
131
- * verify against the live PayPal order. If PayPal can't be reached, return
132
- * the stored data — the previous fail-safe behavior — since attempting a
133
- * fresh capture against an unreachable PayPal would fail anyway.
134
- */
135
- async function getExistingCompletedCapture(
136
- cartId: string,
137
- orderId: string,
138
- scope: any,
139
- fetchLiveOrder: () => Promise<any>
140
- ) {
141
- try {
142
- const session = await findPayPalSessionForCart(cartId, scope)
143
- if (!session) return null
144
-
145
- const paypalData = (session.session_data || {}).paypal || {}
146
- const existingOrderId = String(paypalData.order_id || "")
147
- if (existingOrderId && existingOrderId !== orderId) return null
148
-
149
- const stored = paypalData.capture
150
- if (stored) {
151
- const storedStatus = extractCaptureStatus(stored)
152
- if (storedStatus === "COMPLETED") return stored
153
- if (storedStatus) return null
154
- // no readable status on the stored object — verify live below
155
- }
156
- if (!stored && !paypalData.capture_id) return null
157
-
158
- let order: any
159
- try {
160
- order = await fetchLiveOrder()
161
- } catch {
162
- return stored || { id: paypalData.capture_id }
163
- }
164
- const liveCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
165
- if (liveCapture && extractCaptureStatus(liveCapture) === "COMPLETED") {
166
- return liveCapture
167
- }
168
- return null
169
- } catch {
170
- return null
171
- }
172
- }
173
-
174
- export async function POST(req: MedusaRequest, res: MedusaResponse) {
175
- const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
176
- const logger = req.scope.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
177
- const requestId = randomUUID()
178
- const { scope } = req
179
- let debugId: string | null = null
180
-
181
- try {
182
- const body = (req.body || {}) as Body
183
- const cartId = body.cart_id
184
- const orderId = body.order_id
185
-
186
- if (!cartId || !orderId) {
187
- return res.status(400).json({ message: "cart_id and order_id are required" })
188
- }
189
-
190
- if (typeof cartId !== "string" || !cartId.startsWith("cart_")) {
191
- return res.status(400).json({ message: "Invalid cart_id format" })
192
- }
193
-
194
- if (!PAYPAL_ORDER_ID_RE.test(orderId)) {
195
- return res.status(400).json({ message: "Invalid order_id format" })
196
- }
197
-
198
- // Bind the capture to the cart's own PayPal session, fail-closed: the
199
- // order_id MUST be the one this cart's session created (stored by
200
- // create-order). This prevents capturing an arbitrary, caller-supplied
201
- // order_id against the merchant account.
202
- const session = await findPayPalSessionForCart(cartId, scope)
203
- const sessionOrderId = getStoredPayPalOrderId(session?.session_data)
204
- if (!session || !sessionOrderId) {
205
- return res.status(409).json({
206
- message: "No PayPal order is associated with this cart's payment session",
207
- })
208
- }
209
- if (sessionOrderId !== orderId) {
210
- return res.status(400).json({
211
- message: "order_id does not match the payment session for this cart",
212
- })
213
- }
214
-
215
- const creds = await paypal.getActiveCredentials()
216
- // Cached app access token (single-flight refresh) — avoids an OAuth
217
- // round-trip on every capture-order call.
218
- const base = getPayPalApiBase(creds.environment)
219
- const accessToken = await paypal.getAppAccessToken()
220
-
221
- const fetchLiveOrder = async () => {
222
- const resp = await paypalFetch(
223
- `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
224
- {
225
- method: "GET",
226
- headers: {
227
- Authorization: `Bearer ${accessToken}`,
228
- "Content-Type": "application/json",
229
- },
230
- }
231
- )
232
- if (!resp.ok) {
233
- throw new Error(`PayPal get order error (${resp.status})`)
234
- }
235
- return resp.json()
236
- }
237
-
238
- const existingCapture = await getExistingCompletedCapture(
239
- cartId,
240
- orderId,
241
- scope,
242
- fetchLiveOrder
243
- )
244
- if (existingCapture) {
245
- return res.json({ capture: existingCapture })
246
- }
247
-
248
- const settings = await paypal.getSettings().catch(() => ({}))
249
- const data =
250
- settings && typeof settings === "object" && "data" in settings
251
- ? ((settings as { data?: Record<string, any> }).data ?? {})
252
- : {}
253
- const additionalSettings = (data.additional_settings || {}) as Record<string, any>
254
- const paymentAction =
255
- typeof additionalSettings.paymentAction === "string"
256
- ? additionalSettings.paymentAction
257
- : "capture"
258
-
259
- // The suffix must include the order id: PayPal deduplicates by
260
- // PayPal-Request-Id, so a client reusing one Idempotency-Key header across
261
- // two different orders would otherwise get order A's cached capture back
262
- // for order B. Named `paypalRequestId` so it never shadows `requestId`
263
- // (the log/response correlation UUID declared at the top of POST).
264
- const paypalRequestId = resolveIdempotencyKey(
265
- req,
266
- `capture-order-${orderId}`,
267
- `pp-capture-${orderId}`
268
- )
269
- const safeOrderId = encodeURIComponent(orderId)
270
- const endpoint =
271
- paymentAction === "authorize"
272
- ? `${base}/v2/checkout/orders/${safeOrderId}/authorize`
273
- : `${base}/v2/checkout/orders/${safeOrderId}/capture`
274
-
275
- const ppResp = await paypalFetch(endpoint, {
276
- method: "POST",
277
- headers: {
278
- Authorization: `Bearer ${accessToken}`,
279
- "Content-Type": "application/json",
280
- "PayPal-Request-Id": paypalRequestId,
281
- "PayPal-Partner-Attribution-Id": BN_CODE,
282
- },
283
- })
284
-
285
- const ppText = await ppResp.text()
286
- debugId = ppResp.headers.get("paypal-debug-id")
287
- if (!ppResp.ok) {
288
- throw new Error(
289
- `PayPal capture error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`
290
- )
291
- }
292
-
293
- const payload = JSON.parse(ppText)
294
- let persisted = true
295
- if (paymentAction === "authorize") {
296
- persisted = await attachPayPalAuthorizationToSession(cartId, orderId, payload, req.scope)
297
- } else {
298
- // A 2xx capture response does NOT guarantee the funds settled: PayPal
299
- // returns 201 for PENDING (pending review / eCheck), DECLINED and FAILED
300
- // captures too. Returning those to the storefront as a successful capture
301
- // would let it finalize the cart for a payment that never completed, so
302
- // only a COMPLETED capture is reported as success — the webhook will
303
- // reconcile a later PENDING→COMPLETED transition.
304
- const captureStatus = extractCaptureStatus(payload)
305
- if (captureStatus !== "COMPLETED") {
306
- throw new Error(
307
- `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"})${
308
- debugId ? ` debug_id=${debugId}` : ""
309
- }`
310
- )
311
- }
312
- persisted = await attachPayPalCaptureToSession(cartId, orderId, payload, req.scope)
313
- }
314
-
315
- // The PayPal operation itself succeeded. If we could not persist it onto the
316
- // Medusa session, the money is (authorized/)captured but Medusa doesn't yet
317
- // record it — record a metric and log CRITICAL so it's observable/alertable.
318
- // We still return success to the storefront: re-capturing would hit
319
- // ORDER_ALREADY_CAPTURED, and both the webhook and paypal-complete's live
320
- // PayPal re-derivation reconcile the session afterward.
321
- if (!persisted) {
322
- logger.error(
323
- `[paypal] CRITICAL: ${
324
- paymentAction === "authorize" ? "authorization" : "capture"
325
- } succeeded at PayPal but could not be persisted to the session (request_id=${requestId}, cart_id=${cartId}, order_id=${orderId})`
326
- )
327
- try {
328
- await paypal.recordMetric(
329
- paymentAction === "authorize"
330
- ? "authorize_order_persist_failed"
331
- : "capture_order_persist_failed"
332
- )
333
- } catch {
334
- }
335
- }
336
-
337
- try {
338
- await paypal.recordMetric(
339
- paymentAction === "authorize" ? "authorize_order_success" : "capture_order_success"
340
- )
341
- } catch {
342
- }
343
-
344
- return paymentAction === "authorize"
345
- ? res.json({ authorization: payload })
346
- : res.json({ capture: payload })
347
- } catch (e: any) {
348
- const body = (req.body || {}) as Body
349
- logger.error(
350
- `[paypal] capture-order failed (request_id=${requestId}, cart_id=${
351
- body.cart_id ?? "n/a"
352
- }, order_id=${body.order_id ?? "n/a"}, debug_id=${debugId ?? "n/a"}): ${
353
- e?.message ?? String(e)
354
- }`,
355
- e instanceof Error ? e : undefined
356
- )
357
- try {
358
- await paypal.recordAuditEvent("capture_order_failed", {
359
- cart_id: body.cart_id,
360
- order_id: body.order_id,
361
- debug_id: debugId,
362
- request_id: requestId,
363
- message: e?.message || String(e),
364
- })
365
- await paypal.recordMetric("capture_order_failed")
366
- } catch {
367
- }
368
- return res.status(500).json({ message: "Failed to capture PayPal order", request_id: requestId })
369
- }
370
- }
1
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
+ import type { Logger } from "@medusajs/framework/types"
3
+ import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
4
+ import { randomUUID } from "crypto"
5
+ import type PayPalModuleService from "../../../../modules/paypal/service"
6
+ import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
7
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
8
+ import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
9
+ import { extractCaptureStatus } from "../../../../modules/paypal/payment-provider/status-utils"
10
+ import {
11
+ findPayPalSessionForCart,
12
+ getStoredPayPalOrderId,
13
+ updatePayPalSessionData,
14
+ } from "../../../../modules/paypal/utils/payment-session"
15
+
16
+ /** Shape of a PayPal order id — rejects anything that is not one before it hits the API. */
17
+ const PAYPAL_ORDER_ID_RE = /^[A-Z0-9]{10,25}$/
18
+
19
+ type Body = {
20
+ cart_id: string
21
+ order_id: string
22
+ }
23
+
24
+ function resolveIdempotencyKey(
25
+ req: MedusaRequest,
26
+ suffix: string,
27
+ fallback: string
28
+ ) {
29
+ const header =
30
+ req.headers["idempotency-key"] ||
31
+ req.headers["Idempotency-Key"] ||
32
+ req.headers["x-idempotency-key"] ||
33
+ req.headers["X-Idempotency-Key"]
34
+ const key = Array.isArray(header) ? header[0] : header
35
+ if (key && String(key).trim()) {
36
+ return `${String(key).trim()}-${suffix}`
37
+ }
38
+ return fallback || `pp-${suffix}-${randomUUID()}`
39
+ }
40
+
41
+ /**
42
+ * Persist the capture onto the cart's PayPal session. Returns `true` when the
43
+ * data was written (or there was nothing to write because no session exists),
44
+ * and `false` when the write ultimately failed after retries. The caller must
45
+ * NOT silently treat a `false` here as success: the funds were captured at
46
+ * PayPal, so a persistence failure has to be recorded/alerted (the webhook and
47
+ * paypal-complete's live re-derivation are the reconciliation backstop).
48
+ */
49
+ async function attachPayPalCaptureToSession(
50
+ cartId: string,
51
+ orderId: string,
52
+ capture: any,
53
+ scope: any
54
+ ): Promise<boolean> {
55
+ const session = await findPayPalSessionForCart(cartId, scope)
56
+ if (!session) {
57
+ console.warn(
58
+ "[PayPal] attachPayPalCaptureToSession: no session found for cart",
59
+ cartId
60
+ )
61
+ return true
62
+ }
63
+
64
+ const captureId =
65
+ capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id || capture?.id
66
+
67
+ try {
68
+ await updatePayPalSessionData(
69
+ session.session_id,
70
+ {
71
+ paypal: {
72
+ ...((session.session_data || {}).paypal || {}),
73
+ order_id: orderId,
74
+ capture_id: captureId,
75
+ capture,
76
+ },
77
+ },
78
+ scope
79
+ )
80
+ return true
81
+ } catch (e: unknown) {
82
+ console.error(
83
+ "[PayPal] attachPayPalCaptureToSession failed:",
84
+ e instanceof Error ? e.message : e
85
+ )
86
+ return false
87
+ }
88
+ }
89
+
90
+ /** Authorize-intent counterpart of `attachPayPalCaptureToSession`; same contract. */
91
+ async function attachPayPalAuthorizationToSession(
92
+ cartId: string,
93
+ orderId: string,
94
+ authorization: any,
95
+ scope: any
96
+ ): Promise<boolean> {
97
+ const session = await findPayPalSessionForCart(cartId, scope)
98
+ if (!session) {
99
+ console.warn(
100
+ "[PayPal] attachPayPalAuthorizationToSession: no session found for cart",
101
+ cartId
102
+ )
103
+ return true
104
+ }
105
+
106
+ const authorizationId =
107
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
108
+
109
+ try {
110
+ await updatePayPalSessionData(
111
+ session.session_id,
112
+ {
113
+ paypal: {
114
+ ...((session.session_data || {}).paypal || {}),
115
+ order_id: orderId,
116
+ authorization_id: authorizationId,
117
+ authorization,
118
+ },
119
+ },
120
+ scope
121
+ )
122
+ return true
123
+ } catch (e: unknown) {
124
+ console.error(
125
+ "[PayPal] attachPayPalAuthorizationToSession failed:",
126
+ e instanceof Error ? e.message : e
127
+ )
128
+ return false
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Return the session's existing capture ONLY when it demonstrably COMPLETED.
134
+ *
135
+ * The session can carry a capture that never settled: the webhook processor
136
+ * patches `capture_id` onto the session for every capture event, including
137
+ * PAYMENT.CAPTURE.DENIED and PENDING. Blindly short-circuiting on any stored
138
+ * capture would report success to the storefront for a payment that was
139
+ * declined — the buyer would then hit "payment processed but order could not
140
+ * be finalized" instead of being able to retry.
141
+ *
142
+ * - stored capture object with a known status: COMPLETED → return it,
143
+ * anything else → null (fall through and attempt a real capture).
144
+ * - bare `capture_id` (or a capture object whose status can't be read):
145
+ * verify against the live PayPal order. If PayPal can't be reached, return
146
+ * the stored data — the previous fail-safe behavior — since attempting a
147
+ * fresh capture against an unreachable PayPal would fail anyway.
148
+ */
149
+ async function getExistingCompletedCapture(
150
+ cartId: string,
151
+ orderId: string,
152
+ scope: any,
153
+ fetchLiveOrder: () => Promise<any>
154
+ ) {
155
+ try {
156
+ const session = await findPayPalSessionForCart(cartId, scope)
157
+ if (!session) return null
158
+
159
+ const paypalData = (session.session_data || {}).paypal || {}
160
+ const existingOrderId = String(paypalData.order_id || "")
161
+ if (existingOrderId && existingOrderId !== orderId) return null
162
+
163
+ const stored = paypalData.capture
164
+ if (stored) {
165
+ const storedStatus = extractCaptureStatus(stored)
166
+ if (storedStatus === "COMPLETED") return stored
167
+ if (storedStatus) return null
168
+ // no readable status on the stored object — verify live below
169
+ }
170
+ if (!stored && !paypalData.capture_id) return null
171
+
172
+ let order: any
173
+ try {
174
+ order = await fetchLiveOrder()
175
+ } catch {
176
+ return stored || { id: paypalData.capture_id }
177
+ }
178
+ const liveCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
179
+ if (liveCapture && extractCaptureStatus(liveCapture) === "COMPLETED") {
180
+ return liveCapture
181
+ }
182
+ return null
183
+ } catch {
184
+ return null
185
+ }
186
+ }
187
+
188
+ /**
189
+ * POST /store/paypal/capture-order — capture (or, for authorize-intent
190
+ * merchants, authorize) the PayPal order the buyer just approved.
191
+ *
192
+ * Fail-closed: the supplied `order_id` must equal the id create-order stored
193
+ * on this cart's session, and only a COMPLETED capture is reported as success.
194
+ * Responds `{ capture }` or `{ authorization }` with the raw PayPal resource.
195
+ */
196
+ export async function POST(req: MedusaRequest, res: MedusaResponse) {
197
+ const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
198
+ const logger = req.scope.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
199
+ const requestId = randomUUID()
200
+ const { scope } = req
201
+ let debugId: string | null = null
202
+
203
+ try {
204
+ const body = (req.body || {}) as Body
205
+ const cartId = body.cart_id
206
+ const orderId = body.order_id
207
+
208
+ if (!cartId || !orderId) {
209
+ return res
210
+ .status(400)
211
+ .json({ message: "cart_id and order_id are required" })
212
+ }
213
+
214
+ if (typeof cartId !== "string" || !cartId.startsWith("cart_")) {
215
+ return res.status(400).json({ message: "Invalid cart_id format" })
216
+ }
217
+
218
+ if (!PAYPAL_ORDER_ID_RE.test(orderId)) {
219
+ return res.status(400).json({ message: "Invalid order_id format" })
220
+ }
221
+
222
+ // Bind the capture to the cart's own PayPal session, fail-closed: the
223
+ // order_id MUST be the one this cart's session created (stored by
224
+ // create-order). This prevents capturing an arbitrary, caller-supplied
225
+ // order_id against the merchant account.
226
+ const session = await findPayPalSessionForCart(cartId, scope)
227
+ const sessionOrderId = getStoredPayPalOrderId(session?.session_data)
228
+ if (!session || !sessionOrderId) {
229
+ return res.status(409).json({
230
+ message:
231
+ "No PayPal order is associated with this cart's payment session",
232
+ })
233
+ }
234
+ if (sessionOrderId !== orderId) {
235
+ return res.status(400).json({
236
+ message: "order_id does not match the payment session for this cart",
237
+ })
238
+ }
239
+
240
+ const creds = await paypal.getActiveCredentials()
241
+ // Cached app access token (single-flight refresh) — avoids an OAuth
242
+ // round-trip on every capture-order call.
243
+ const base = getPayPalApiBase(creds.environment)
244
+ const accessToken = await paypal.getAppAccessToken()
245
+
246
+ const fetchLiveOrder = async () => {
247
+ const resp = await paypalFetch(
248
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
249
+ {
250
+ method: "GET",
251
+ headers: {
252
+ Authorization: `Bearer ${accessToken}`,
253
+ "Content-Type": "application/json",
254
+ },
255
+ }
256
+ )
257
+ if (!resp.ok) {
258
+ throw new Error(`PayPal get order error (${resp.status})`)
259
+ }
260
+ return resp.json()
261
+ }
262
+
263
+ const existingCapture = await getExistingCompletedCapture(
264
+ cartId,
265
+ orderId,
266
+ scope,
267
+ fetchLiveOrder
268
+ )
269
+ if (existingCapture) {
270
+ return res.json({ capture: existingCapture })
271
+ }
272
+
273
+ const settings = await paypal.getSettings().catch(() => ({}))
274
+ const data =
275
+ settings && typeof settings === "object" && "data" in settings
276
+ ? ((settings as { data?: Record<string, any> }).data ?? {})
277
+ : {}
278
+ const additionalSettings = (data.additional_settings || {}) as Record<
279
+ string,
280
+ any
281
+ >
282
+ const paymentAction =
283
+ typeof additionalSettings.paymentAction === "string"
284
+ ? additionalSettings.paymentAction
285
+ : "capture"
286
+
287
+ // The suffix must include the order id: PayPal deduplicates by
288
+ // PayPal-Request-Id, so a client reusing one Idempotency-Key header across
289
+ // two different orders would otherwise get order A's cached capture back
290
+ // for order B. Named `paypalRequestId` so it never shadows `requestId`
291
+ // (the log/response correlation UUID declared at the top of POST).
292
+ const paypalRequestId = resolveIdempotencyKey(
293
+ req,
294
+ `capture-order-${orderId}`,
295
+ `pp-capture-${orderId}`
296
+ )
297
+ const safeOrderId = encodeURIComponent(orderId)
298
+ const endpoint =
299
+ paymentAction === "authorize"
300
+ ? `${base}/v2/checkout/orders/${safeOrderId}/authorize`
301
+ : `${base}/v2/checkout/orders/${safeOrderId}/capture`
302
+
303
+ const ppResp = await paypalFetch(endpoint, {
304
+ method: "POST",
305
+ headers: {
306
+ Authorization: `Bearer ${accessToken}`,
307
+ "Content-Type": "application/json",
308
+ "PayPal-Request-Id": paypalRequestId,
309
+ "PayPal-Partner-Attribution-Id": BN_CODE,
310
+ },
311
+ })
312
+
313
+ const ppText = await ppResp.text()
314
+ debugId = ppResp.headers.get("paypal-debug-id")
315
+ if (!ppResp.ok) {
316
+ throw new Error(
317
+ `PayPal capture error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`
318
+ )
319
+ }
320
+
321
+ const payload = JSON.parse(ppText)
322
+ let persisted = true
323
+ if (paymentAction === "authorize") {
324
+ persisted = await attachPayPalAuthorizationToSession(
325
+ cartId,
326
+ orderId,
327
+ payload,
328
+ req.scope
329
+ )
330
+ } else {
331
+ // A 2xx capture response does NOT guarantee the funds settled: PayPal
332
+ // returns 201 for PENDING (pending review / eCheck), DECLINED and FAILED
333
+ // captures too. Returning those to the storefront as a successful capture
334
+ // would let it finalize the cart for a payment that never completed, so
335
+ // only a COMPLETED capture is reported as success — the webhook will
336
+ // reconcile a later PENDING→COMPLETED transition.
337
+ const captureStatus = extractCaptureStatus(payload)
338
+ if (captureStatus !== "COMPLETED") {
339
+ throw new Error(
340
+ `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"})${
341
+ debugId ? ` debug_id=${debugId}` : ""
342
+ }`
343
+ )
344
+ }
345
+ persisted = await attachPayPalCaptureToSession(
346
+ cartId,
347
+ orderId,
348
+ payload,
349
+ req.scope
350
+ )
351
+ }
352
+
353
+ // The PayPal operation itself succeeded. If we could not persist it onto the
354
+ // Medusa session, the money is (authorized/)captured but Medusa doesn't yet
355
+ // record it — record a metric and log CRITICAL so it's observable/alertable.
356
+ // We still return success to the storefront: re-capturing would hit
357
+ // ORDER_ALREADY_CAPTURED, and both the webhook and paypal-complete's live
358
+ // PayPal re-derivation reconcile the session afterward.
359
+ if (!persisted) {
360
+ logger.error(
361
+ `[paypal] CRITICAL: ${
362
+ paymentAction === "authorize" ? "authorization" : "capture"
363
+ } succeeded at PayPal but could not be persisted to the session (request_id=${requestId}, cart_id=${cartId}, order_id=${orderId})`
364
+ )
365
+ try {
366
+ await paypal.recordMetric(
367
+ paymentAction === "authorize"
368
+ ? "authorize_order_persist_failed"
369
+ : "capture_order_persist_failed"
370
+ )
371
+ } catch {
372
+ // Metrics are best-effort.
373
+ }
374
+ }
375
+
376
+ try {
377
+ await paypal.recordMetric(
378
+ paymentAction === "authorize"
379
+ ? "authorize_order_success"
380
+ : "capture_order_success"
381
+ )
382
+ } catch {
383
+ // Metrics are best-effort; the capture already succeeded.
384
+ }
385
+
386
+ return paymentAction === "authorize"
387
+ ? res.json({ authorization: payload })
388
+ : res.json({ capture: payload })
389
+ } catch (e: any) {
390
+ const body = (req.body || {}) as Body
391
+ logger.error(
392
+ `[paypal] capture-order failed (request_id=${requestId}, cart_id=${
393
+ body.cart_id ?? "n/a"
394
+ }, order_id=${body.order_id ?? "n/a"}, debug_id=${debugId ?? "n/a"}): ${
395
+ e?.message ?? String(e)
396
+ }`,
397
+ e instanceof Error ? e : undefined
398
+ )
399
+ try {
400
+ await paypal.recordAuditEvent("capture_order_failed", {
401
+ cart_id: body.cart_id,
402
+ order_id: body.order_id,
403
+ debug_id: debugId,
404
+ request_id: requestId,
405
+ message: e?.message || String(e),
406
+ })
407
+ await paypal.recordMetric("capture_order_failed")
408
+ } catch {
409
+ // Audit/metric writes are best-effort.
410
+ }
411
+ return res.status(500).json({
412
+ message: "Failed to capture PayPal order",
413
+ request_id: requestId,
414
+ })
415
+ }
416
+ }