@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,539 +1,586 @@
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 { getCurrencyExponent } from "../../../../modules/paypal/utils/amounts"
6
- import {
7
- assertPayPalCurrencySupported,
8
- normalizeCurrencyCode,
9
- } from "../../../../modules/paypal/utils/currencies"
10
- import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
11
- import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
12
- import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
13
- import type PayPalModuleService from "../../../../modules/paypal/service"
14
- import {
15
- findPayPalSessionForCart,
16
- getStoredPayPalOrderId,
17
- updatePayPalSessionData,
18
- } from "../../../../modules/paypal/utils/payment-session"
19
-
20
- type Body = {
21
- cart_id: string
22
- is_card_payment?: boolean
23
- }
24
-
25
- function resolveIdempotencyKey(req: MedusaRequest, suffix: string, fallback: string) {
26
- const header =
27
- req.headers["idempotency-key"] ||
28
- req.headers["Idempotency-Key"] ||
29
- req.headers["x-idempotency-key"] ||
30
- req.headers["X-Idempotency-Key"]
31
- const key = Array.isArray(header) ? header[0] : header
32
- if (key && String(key).trim()) {
33
- // The suffix must include the cart id (callers pass it): PayPal caches by
34
- // PayPal-Request-Id, so a client reusing one idempotency-key header across
35
- // two carts would otherwise get cart A's cached order (A's amount) back
36
- // for cart B.
37
- return `${String(key).trim()}-${suffix}`
38
- }
39
- return fallback || `pp-${suffix}-${randomUUID()}`
40
- }
41
-
42
- // Persist the PayPal order id onto the cart's PayPal payment session so that
43
- // capture-order can bind the capture to the order this cart created. Resolved
44
- // through the Payment module service (the previous direct-container resolve of
45
- // "payment_collection"/"payment_session" did not exist in the request scope, so
46
- // the id was silently never stored and every capture failed fail-closed).
47
- async function attachPayPalOrderToSession(
48
- req: MedusaRequest,
49
- cartId: string,
50
- orderId: string
51
- ) {
52
- const session = await findPayPalSessionForCart(cartId, req.scope)
53
- if (!session) {
54
- return
55
- }
56
- await updatePayPalSessionData(
57
- session.session_id,
58
- {
59
- paypal: {
60
- ...(session.session_data.paypal || {}),
61
- order_id: orderId,
62
- },
63
- },
64
- req.scope
65
- )
66
- }
67
-
68
- async function getExistingPayPalOrderId(req: MedusaRequest, cartId: string) {
69
- const session = await findPayPalSessionForCart(cartId, req.scope)
70
- return getStoredPayPalOrderId(session?.session_data)
71
- }
72
-
73
- function resolveReturnUrl(req: MedusaRequest) {
74
- const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
75
- if (!configured) {
76
- return undefined
77
- }
78
- return `${configured.replace(/\/$/, "")}/checkout`
79
- }
80
-
81
- function resolveCancelUrl(req: MedusaRequest) {
82
- const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
83
- if (!configured) {
84
- return undefined
85
- }
86
- return `${configured.replace(/\/$/, "")}/cart`
87
- }
88
-
89
- export async function POST(req: MedusaRequest, res: MedusaResponse) {
90
- const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
91
- const logger = req.scope.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
92
- const requestId = randomUUID()
93
- let debugId: string | null = null
94
-
95
- try {
96
- const body = (req.body || {}) as Body
97
- const cartId = body.cart_id
98
- const isCardPayment = !!(body as any).is_card_payment
99
-
100
- if (!cartId || typeof cartId !== "string") {
101
- return res.status(400).json({ message: "cart_id is required" })
102
- }
103
-
104
- if (!cartId.startsWith("cart_")) {
105
- return res.status(400).json({ message: "Invalid cart_id format" })
106
- }
107
-
108
- // A stored order id is only reused after verifying it still matches the
109
- // cart (amount/currency/state) — see below, once the cart is loaded. Buyers
110
- // who back out of the PayPal popup and change their cart would otherwise be
111
- // charged the stale total.
112
- const existingOrderId = await getExistingPayPalOrderId(req, cartId)
113
-
114
- const query = req.scope.resolve("query")
115
-
116
- const { data } = await query.graph({
117
- entity: "cart",
118
- fields: [
119
- "id",
120
- "total",
121
- "subtotal",
122
- "shipping_total",
123
- "tax_total",
124
- "discount_total",
125
- "gift_card_total",
126
- "currency_code",
127
- "region.currency_code",
128
- "items.title",
129
- "items.quantity",
130
- "items.unit_price",
131
- "items.subtotal",
132
- "items.tax_total",
133
- "items.total",
134
- ],
135
- filters: { id: cartId },
136
- })
137
-
138
- const cart = (data?.[0] as any) || null
139
-
140
- if (!cart) {
141
- return res.status(404).json({ message: "Cart not found" })
142
- }
143
-
144
- const creds = await paypal.getActiveCredentials()
145
-
146
- type PayPalSettingsResponse = {
147
- data?: {
148
- additional_settings?: Record<string, unknown>
149
- api_details?: Record<string, unknown>
150
- advanced_card_payments?: Record<string, unknown>
151
- }
152
- }
153
- const settings = await paypal
154
- .getSettings()
155
- .catch((): PayPalSettingsResponse => ({}))
156
- const settingsData = (settings.data || {}) as Record<string, any>
157
- const additionalSettings = settingsData.additional_settings || {}
158
- const apiDetails = settingsData.api_details || {}
159
- const advancedCardSettings = (settingsData.advanced_card_payments || {}) as Record<string, any>
160
-
161
- const threeDsRaw =
162
- typeof advancedCardSettings.threeDS === "string"
163
- ? advancedCardSettings.threeDS
164
- : "when_required"
165
-
166
- const threeDsMethod: string | null = isCardPayment
167
- ? (threeDsRaw === "always"
168
- ? "SCA_ALWAYS"
169
- : "SCA_WHEN_REQUIRED")
170
- : null
171
- const configuredCurrency =
172
- typeof apiDetails.currency_code === "string"
173
- ? normalizeCurrencyCode(apiDetails.currency_code)
174
- : normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
175
-
176
- const currency = normalizeCurrencyCode(
177
- cart.region?.currency_code || cart.currency_code || configuredCurrency
178
- )
179
- assertPayPalCurrencySupported({
180
- currencyCode: currency,
181
- paypalCurrencyOverride: configuredCurrency,
182
- })
183
-
184
- const exponent = getCurrencyExponent(currency)
185
- const totalMajor = Number(cart.total || 0)
186
- const value = totalMajor.toFixed(exponent)
187
-
188
- // Reuse the stored PayPal order only when it still matches the cart: same
189
- // amount, same currency, and still in a reusable (pre-terminal) state. On
190
- // mismatch fall through and create a fresh order (which replaces the
191
- // stored id on the session). If PayPal can't be reached for the check,
192
- // reuse the stored id — matching the previous behavior rather than
193
- // blocking checkout on a transient error.
194
- if (existingOrderId) {
195
- try {
196
- const checkBase = getPayPalApiBase(creds.environment)
197
- const checkToken = await paypal.getAppAccessToken()
198
- const checkResp = await paypalFetch(
199
- `${checkBase}/v2/checkout/orders/${encodeURIComponent(existingOrderId)}`,
200
- {
201
- method: "GET",
202
- headers: {
203
- Authorization: `Bearer ${checkToken}`,
204
- "Content-Type": "application/json",
205
- },
206
- }
207
- )
208
- if (checkResp.ok) {
209
- const existingOrder = await checkResp.json()
210
- const existingAmount = existingOrder?.purchase_units?.[0]?.amount
211
- const existingStatus = String(existingOrder?.status || "").toUpperCase()
212
- const reusableStatus = ["CREATED", "APPROVED", "PAYER_ACTION_REQUIRED"].includes(
213
- existingStatus
214
- )
215
- const amountMatches =
216
- String(existingAmount?.value || "") === value &&
217
- String(existingAmount?.currency_code || "").toUpperCase() === currency
218
- if (reusableStatus && amountMatches) {
219
- return res.json({ id: existingOrderId })
220
- }
221
- if (existingStatus === "COMPLETED") {
222
- // Already paid — never mint a second order for this cart.
223
- return res.json({ id: existingOrderId })
224
- }
225
- logger.info(
226
- `[paypal] create-order: stored order ${existingOrderId} is stale (status=${existingStatus}, amount=${existingAmount?.value} ${existingAmount?.currency_code} vs cart ${value} ${currency}) — creating a fresh order (request_id=${requestId})`
227
- )
228
- } else if (checkResp.status !== 404) {
229
- // Transient PayPal-side failure: reuse rather than block checkout.
230
- return res.json({ id: existingOrderId })
231
- }
232
- // 404: the stored order no longer exists (e.g. environment switched) —
233
- // fall through and create a fresh one.
234
- } catch {
235
- return res.json({ id: existingOrderId })
236
- }
237
- }
238
-
239
- const paymentActionRaw =
240
- typeof additionalSettings.paymentAction === "string"
241
- ? additionalSettings.paymentAction
242
- : "capture"
243
- const paymentAction = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
244
- const brandName =
245
- typeof additionalSettings.brandName === "string"
246
- ? additionalSettings.brandName
247
- : undefined
248
- const landingPageRaw =
249
- typeof additionalSettings.landingPage === "string"
250
- ? additionalSettings.landingPage
251
- : undefined
252
- const landingPage =
253
- landingPageRaw === "login"
254
- ? "LOGIN"
255
- : landingPageRaw === "billing"
256
- ? "BILLING"
257
- : landingPageRaw === "no_preference"
258
- ? "NO_PREFERENCE"
259
- : undefined
260
- const requireInstantPayment =
261
- typeof additionalSettings.requireInstantPayment === "boolean"
262
- ? additionalSettings.requireInstantPayment
263
- : undefined
264
- const sendItemDetails = additionalSettings.sendItemDetails !== false
265
- const statementName =
266
- typeof additionalSettings.creditCardStatementName === "string"
267
- ? additionalSettings.creditCardStatementName.trim()
268
- : ""
269
- const invoicePrefix =
270
- typeof additionalSettings.invoicePrefix === "string"
271
- ? additionalSettings.invoicePrefix
272
- : ""
273
- const cartIdSuffix = cart.id.slice(-12).toUpperCase()
274
- const invoiceId = `${invoicePrefix}${cartIdSuffix}`.trim() || cart.id
275
- const returnUrl =
276
- (typeof apiDetails.storefront_url === "string" && apiDetails.storefront_url.trim()
277
- ? `${apiDetails.storefront_url.replace(/\/$/, "")}/checkout`
278
- : resolveReturnUrl(req))
279
- const cancelUrl =
280
- (typeof apiDetails.storefront_url === "string" && apiDetails.storefront_url.trim()
281
- ? `${apiDetails.storefront_url.replace(/\/$/, "")}/cart`
282
- : resolveCancelUrl(req))
283
-
284
- const applicationContext: Record<string, any> = {
285
- ...(brandName ? { brand_name: brandName } : {}),
286
- ...(landingPage ? { landing_page: landingPage } : {}),
287
- ...(requireInstantPayment ? { payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED" } : {}),
288
- ...(returnUrl ? { return_url: returnUrl } : {}),
289
- ...(cancelUrl ? { cancel_url: cancelUrl } : {}),
290
- }
291
-
292
- const subtotalMajor = Number(cart.subtotal || 0)
293
- const shippingMajor = Number(cart.shipping_total || 0)
294
- const taxMajor = Number(cart.tax_total || 0)
295
- const discountMajor = Number(cart.discount_total || 0)
296
- const giftCardMajor = Number(cart.gift_card_total || 0)
297
- const lineItems = Array.isArray((cart as any).items) ? (cart as any).items : []
298
-
299
- const purchaseItemsRaw = sendItemDetails
300
- ? lineItems
301
- .map((item: any) => {
302
- const quantity = Number(item?.quantity || 0)
303
- const lineSubtotalMajor = Number(
304
- item?.subtotal ?? (Number(item?.unit_price || 0) * quantity)
305
- )
306
- const unitAmount =
307
- quantity > 0 ? parseFloat((lineSubtotalMajor / quantity).toFixed(exponent)) : 0
308
-
309
- if (!quantity || Number.isNaN(quantity) || Number.isNaN(unitAmount)) {
310
- return null
311
- }
312
-
313
- return {
314
- quantity,
315
- unitAmount,
316
- paypalItem: {
317
- name: String(item?.title || "Item").slice(0, 127),
318
- quantity: String(Math.max(1, quantity)),
319
- unit_amount: {
320
- currency_code: currency,
321
- value: unitAmount.toFixed(exponent),
322
- },
323
- },
324
- }
325
- })
326
- .filter(Boolean)
327
- : []
328
-
329
- const roundedItemSum = purchaseItemsRaw.reduce(
330
- (sum: number, item: any) => sum + item.unitAmount * item.quantity,
331
- 0
332
- )
333
- const roundedItemSumFixed = parseFloat(roundedItemSum.toFixed(exponent))
334
-
335
- const finalPurchaseItems = purchaseItemsRaw.map((item: any) => item.paypalItem)
336
-
337
- // Reconcile rounding drift so the items we send sum to the cart subtotal.
338
- if (finalPurchaseItems.length > 0) {
339
- const diff = parseFloat((subtotalMajor - roundedItemSumFixed).toFixed(exponent))
340
- if (Math.abs(diff) > 0.000001) {
341
- finalPurchaseItems.push({
342
- name: "Line Item Amount Offset",
343
- quantity: "1",
344
- unit_amount: {
345
- currency_code: currency,
346
- value: diff.toFixed(exponent),
347
- },
348
- })
349
- }
350
- }
351
-
352
- // Only send line items (and an item_total) when we actually have them.
353
- const sendItems = finalPurchaseItems.length > 0
354
-
355
- // item_total MUST equal the exact sum of (unit_amount * quantity) of the
356
- // items we send; otherwise PayPal rejects with ITEM_TOTAL_MISMATCH.
357
- const itemsTotalMajor = sendItems
358
- ? parseFloat(
359
- finalPurchaseItems
360
- .reduce(
361
- (sum: number, it: any) =>
362
- sum + Number(it.unit_amount.value) * Number(it.quantity),
363
- 0
364
- )
365
- .toFixed(exponent)
366
- )
367
- : 0
368
-
369
- const discountValue = discountMajor + giftCardMajor
370
-
371
- // Build a breakdown only when we send line items. A breakdown whose
372
- // item_total has no matching items (or items with no item_total) is
373
- // rejected by PayPal, so with no items we send just the order total.
374
- const breakdown: Record<string, any> = {}
375
- if (sendItems) {
376
- if (itemsTotalMajor > 0) {
377
- breakdown.item_total = {
378
- currency_code: currency,
379
- value: itemsTotalMajor.toFixed(exponent),
380
- }
381
- }
382
- if (shippingMajor > 0) {
383
- breakdown.shipping = {
384
- currency_code: currency,
385
- value: shippingMajor.toFixed(exponent),
386
- }
387
- }
388
- if (taxMajor > 0) {
389
- breakdown.tax_total = {
390
- currency_code: currency,
391
- value: taxMajor.toFixed(exponent),
392
- }
393
- }
394
- if (discountValue > 0) {
395
- breakdown.discount = {
396
- currency_code: currency,
397
- value: discountValue.toFixed(exponent),
398
- }
399
- }
400
-
401
- const breakdownSum = parseFloat(
402
- (itemsTotalMajor + shippingMajor + taxMajor - discountValue).toFixed(exponent)
403
- )
404
-
405
- if (Math.abs(breakdownSum - totalMajor) > 0.000001) {
406
- const gap = parseFloat((totalMajor - breakdownSum).toFixed(exponent))
407
-
408
- if (gap > 0) {
409
- breakdown.tax_total = {
410
- currency_code: currency,
411
- value: parseFloat(
412
- ((Number(breakdown.tax_total?.value || 0) + gap).toFixed(exponent))
413
- ).toFixed(exponent),
414
- }
415
- } else {
416
- breakdown.shipping_discount = {
417
- currency_code: currency,
418
- value: Math.abs(gap).toFixed(exponent),
419
- }
420
- }
421
- }
422
- }
423
-
424
- logger.debug(
425
- `[paypal] create-order line items (request_id=${requestId}): send_item_details=${sendItemDetails}, cart_items=${lineItems.length}, sent_items=${finalPurchaseItems.length}, items_total=${itemsTotalMajor}, subtotal=${subtotalMajor}, total=${totalMajor}`
426
- )
427
-
428
- // Use the module's cached app access token (single-flight refresh, ~9h TTL)
429
- // instead of minting a fresh OAuth token on every create-order call.
430
- const base = getPayPalApiBase(creds.environment)
431
- const accessToken = await paypal.getAppAccessToken()
432
-
433
- // Deterministic-per-(cart, amount, currency) idempotency key for the PayPal
434
- // call. The amount/currency MUST be part of the key: PayPal replays the
435
- // cached response for a reused PayPal-Request-Id, so a key derived from the
436
- // cart id alone would return the ORIGINAL order (at the original total)
437
- // when the buyer changes the cart and a fresh order is minted — silently
438
- // re-charging the stale amount and defeating the staleness check above.
439
- // Kept distinct from `requestId` (the log/response correlation id declared
440
- // at the top of POST) so the two never shadow each other.
441
- const paypalRequestId = resolveIdempotencyKey(
442
- req,
443
- `create-order-${cart.id}-${value}-${currency}`,
444
- `pp-create-${cart.id}-${value}-${currency}`
445
- )
446
-
447
- const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
448
- method: "POST",
449
- headers: {
450
- Authorization: `Bearer ${accessToken}`,
451
- "Content-Type": "application/json",
452
- "PayPal-Request-Id": paypalRequestId,
453
- "PayPal-Partner-Attribution-Id": BN_CODE,
454
- },
455
- body: JSON.stringify({
456
- intent: paymentAction,
457
- purchase_units: [
458
- {
459
- reference_id: "default",
460
- // Set custom_id on the purchase unit (not just the order) so PayPal
461
- // propagates the cart id onto capture/refund webhook resources,
462
- // letting webhooks resolve the session directly without a scan.
463
- custom_id: cart.id,
464
- invoice_id: invoiceId,
465
- ...(statementName ? { soft_descriptor: statementName.slice(0, 22) } : {}),
466
- amount: {
467
- currency_code: currency,
468
- value,
469
- ...(Object.keys(breakdown).length > 0 ? { breakdown } : {}),
470
- },
471
- ...(finalPurchaseItems.length > 0 ? { items: finalPurchaseItems } : {}),
472
- },
473
- ],
474
- ...(threeDsMethod
475
- ? {
476
- payment_source: {
477
- card: {
478
- attributes: {
479
- verification: {
480
- method: threeDsMethod,
481
- },
482
- },
483
- },
484
- },
485
- }
486
- : {}),
487
- custom_id: cart.id,
488
- ...(Object.keys(applicationContext).length > 0
489
- ? { application_context: applicationContext }
490
- : {}),
491
- }),
492
- })
493
-
494
- const ppText = await ppResp.text()
495
- debugId = ppResp.headers.get("paypal-debug-id")
496
- if (!ppResp.ok) {
497
- throw new Error(
498
- `PayPal create order error (${ppResp.status}): ${ppText}${
499
- debugId ? ` debug_id=${debugId}` : ""
500
- }`
501
- )
502
- }
503
-
504
- const order = JSON.parse(ppText)
505
-
506
- await attachPayPalOrderToSession(req, cart.id, order.id)
507
-
508
- try {
509
- await paypal.recordMetric("create_order_success")
510
- } catch {
511
- }
512
- return res.json({ id: order.id })
513
- } catch (e: any) {
514
- const body = (req.body || {}) as Body
515
- logger.error(
516
- `[paypal] create-order failed (request_id=${requestId}, cart_id=${
517
- body.cart_id ?? "n/a"
518
- }, debug_id=${debugId ?? "n/a"}): ${e?.message ?? String(e)}`,
519
- e instanceof Error ? e : undefined
520
- )
521
- try {
522
- await paypal.recordAuditEvent("create_order_failed", {
523
- cart_id: body.cart_id,
524
- debug_id: debugId,
525
- request_id: requestId,
526
- message: e?.message || String(e),
527
- })
528
- await paypal.recordMetric("create_order_failed")
529
- } catch {
530
- }
531
- const rawMessage = e?.message || ""
532
- const isCurrencyError =
533
- rawMessage.includes("PayPal does not support currency") ||
534
- rawMessage.includes("PayPal is configured for")
535
- const status = isCurrencyError ? 400 : 500
536
- const message = isCurrencyError ? rawMessage : "Failed to create PayPal order"
537
- return res.status(status).json({ message, request_id: requestId })
538
- }
539
- }
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 { getCurrencyExponent } from "../../../../modules/paypal/utils/amounts"
6
+ import {
7
+ assertPayPalCurrencySupported,
8
+ normalizeCurrencyCode,
9
+ } from "../../../../modules/paypal/utils/currencies"
10
+ import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
11
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
12
+ import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
13
+ import type PayPalModuleService from "../../../../modules/paypal/service"
14
+ import {
15
+ findPayPalSessionForCart,
16
+ getStoredPayPalOrderId,
17
+ updatePayPalSessionData,
18
+ } from "../../../../modules/paypal/utils/payment-session"
19
+
20
+ type Body = {
21
+ cart_id: string
22
+ is_card_payment?: boolean
23
+ }
24
+
25
+ function resolveIdempotencyKey(
26
+ req: MedusaRequest,
27
+ suffix: string,
28
+ fallback: string
29
+ ) {
30
+ const header =
31
+ req.headers["idempotency-key"] ||
32
+ req.headers["Idempotency-Key"] ||
33
+ req.headers["x-idempotency-key"] ||
34
+ req.headers["X-Idempotency-Key"]
35
+ const key = Array.isArray(header) ? header[0] : header
36
+ if (key && String(key).trim()) {
37
+ // The suffix must include the cart id (callers pass it): PayPal caches by
38
+ // PayPal-Request-Id, so a client reusing one idempotency-key header across
39
+ // two carts would otherwise get cart A's cached order (A's amount) back
40
+ // for cart B.
41
+ return `${String(key).trim()}-${suffix}`
42
+ }
43
+ return fallback || `pp-${suffix}-${randomUUID()}`
44
+ }
45
+
46
+ // Persist the PayPal order id onto the cart's PayPal payment session so that
47
+ // capture-order can bind the capture to the order this cart created. Resolved
48
+ // through the Payment module service (the previous direct-container resolve of
49
+ // "payment_collection"/"payment_session" did not exist in the request scope, so
50
+ // the id was silently never stored and every capture failed fail-closed).
51
+ async function attachPayPalOrderToSession(
52
+ req: MedusaRequest,
53
+ cartId: string,
54
+ orderId: string
55
+ ) {
56
+ const session = await findPayPalSessionForCart(cartId, req.scope)
57
+ if (!session) {
58
+ return
59
+ }
60
+ await updatePayPalSessionData(
61
+ session.session_id,
62
+ {
63
+ paypal: {
64
+ ...(session.session_data.paypal || {}),
65
+ order_id: orderId,
66
+ },
67
+ },
68
+ req.scope
69
+ )
70
+ }
71
+
72
+ async function getExistingPayPalOrderId(req: MedusaRequest, cartId: string) {
73
+ const session = await findPayPalSessionForCart(cartId, req.scope)
74
+ return getStoredPayPalOrderId(session?.session_data)
75
+ }
76
+
77
+ /** Storefront return URL from env (`STOREFRONT_URL` / `STORE_URL`), if set. */
78
+ function resolveReturnUrl() {
79
+ const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
80
+ if (!configured) {
81
+ return undefined
82
+ }
83
+ return `${configured.replace(/\/$/, "")}/checkout`
84
+ }
85
+
86
+ /** Storefront cancel URL from env (`STOREFRONT_URL` / `STORE_URL`), if set. */
87
+ function resolveCancelUrl() {
88
+ const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
89
+ if (!configured) {
90
+ return undefined
91
+ }
92
+ return `${configured.replace(/\/$/, "")}/cart`
93
+ }
94
+
95
+ /**
96
+ * POST /store/paypal/create-order — create (or reuse) the PayPal order for a
97
+ * cart and store its id on the cart's PayPal payment session.
98
+ *
99
+ * Returns `{ id }` — the PayPal order id the storefront hands to the JS SDK.
100
+ * Line items and an amount breakdown are sent when `sendItemDetails` is on,
101
+ * with rounding drift reconciled so PayPal's strict total checks pass.
102
+ */
103
+ export async function POST(req: MedusaRequest, res: MedusaResponse) {
104
+ const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
105
+ const logger = req.scope.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
106
+ const requestId = randomUUID()
107
+ let debugId: string | null = null
108
+
109
+ try {
110
+ const body = (req.body || {}) as Body
111
+ const cartId = body.cart_id
112
+ const isCardPayment = !!body.is_card_payment
113
+
114
+ if (!cartId || typeof cartId !== "string") {
115
+ return res.status(400).json({ message: "cart_id is required" })
116
+ }
117
+
118
+ if (!cartId.startsWith("cart_")) {
119
+ return res.status(400).json({ message: "Invalid cart_id format" })
120
+ }
121
+
122
+ // A stored order id is only reused after verifying it still matches the
123
+ // cart (amount/currency/state) — see below, once the cart is loaded. Buyers
124
+ // who back out of the PayPal popup and change their cart would otherwise be
125
+ // charged the stale total.
126
+ const existingOrderId = await getExistingPayPalOrderId(req, cartId)
127
+
128
+ const query = req.scope.resolve("query")
129
+
130
+ const { data } = await query.graph({
131
+ entity: "cart",
132
+ fields: [
133
+ "id",
134
+ "total",
135
+ "subtotal",
136
+ "shipping_total",
137
+ "tax_total",
138
+ "discount_total",
139
+ "gift_card_total",
140
+ "currency_code",
141
+ "region.currency_code",
142
+ "items.title",
143
+ "items.quantity",
144
+ "items.unit_price",
145
+ "items.subtotal",
146
+ "items.tax_total",
147
+ "items.total",
148
+ ],
149
+ filters: { id: cartId },
150
+ })
151
+
152
+ const cart = (data?.[0] as any) || null
153
+
154
+ if (!cart) {
155
+ return res.status(404).json({ message: "Cart not found" })
156
+ }
157
+
158
+ const creds = await paypal.getActiveCredentials()
159
+
160
+ type PayPalSettingsResponse = {
161
+ data?: {
162
+ additional_settings?: Record<string, unknown>
163
+ api_details?: Record<string, unknown>
164
+ advanced_card_payments?: Record<string, unknown>
165
+ }
166
+ }
167
+ const settings = await paypal
168
+ .getSettings()
169
+ .catch((): PayPalSettingsResponse => ({}))
170
+ const settingsData = (settings.data || {}) as Record<string, any>
171
+ const additionalSettings = settingsData.additional_settings || {}
172
+ const apiDetails = settingsData.api_details || {}
173
+ const advancedCardSettings = (settingsData.advanced_card_payments ||
174
+ {}) as Record<string, any>
175
+
176
+ const threeDsRaw =
177
+ typeof advancedCardSettings.threeDS === "string"
178
+ ? advancedCardSettings.threeDS
179
+ : "when_required"
180
+
181
+ const threeDsMethod: string | null = isCardPayment
182
+ ? threeDsRaw === "always"
183
+ ? "SCA_ALWAYS"
184
+ : "SCA_WHEN_REQUIRED"
185
+ : null
186
+ const configuredCurrency =
187
+ typeof apiDetails.currency_code === "string"
188
+ ? normalizeCurrencyCode(apiDetails.currency_code)
189
+ : normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
190
+
191
+ const currency = normalizeCurrencyCode(
192
+ cart.region?.currency_code || cart.currency_code || configuredCurrency
193
+ )
194
+ assertPayPalCurrencySupported({
195
+ currencyCode: currency,
196
+ paypalCurrencyOverride: configuredCurrency,
197
+ })
198
+
199
+ const exponent = getCurrencyExponent(currency)
200
+ const totalMajor = Number(cart.total || 0)
201
+ const value = totalMajor.toFixed(exponent)
202
+
203
+ // Reuse the stored PayPal order only when it still matches the cart: same
204
+ // amount, same currency, and still in a reusable (pre-terminal) state. On
205
+ // mismatch fall through and create a fresh order (which replaces the
206
+ // stored id on the session). If PayPal can't be reached for the check,
207
+ // reuse the stored id — matching the previous behavior rather than
208
+ // blocking checkout on a transient error.
209
+ if (existingOrderId) {
210
+ try {
211
+ const checkBase = getPayPalApiBase(creds.environment)
212
+ const checkToken = await paypal.getAppAccessToken()
213
+ const checkResp = await paypalFetch(
214
+ `${checkBase}/v2/checkout/orders/${encodeURIComponent(existingOrderId)}`,
215
+ {
216
+ method: "GET",
217
+ headers: {
218
+ Authorization: `Bearer ${checkToken}`,
219
+ "Content-Type": "application/json",
220
+ },
221
+ }
222
+ )
223
+ if (checkResp.ok) {
224
+ const existingOrder = await checkResp.json()
225
+ const existingAmount = existingOrder?.purchase_units?.[0]?.amount
226
+ const existingStatus = String(
227
+ existingOrder?.status || ""
228
+ ).toUpperCase()
229
+ const reusableStatus = [
230
+ "CREATED",
231
+ "APPROVED",
232
+ "PAYER_ACTION_REQUIRED",
233
+ ].includes(existingStatus)
234
+ const amountMatches =
235
+ String(existingAmount?.value || "") === value &&
236
+ String(existingAmount?.currency_code || "").toUpperCase() ===
237
+ currency
238
+ if (reusableStatus && amountMatches) {
239
+ return res.json({ id: existingOrderId })
240
+ }
241
+ if (existingStatus === "COMPLETED") {
242
+ // Already paid — never mint a second order for this cart.
243
+ return res.json({ id: existingOrderId })
244
+ }
245
+ logger.info(
246
+ `[paypal] create-order: stored order ${existingOrderId} is stale (status=${existingStatus}, amount=${existingAmount?.value} ${existingAmount?.currency_code} vs cart ${value} ${currency}) — creating a fresh order (request_id=${requestId})`
247
+ )
248
+ } else if (checkResp.status !== 404) {
249
+ // Transient PayPal-side failure: reuse rather than block checkout.
250
+ return res.json({ id: existingOrderId })
251
+ }
252
+ // 404: the stored order no longer exists (e.g. environment switched) —
253
+ // fall through and create a fresh one.
254
+ } catch {
255
+ return res.json({ id: existingOrderId })
256
+ }
257
+ }
258
+
259
+ const paymentActionRaw =
260
+ typeof additionalSettings.paymentAction === "string"
261
+ ? additionalSettings.paymentAction
262
+ : "capture"
263
+ const paymentAction =
264
+ paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
265
+ const brandName =
266
+ typeof additionalSettings.brandName === "string"
267
+ ? additionalSettings.brandName
268
+ : undefined
269
+ const landingPageRaw =
270
+ typeof additionalSettings.landingPage === "string"
271
+ ? additionalSettings.landingPage
272
+ : undefined
273
+ const landingPage =
274
+ landingPageRaw === "login"
275
+ ? "LOGIN"
276
+ : landingPageRaw === "billing"
277
+ ? "BILLING"
278
+ : landingPageRaw === "no_preference"
279
+ ? "NO_PREFERENCE"
280
+ : undefined
281
+ const requireInstantPayment =
282
+ typeof additionalSettings.requireInstantPayment === "boolean"
283
+ ? additionalSettings.requireInstantPayment
284
+ : undefined
285
+ const sendItemDetails = additionalSettings.sendItemDetails !== false
286
+ const statementName =
287
+ typeof additionalSettings.creditCardStatementName === "string"
288
+ ? additionalSettings.creditCardStatementName.trim()
289
+ : ""
290
+ const invoicePrefix =
291
+ typeof additionalSettings.invoicePrefix === "string"
292
+ ? additionalSettings.invoicePrefix
293
+ : ""
294
+ const cartIdSuffix = cart.id.slice(-12).toUpperCase()
295
+ const invoiceId = `${invoicePrefix}${cartIdSuffix}`.trim() || cart.id
296
+ const returnUrl =
297
+ typeof apiDetails.storefront_url === "string" &&
298
+ apiDetails.storefront_url.trim()
299
+ ? `${apiDetails.storefront_url.replace(/\/$/, "")}/checkout`
300
+ : resolveReturnUrl()
301
+ const cancelUrl =
302
+ typeof apiDetails.storefront_url === "string" &&
303
+ apiDetails.storefront_url.trim()
304
+ ? `${apiDetails.storefront_url.replace(/\/$/, "")}/cart`
305
+ : resolveCancelUrl()
306
+
307
+ const applicationContext: Record<string, any> = {
308
+ ...(brandName ? { brand_name: brandName } : {}),
309
+ ...(landingPage ? { landing_page: landingPage } : {}),
310
+ ...(requireInstantPayment
311
+ ? { payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED" }
312
+ : {}),
313
+ ...(returnUrl ? { return_url: returnUrl } : {}),
314
+ ...(cancelUrl ? { cancel_url: cancelUrl } : {}),
315
+ }
316
+
317
+ const subtotalMajor = Number(cart.subtotal || 0)
318
+ const shippingMajor = Number(cart.shipping_total || 0)
319
+ const taxMajor = Number(cart.tax_total || 0)
320
+ const discountMajor = Number(cart.discount_total || 0)
321
+ const giftCardMajor = Number(cart.gift_card_total || 0)
322
+ const lineItems = Array.isArray((cart as any).items)
323
+ ? (cart as any).items
324
+ : []
325
+
326
+ const purchaseItemsRaw = sendItemDetails
327
+ ? lineItems
328
+ .map((item: any) => {
329
+ const quantity = Number(item?.quantity || 0)
330
+ const lineSubtotalMajor = Number(
331
+ item?.subtotal ?? Number(item?.unit_price || 0) * quantity
332
+ )
333
+ const unitAmount =
334
+ quantity > 0
335
+ ? parseFloat((lineSubtotalMajor / quantity).toFixed(exponent))
336
+ : 0
337
+
338
+ if (
339
+ !quantity ||
340
+ Number.isNaN(quantity) ||
341
+ Number.isNaN(unitAmount)
342
+ ) {
343
+ return null
344
+ }
345
+
346
+ return {
347
+ quantity,
348
+ unitAmount,
349
+ paypalItem: {
350
+ name: String(item?.title || "Item").slice(0, 127),
351
+ quantity: String(Math.max(1, quantity)),
352
+ unit_amount: {
353
+ currency_code: currency,
354
+ value: unitAmount.toFixed(exponent),
355
+ },
356
+ },
357
+ }
358
+ })
359
+ .filter(Boolean)
360
+ : []
361
+
362
+ const roundedItemSum = purchaseItemsRaw.reduce(
363
+ (sum: number, item: any) => sum + item.unitAmount * item.quantity,
364
+ 0
365
+ )
366
+ const roundedItemSumFixed = parseFloat(roundedItemSum.toFixed(exponent))
367
+
368
+ const finalPurchaseItems = purchaseItemsRaw.map(
369
+ (item: any) => item.paypalItem
370
+ )
371
+
372
+ // Reconcile rounding drift so the items we send sum to the cart subtotal.
373
+ if (finalPurchaseItems.length > 0) {
374
+ const diff = parseFloat(
375
+ (subtotalMajor - roundedItemSumFixed).toFixed(exponent)
376
+ )
377
+ if (Math.abs(diff) > 0.000001) {
378
+ finalPurchaseItems.push({
379
+ name: "Line Item Amount Offset",
380
+ quantity: "1",
381
+ unit_amount: {
382
+ currency_code: currency,
383
+ value: diff.toFixed(exponent),
384
+ },
385
+ })
386
+ }
387
+ }
388
+
389
+ // Only send line items (and an item_total) when we actually have them.
390
+ const sendItems = finalPurchaseItems.length > 0
391
+
392
+ // item_total MUST equal the exact sum of (unit_amount * quantity) of the
393
+ // items we send; otherwise PayPal rejects with ITEM_TOTAL_MISMATCH.
394
+ const itemsTotalMajor = sendItems
395
+ ? parseFloat(
396
+ finalPurchaseItems
397
+ .reduce(
398
+ (sum: number, it: any) =>
399
+ sum + Number(it.unit_amount.value) * Number(it.quantity),
400
+ 0
401
+ )
402
+ .toFixed(exponent)
403
+ )
404
+ : 0
405
+
406
+ const discountValue = discountMajor + giftCardMajor
407
+
408
+ // Build a breakdown only when we send line items. A breakdown whose
409
+ // item_total has no matching items (or items with no item_total) is
410
+ // rejected by PayPal, so with no items we send just the order total.
411
+ const breakdown: Record<string, any> = {}
412
+ if (sendItems) {
413
+ if (itemsTotalMajor > 0) {
414
+ breakdown.item_total = {
415
+ currency_code: currency,
416
+ value: itemsTotalMajor.toFixed(exponent),
417
+ }
418
+ }
419
+ if (shippingMajor > 0) {
420
+ breakdown.shipping = {
421
+ currency_code: currency,
422
+ value: shippingMajor.toFixed(exponent),
423
+ }
424
+ }
425
+ if (taxMajor > 0) {
426
+ breakdown.tax_total = {
427
+ currency_code: currency,
428
+ value: taxMajor.toFixed(exponent),
429
+ }
430
+ }
431
+ if (discountValue > 0) {
432
+ breakdown.discount = {
433
+ currency_code: currency,
434
+ value: discountValue.toFixed(exponent),
435
+ }
436
+ }
437
+
438
+ const breakdownSum = parseFloat(
439
+ (itemsTotalMajor + shippingMajor + taxMajor - discountValue).toFixed(
440
+ exponent
441
+ )
442
+ )
443
+
444
+ if (Math.abs(breakdownSum - totalMajor) > 0.000001) {
445
+ const gap = parseFloat((totalMajor - breakdownSum).toFixed(exponent))
446
+
447
+ if (gap > 0) {
448
+ breakdown.tax_total = {
449
+ currency_code: currency,
450
+ value: parseFloat(
451
+ (Number(breakdown.tax_total?.value || 0) + gap).toFixed(exponent)
452
+ ).toFixed(exponent),
453
+ }
454
+ } else {
455
+ breakdown.shipping_discount = {
456
+ currency_code: currency,
457
+ value: Math.abs(gap).toFixed(exponent),
458
+ }
459
+ }
460
+ }
461
+ }
462
+
463
+ logger.debug(
464
+ `[paypal] create-order line items (request_id=${requestId}): send_item_details=${sendItemDetails}, cart_items=${lineItems.length}, sent_items=${finalPurchaseItems.length}, items_total=${itemsTotalMajor}, subtotal=${subtotalMajor}, total=${totalMajor}`
465
+ )
466
+
467
+ // Use the module's cached app access token (single-flight refresh, ~9h TTL)
468
+ // instead of minting a fresh OAuth token on every create-order call.
469
+ const base = getPayPalApiBase(creds.environment)
470
+ const accessToken = await paypal.getAppAccessToken()
471
+
472
+ // Deterministic-per-(cart, amount, currency) idempotency key for the PayPal
473
+ // call. The amount/currency MUST be part of the key: PayPal replays the
474
+ // cached response for a reused PayPal-Request-Id, so a key derived from the
475
+ // cart id alone would return the ORIGINAL order (at the original total)
476
+ // when the buyer changes the cart and a fresh order is minted — silently
477
+ // re-charging the stale amount and defeating the staleness check above.
478
+ // Kept distinct from `requestId` (the log/response correlation id declared
479
+ // at the top of POST) so the two never shadow each other.
480
+ const paypalRequestId = resolveIdempotencyKey(
481
+ req,
482
+ `create-order-${cart.id}-${value}-${currency}`,
483
+ `pp-create-${cart.id}-${value}-${currency}`
484
+ )
485
+
486
+ const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
487
+ method: "POST",
488
+ headers: {
489
+ Authorization: `Bearer ${accessToken}`,
490
+ "Content-Type": "application/json",
491
+ "PayPal-Request-Id": paypalRequestId,
492
+ "PayPal-Partner-Attribution-Id": BN_CODE,
493
+ },
494
+ body: JSON.stringify({
495
+ intent: paymentAction,
496
+ purchase_units: [
497
+ {
498
+ reference_id: "default",
499
+ // Set custom_id on the purchase unit (not just the order) so PayPal
500
+ // propagates the cart id onto capture/refund webhook resources,
501
+ // letting webhooks resolve the session directly without a scan.
502
+ custom_id: cart.id,
503
+ invoice_id: invoiceId,
504
+ ...(statementName
505
+ ? { soft_descriptor: statementName.slice(0, 22) }
506
+ : {}),
507
+ amount: {
508
+ currency_code: currency,
509
+ value,
510
+ ...(Object.keys(breakdown).length > 0 ? { breakdown } : {}),
511
+ },
512
+ ...(finalPurchaseItems.length > 0
513
+ ? { items: finalPurchaseItems }
514
+ : {}),
515
+ },
516
+ ],
517
+ ...(threeDsMethod
518
+ ? {
519
+ payment_source: {
520
+ card: {
521
+ attributes: {
522
+ verification: {
523
+ method: threeDsMethod,
524
+ },
525
+ },
526
+ },
527
+ },
528
+ }
529
+ : {}),
530
+ custom_id: cart.id,
531
+ ...(Object.keys(applicationContext).length > 0
532
+ ? { application_context: applicationContext }
533
+ : {}),
534
+ }),
535
+ })
536
+
537
+ const ppText = await ppResp.text()
538
+ debugId = ppResp.headers.get("paypal-debug-id")
539
+ if (!ppResp.ok) {
540
+ throw new Error(
541
+ `PayPal create order error (${ppResp.status}): ${ppText}${
542
+ debugId ? ` debug_id=${debugId}` : ""
543
+ }`
544
+ )
545
+ }
546
+
547
+ const order = JSON.parse(ppText)
548
+
549
+ await attachPayPalOrderToSession(req, cart.id, order.id)
550
+
551
+ try {
552
+ await paypal.recordMetric("create_order_success")
553
+ } catch {
554
+ // Metrics are best-effort; never fail the order because of them.
555
+ }
556
+ return res.json({ id: order.id })
557
+ } catch (e: any) {
558
+ const body = (req.body || {}) as Body
559
+ logger.error(
560
+ `[paypal] create-order failed (request_id=${requestId}, cart_id=${
561
+ body.cart_id ?? "n/a"
562
+ }, debug_id=${debugId ?? "n/a"}): ${e?.message ?? String(e)}`,
563
+ e instanceof Error ? e : undefined
564
+ )
565
+ try {
566
+ await paypal.recordAuditEvent("create_order_failed", {
567
+ cart_id: body.cart_id,
568
+ debug_id: debugId,
569
+ request_id: requestId,
570
+ message: e?.message || String(e),
571
+ })
572
+ await paypal.recordMetric("create_order_failed")
573
+ } catch {
574
+ // Audit/metric writes are best-effort.
575
+ }
576
+ const rawMessage = e?.message || ""
577
+ const isCurrencyError =
578
+ rawMessage.includes("PayPal does not support currency") ||
579
+ rawMessage.includes("PayPal is configured for")
580
+ const status = isCurrencyError ? 400 : 500
581
+ const message = isCurrencyError
582
+ ? rawMessage
583
+ : "Failed to create PayPal order"
584
+ return res.status(status).json({ message, request_id: requestId })
585
+ }
586
+ }