@easypayment/medusa-payment-paypal 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/.medusa/server/src/admin/index.js +392 -138
  2. package/.medusa/server/src/admin/index.mjs +392 -138
  3. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts +1 -0
  4. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  5. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js +5 -1
  6. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  7. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts +1 -0
  8. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts.map +1 -1
  9. package/.medusa/server/src/api/admin/paypal/disconnect/route.js +1 -0
  10. package/.medusa/server/src/api/admin/paypal/disconnect/route.js.map +1 -1
  11. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts +2 -0
  12. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts.map +1 -1
  13. package/.medusa/server/src/api/admin/paypal/environment/route.js +2 -0
  14. package/.medusa/server/src/api/admin/paypal/environment/route.js.map +1 -1
  15. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +9 -0
  16. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
  17. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +9 -4
  18. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
  19. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts +7 -1
  20. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts.map +1 -1
  21. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js +9 -2
  22. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js.map +1 -1
  23. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts +1 -0
  24. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts.map +1 -1
  25. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js +1 -0
  26. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js.map +1 -1
  27. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts +1 -0
  28. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts.map +1 -1
  29. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js +10 -3
  30. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js.map +1 -1
  31. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts +2 -0
  32. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts.map +1 -1
  33. package/.medusa/server/src/api/admin/paypal/settings/route.js +9 -2
  34. package/.medusa/server/src/api/admin/paypal/settings/route.js.map +1 -1
  35. package/.medusa/server/src/api/admin/paypal/status/route.d.ts +4 -0
  36. package/.medusa/server/src/api/admin/paypal/status/route.d.ts.map +1 -1
  37. package/.medusa/server/src/api/admin/paypal/status/route.js +9 -1
  38. package/.medusa/server/src/api/admin/paypal/status/route.js.map +1 -1
  39. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts +4 -0
  40. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  41. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +11 -1
  42. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  43. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts +8 -0
  44. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  45. package/.medusa/server/src/api/store/paypal/capture-order/route.js +23 -3
  46. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  47. package/.medusa/server/src/api/store/paypal/config/route.d.ts +5 -0
  48. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  49. package/.medusa/server/src/api/store/paypal/config/route.js +12 -5
  50. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  51. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +8 -0
  52. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  53. package/.medusa/server/src/api/store/paypal/create-order/route.js +80 -26
  54. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  55. package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
  56. package/.medusa/server/src/api/store/paypal/onboard-return/route.js +19 -19
  57. package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
  58. package/.medusa/server/src/api/store/paypal/settings/route.d.ts +1 -0
  59. package/.medusa/server/src/api/store/paypal/settings/route.d.ts.map +1 -1
  60. package/.medusa/server/src/api/store/paypal/settings/route.js +4 -1
  61. package/.medusa/server/src/api/store/paypal/settings/route.js.map +1 -1
  62. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts +7 -0
  63. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
  64. package/.medusa/server/src/api/store/paypal/webhook/route.js +34 -3
  65. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
  66. package/.medusa/server/src/api/store/paypal-complete/route.d.ts +8 -0
  67. package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -1
  68. package/.medusa/server/src/api/store/paypal-complete/route.js +55 -8
  69. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  70. package/.medusa/server/src/api/utils/rate-limit.d.ts +4 -0
  71. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  72. package/.medusa/server/src/api/utils/rate-limit.js +9 -4
  73. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  74. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts +5 -0
  75. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  76. package/.medusa/server/src/jobs/paypal-webhook-retry.js +13 -2
  77. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  78. package/.medusa/server/src/modules/paypal/index.d.ts +1 -0
  79. package/.medusa/server/src/modules/paypal/index.d.ts.map +1 -1
  80. package/.medusa/server/src/modules/paypal/index.js +1 -0
  81. package/.medusa/server/src/modules/paypal/index.js.map +1 -1
  82. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js +22 -22
  83. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js +11 -11
  84. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js +18 -18
  85. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js +16 -16
  86. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js +20 -20
  87. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js +14 -14
  88. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js +15 -15
  89. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts.map +1 -1
  90. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js.map +1 -1
  91. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts.map +1 -1
  92. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js.map +1 -1
  93. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts.map +1 -1
  94. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js.map +1 -1
  95. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js +6 -6
  96. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts +5 -0
  97. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts.map +1 -1
  98. package/.medusa/server/src/modules/paypal/models/paypal_connection.js +5 -0
  99. package/.medusa/server/src/modules/paypal/models/paypal_connection.js.map +1 -1
  100. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts +4 -0
  101. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts.map +1 -1
  102. package/.medusa/server/src/modules/paypal/models/paypal_metric.js +4 -0
  103. package/.medusa/server/src/modules/paypal/models/paypal_metric.js.map +1 -1
  104. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts +5 -0
  105. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts.map +1 -1
  106. package/.medusa/server/src/modules/paypal/models/paypal_settings.js +5 -0
  107. package/.medusa/server/src/modules/paypal/models/paypal_settings.js.map +1 -1
  108. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts +7 -0
  109. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts.map +1 -1
  110. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js +7 -0
  111. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js.map +1 -1
  112. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +24 -1
  113. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  114. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +296 -0
  115. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  116. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +14 -7
  117. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  118. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +40 -198
  119. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  120. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -1
  121. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -1
  122. package/.medusa/server/src/modules/paypal/payment-provider/index.js +6 -4
  123. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -1
  124. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +9 -2
  125. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  126. package/.medusa/server/src/modules/paypal/payment-provider/service.js +29 -181
  127. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  128. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts +21 -0
  129. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.d.ts.map +1 -1
  130. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js +54 -0
  131. package/.medusa/server/src/modules/paypal/payment-provider/status-utils.js.map +1 -1
  132. package/.medusa/server/src/modules/paypal/service.d.ts +72 -2
  133. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  134. package/.medusa/server/src/modules/paypal/service.js +159 -33
  135. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  136. package/.medusa/server/src/modules/paypal/types/config.d.ts +2 -0
  137. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  138. package/.medusa/server/src/modules/paypal/types/config.js +5 -2
  139. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  140. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -0
  141. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
  142. package/.medusa/server/src/modules/paypal/utils/amounts.js +15 -5
  143. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
  144. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  145. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  146. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +45 -1
  147. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  148. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +9 -0
  149. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -1
  150. package/.medusa/server/src/modules/paypal/utils/currencies.js +13 -0
  151. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -1
  152. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +12 -0
  153. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  154. package/.medusa/server/src/modules/paypal/utils/payment-session.js +4 -3
  155. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  156. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +1 -0
  157. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -1
  158. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +1 -0
  159. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -1
  160. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts +11 -0
  161. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  162. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +17 -1
  163. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  164. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +6 -0
  165. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -1
  166. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +6 -0
  167. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -1
  168. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts +2 -0
  169. package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
  170. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +6 -1
  171. package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
  172. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +43 -0
  173. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  174. package/.medusa/server/src/modules/paypal/webhook-processor.js +57 -5
  175. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  176. package/.medusa/server/src/providers/paypal/index.d.ts +1 -0
  177. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -1
  178. package/.medusa/server/src/providers/paypal/index.js +1 -0
  179. package/.medusa/server/src/providers/paypal/index.js.map +1 -1
  180. package/.medusa/server/src/providers/paypal_card/index.d.ts +1 -0
  181. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -1
  182. package/.medusa/server/src/providers/paypal_card/index.js +1 -0
  183. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -1
  184. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  185. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -1
  186. package/.medusa/server/src/subscribers/paypal-order-invoice.js +9 -1
  187. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -1
  188. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +1 -0
  189. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  190. package/.medusa/server/src/subscribers/paypal-webhook-process.js +17 -4
  191. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  192. package/CHANGELOG.md +65 -0
  193. package/README.md +184 -184
  194. package/package.json +7 -4
  195. package/src/admin/index.ts +1 -1
  196. package/src/admin/routes/settings/paypal/_components/FieldRow.tsx +38 -29
  197. package/src/admin/routes/settings/paypal/_components/SectionCard.tsx +29 -26
  198. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +49 -48
  199. package/src/admin/routes/settings/paypal/_components/Toast.tsx +63 -52
  200. package/src/admin/routes/settings/paypal/_utils/adminFetch.ts +52 -32
  201. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +246 -139
  202. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +208 -123
  203. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +9 -5
  204. package/src/admin/routes/settings/paypal/connection/page.tsx +974 -908
  205. package/src/admin/routes/settings/paypal/google-pay/page.tsx +9 -5
  206. package/src/admin/routes/settings/paypal/page.tsx +14 -13
  207. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +9 -5
  208. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +304 -273
  209. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +48 -39
  210. package/src/api/admin/paypal/disconnect/route.ts +15 -14
  211. package/src/api/admin/paypal/environment/route.ts +34 -32
  212. package/src/api/admin/paypal/onboard-complete/route.ts +61 -50
  213. package/src/api/admin/paypal/onboarding-link/route.ts +91 -76
  214. package/src/api/admin/paypal/onboarding-status/route.ts +21 -20
  215. package/src/api/admin/paypal/save-credentials/route.ts +48 -37
  216. package/src/api/admin/paypal/settings/route.ts +63 -45
  217. package/src/api/admin/paypal/status/route.ts +29 -17
  218. package/src/api/hooks/paypal/onboard-return/route.ts +15 -15
  219. package/src/api/hooks/paypal/webhook/route.ts +17 -17
  220. package/src/api/middlewares.ts +61 -61
  221. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +69 -54
  222. package/src/api/store/paypal/capture-order/route.ts +416 -370
  223. package/src/api/store/paypal/config/route.ts +121 -115
  224. package/src/api/store/paypal/create-order/route.ts +611 -539
  225. package/src/api/store/paypal/onboard-return/route.ts +116 -113
  226. package/src/api/store/paypal/settings/route.ts +29 -19
  227. package/src/api/store/paypal/webhook/route.ts +380 -314
  228. package/src/api/store/paypal-complete/route.ts +184 -128
  229. package/src/api/utils/rate-limit.ts +143 -129
  230. package/src/index.ts +1 -1
  231. package/src/jobs/paypal-webhook-retry.ts +257 -241
  232. package/src/modules/paypal/index.ts +9 -8
  233. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -33
  234. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -22
  235. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -29
  236. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -27
  237. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -31
  238. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -25
  239. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -26
  240. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +15 -11
  241. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +15 -11
  242. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +15 -11
  243. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -17
  244. package/src/modules/paypal/migrations/20270202000000_align_nullable_defaults.ts +44 -44
  245. package/src/modules/paypal/migrations/20270301000000_add_webhook_transmission_id_index.ts +15 -15
  246. package/src/modules/paypal/models/paypal_connection.ts +28 -23
  247. package/src/modules/paypal/models/paypal_metric.ts +13 -9
  248. package/src/modules/paypal/models/paypal_settings.ts +13 -8
  249. package/src/modules/paypal/models/paypal_webhook_event.ts +26 -19
  250. package/src/modules/paypal/payment-provider/base-provider.ts +700 -275
  251. package/src/modules/paypal/payment-provider/card-service.ts +693 -855
  252. package/src/modules/paypal/payment-provider/index.ts +14 -15
  253. package/src/modules/paypal/payment-provider/service.ts +673 -836
  254. package/src/modules/paypal/payment-provider/status-utils.ts +116 -59
  255. package/src/modules/paypal/payment-provider/webhook-utils.ts +109 -109
  256. package/src/modules/paypal/service.ts +362 -115
  257. package/src/modules/paypal/types/config.ts +70 -65
  258. package/src/modules/paypal/utils/amounts.ts +123 -107
  259. package/src/modules/paypal/utils/core-workflow.ts +46 -46
  260. package/src/modules/paypal/utils/credential-resolver.ts +315 -271
  261. package/src/modules/paypal/utils/currencies.ts +97 -84
  262. package/src/modules/paypal/utils/partner.ts +8 -8
  263. package/src/modules/paypal/utils/payment-session.ts +144 -138
  264. package/src/modules/paypal/utils/paypal-auth.ts +6 -5
  265. package/src/modules/paypal/utils/paypal-fetch.ts +197 -181
  266. package/src/modules/paypal/utils/provider-ids.ts +21 -15
  267. package/src/modules/paypal/utils/secret-crypto.ts +226 -197
  268. package/src/modules/paypal/utils/webhook-verify.ts +61 -61
  269. package/src/modules/paypal/webhook-processor.ts +641 -573
  270. package/src/providers/paypal/index.ts +9 -8
  271. package/src/providers/paypal_card/index.ts +9 -8
  272. package/src/subscribers/paypal-order-invoice.ts +180 -173
  273. package/src/subscribers/paypal-webhook-process.ts +147 -131
  274. package/tsconfig.json +21 -31
@@ -1,539 +1,611 @@
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
+ // NOTE: do not add `shipping_methods.*` here. Medusa's totals decorator
131
+ // computes shipping from whatever shipping-method rows are loaded, so a
132
+ // partial selection (e.g. `shipping_methods.id`, without `amount`) makes
133
+ // `total`/`shipping_subtotal` come back WITHOUT shipping and the buyer is
134
+ // under-charged. Left unrequested, the query computes every total below
135
+ // (including `shipping_subtotal`) from the full cart.
136
+ const { data } = await query.graph({
137
+ entity: "cart",
138
+ fields: [
139
+ "id",
140
+ "total",
141
+ "subtotal",
142
+ "item_subtotal",
143
+ "shipping_subtotal",
144
+ "shipping_total",
145
+ "tax_total",
146
+ "discount_total",
147
+ "discount_subtotal",
148
+ "currency_code",
149
+ "region.currency_code",
150
+ "items.title",
151
+ "items.quantity",
152
+ "items.unit_price",
153
+ "items.subtotal",
154
+ "items.tax_total",
155
+ "items.total",
156
+ ],
157
+ filters: { id: cartId },
158
+ })
159
+
160
+ const cart = (data?.[0] as any) || null
161
+
162
+ if (!cart) {
163
+ return res.status(404).json({ message: "Cart not found" })
164
+ }
165
+
166
+ const creds = await paypal.getActiveCredentials()
167
+
168
+ type PayPalSettingsResponse = {
169
+ data?: {
170
+ additional_settings?: Record<string, unknown>
171
+ api_details?: Record<string, unknown>
172
+ advanced_card_payments?: Record<string, unknown>
173
+ }
174
+ }
175
+ const settings = await paypal
176
+ .getSettings()
177
+ .catch((): PayPalSettingsResponse => ({}))
178
+ const settingsData = (settings.data || {}) as Record<string, any>
179
+ const additionalSettings = settingsData.additional_settings || {}
180
+ const apiDetails = settingsData.api_details || {}
181
+ const advancedCardSettings = (settingsData.advanced_card_payments ||
182
+ {}) as Record<string, any>
183
+
184
+ const threeDsRaw =
185
+ typeof advancedCardSettings.threeDS === "string"
186
+ ? advancedCardSettings.threeDS
187
+ : "when_required"
188
+
189
+ const threeDsMethod: string | null = isCardPayment
190
+ ? threeDsRaw === "always"
191
+ ? "SCA_ALWAYS"
192
+ : "SCA_WHEN_REQUIRED"
193
+ : null
194
+ const configuredCurrency =
195
+ typeof apiDetails.currency_code === "string"
196
+ ? normalizeCurrencyCode(apiDetails.currency_code)
197
+ : normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
198
+
199
+ const currency = normalizeCurrencyCode(
200
+ cart.region?.currency_code || cart.currency_code || configuredCurrency
201
+ )
202
+ assertPayPalCurrencySupported({
203
+ currencyCode: currency,
204
+ paypalCurrencyOverride: configuredCurrency,
205
+ })
206
+
207
+ const exponent = getCurrencyExponent(currency)
208
+ const totalMajor = Number(cart.total || 0)
209
+ const value = totalMajor.toFixed(exponent)
210
+
211
+ // Reuse the stored PayPal order only when it still matches the cart: same
212
+ // amount, same currency, and still in a reusable (pre-terminal) state. On
213
+ // mismatch fall through and create a fresh order (which replaces the
214
+ // stored id on the session). If PayPal can't be reached for the check,
215
+ // reuse the stored id — matching the previous behavior rather than
216
+ // blocking checkout on a transient error.
217
+ if (existingOrderId) {
218
+ try {
219
+ const checkBase = getPayPalApiBase(creds.environment)
220
+ const checkToken = await paypal.getAppAccessToken()
221
+ const checkResp = await paypalFetch(
222
+ `${checkBase}/v2/checkout/orders/${encodeURIComponent(existingOrderId)}`,
223
+ {
224
+ method: "GET",
225
+ headers: {
226
+ Authorization: `Bearer ${checkToken}`,
227
+ "Content-Type": "application/json",
228
+ },
229
+ }
230
+ )
231
+ if (checkResp.ok) {
232
+ const existingOrder = await checkResp.json()
233
+ const existingAmount = existingOrder?.purchase_units?.[0]?.amount
234
+ const existingStatus = String(
235
+ existingOrder?.status || ""
236
+ ).toUpperCase()
237
+ const reusableStatus = [
238
+ "CREATED",
239
+ "APPROVED",
240
+ "PAYER_ACTION_REQUIRED",
241
+ ].includes(existingStatus)
242
+ const amountMatches =
243
+ String(existingAmount?.value || "") === value &&
244
+ String(existingAmount?.currency_code || "").toUpperCase() ===
245
+ currency
246
+ if (reusableStatus && amountMatches) {
247
+ return res.json({ id: existingOrderId })
248
+ }
249
+ if (existingStatus === "COMPLETED") {
250
+ // Already paid — never mint a second order for this cart.
251
+ return res.json({ id: existingOrderId })
252
+ }
253
+ logger.info(
254
+ `[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})`
255
+ )
256
+ } else if (checkResp.status !== 404) {
257
+ // Transient PayPal-side failure: reuse rather than block checkout.
258
+ return res.json({ id: existingOrderId })
259
+ }
260
+ // 404: the stored order no longer exists (e.g. environment switched) —
261
+ // fall through and create a fresh one.
262
+ } catch {
263
+ return res.json({ id: existingOrderId })
264
+ }
265
+ }
266
+
267
+ const paymentActionRaw =
268
+ typeof additionalSettings.paymentAction === "string"
269
+ ? additionalSettings.paymentAction
270
+ : "capture"
271
+ const paymentAction =
272
+ paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
273
+ const brandName =
274
+ typeof additionalSettings.brandName === "string"
275
+ ? additionalSettings.brandName
276
+ : undefined
277
+ const landingPageRaw =
278
+ typeof additionalSettings.landingPage === "string"
279
+ ? additionalSettings.landingPage
280
+ : undefined
281
+ const landingPage =
282
+ landingPageRaw === "login"
283
+ ? "LOGIN"
284
+ : landingPageRaw === "billing"
285
+ ? "BILLING"
286
+ : landingPageRaw === "no_preference"
287
+ ? "NO_PREFERENCE"
288
+ : undefined
289
+ const requireInstantPayment =
290
+ typeof additionalSettings.requireInstantPayment === "boolean"
291
+ ? additionalSettings.requireInstantPayment
292
+ : undefined
293
+ const sendItemDetails = additionalSettings.sendItemDetails !== false
294
+ const statementName =
295
+ typeof additionalSettings.creditCardStatementName === "string"
296
+ ? additionalSettings.creditCardStatementName.trim()
297
+ : ""
298
+ const invoicePrefix =
299
+ typeof additionalSettings.invoicePrefix === "string"
300
+ ? additionalSettings.invoicePrefix
301
+ : ""
302
+ const cartIdSuffix = cart.id.slice(-12).toUpperCase()
303
+ const invoiceId = `${invoicePrefix}${cartIdSuffix}`.trim() || cart.id
304
+ const returnUrl =
305
+ typeof apiDetails.storefront_url === "string" &&
306
+ apiDetails.storefront_url.trim()
307
+ ? `${apiDetails.storefront_url.replace(/\/$/, "")}/checkout`
308
+ : resolveReturnUrl()
309
+ const cancelUrl =
310
+ typeof apiDetails.storefront_url === "string" &&
311
+ apiDetails.storefront_url.trim()
312
+ ? `${apiDetails.storefront_url.replace(/\/$/, "")}/cart`
313
+ : resolveCancelUrl()
314
+
315
+ const applicationContext: Record<string, any> = {
316
+ ...(brandName ? { brand_name: brandName } : {}),
317
+ ...(landingPage ? { landing_page: landingPage } : {}),
318
+ ...(requireInstantPayment
319
+ ? { payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED" }
320
+ : {}),
321
+ ...(returnUrl ? { return_url: returnUrl } : {}),
322
+ ...(cancelUrl ? { cancel_url: cancelUrl } : {}),
323
+ }
324
+
325
+ // Medusa v2's `cart.subtotal` is items PLUS shipping (pre-tax, pre-discount)
326
+ // and its `total` is `subtotal + tax_total - discount_subtotal`. The PayPal
327
+ // breakdown needs the item-only subtotal for `item_total` — using
328
+ // `cart.subtotal` here made every cart with a shipping charge grow a bogus
329
+ // "Line Item Amount Offset" item worth the shipping fee plus a matching
330
+ // fake `shipping_discount` to make the numbers balance.
331
+ // Likewise `shipping_total` includes the tax on shipping, which
332
+ // `tax_total` already carries — PayPal's `shipping` must be the pre-tax
333
+ // `shipping_subtotal` or the breakdown is short by the shipping tax.
334
+ const shippingMajor = Number(
335
+ cart.shipping_subtotal ?? cart.shipping_total ?? 0
336
+ )
337
+ const subtotalMajor =
338
+ cart.item_subtotal !== undefined && cart.item_subtotal !== null
339
+ ? Number(cart.item_subtotal || 0)
340
+ : Number(cart.subtotal || 0) - shippingMajor
341
+ const taxMajor = Number(cart.tax_total || 0)
342
+ // `discount_subtotal` is the pre-tax discount actually subtracted from the
343
+ // total; `discount_total` also carries the discount's tax share.
344
+ const discountMajor = Number(
345
+ cart.discount_subtotal ?? cart.discount_total ?? 0
346
+ )
347
+ const lineItems = Array.isArray((cart as any).items)
348
+ ? (cart as any).items
349
+ : []
350
+
351
+ const purchaseItemsRaw = sendItemDetails
352
+ ? lineItems
353
+ .map((item: any) => {
354
+ const quantity = Number(item?.quantity || 0)
355
+ const lineSubtotalMajor = Number(
356
+ item?.subtotal ?? Number(item?.unit_price || 0) * quantity
357
+ )
358
+ const unitAmount =
359
+ quantity > 0
360
+ ? parseFloat((lineSubtotalMajor / quantity).toFixed(exponent))
361
+ : 0
362
+
363
+ if (
364
+ !quantity ||
365
+ Number.isNaN(quantity) ||
366
+ Number.isNaN(unitAmount)
367
+ ) {
368
+ return null
369
+ }
370
+
371
+ return {
372
+ quantity,
373
+ unitAmount,
374
+ paypalItem: {
375
+ name: String(item?.title || "Item").slice(0, 127),
376
+ quantity: String(Math.max(1, quantity)),
377
+ unit_amount: {
378
+ currency_code: currency,
379
+ value: unitAmount.toFixed(exponent),
380
+ },
381
+ },
382
+ }
383
+ })
384
+ .filter(Boolean)
385
+ : []
386
+
387
+ const roundedItemSum = purchaseItemsRaw.reduce(
388
+ (sum: number, item: any) => sum + item.unitAmount * item.quantity,
389
+ 0
390
+ )
391
+ const roundedItemSumFixed = parseFloat(roundedItemSum.toFixed(exponent))
392
+
393
+ const finalPurchaseItems = purchaseItemsRaw.map(
394
+ (item: any) => item.paypalItem
395
+ )
396
+
397
+ // Reconcile rounding drift so the items we send sum to the cart subtotal.
398
+ if (finalPurchaseItems.length > 0) {
399
+ const diff = parseFloat(
400
+ (subtotalMajor - roundedItemSumFixed).toFixed(exponent)
401
+ )
402
+ if (Math.abs(diff) > 0.000001) {
403
+ finalPurchaseItems.push({
404
+ name: "Line Item Amount Offset",
405
+ quantity: "1",
406
+ unit_amount: {
407
+ currency_code: currency,
408
+ value: diff.toFixed(exponent),
409
+ },
410
+ })
411
+ }
412
+ }
413
+
414
+ // Only send line items (and an item_total) when we actually have them.
415
+ const sendItems = finalPurchaseItems.length > 0
416
+
417
+ // item_total MUST equal the exact sum of (unit_amount * quantity) of the
418
+ // items we send; otherwise PayPal rejects with ITEM_TOTAL_MISMATCH.
419
+ const itemsTotalMajor = sendItems
420
+ ? parseFloat(
421
+ finalPurchaseItems
422
+ .reduce(
423
+ (sum: number, it: any) =>
424
+ sum + Number(it.unit_amount.value) * Number(it.quantity),
425
+ 0
426
+ )
427
+ .toFixed(exponent)
428
+ )
429
+ : 0
430
+
431
+ const discountValue = discountMajor
432
+
433
+ // Build a breakdown only when we send line items. A breakdown whose
434
+ // item_total has no matching items (or items with no item_total) is
435
+ // rejected by PayPal, so with no items we send just the order total.
436
+ const breakdown: Record<string, any> = {}
437
+ if (sendItems) {
438
+ if (itemsTotalMajor > 0) {
439
+ breakdown.item_total = {
440
+ currency_code: currency,
441
+ value: itemsTotalMajor.toFixed(exponent),
442
+ }
443
+ }
444
+ if (shippingMajor > 0) {
445
+ breakdown.shipping = {
446
+ currency_code: currency,
447
+ value: shippingMajor.toFixed(exponent),
448
+ }
449
+ }
450
+ if (taxMajor > 0) {
451
+ breakdown.tax_total = {
452
+ currency_code: currency,
453
+ value: taxMajor.toFixed(exponent),
454
+ }
455
+ }
456
+ if (discountValue > 0) {
457
+ breakdown.discount = {
458
+ currency_code: currency,
459
+ value: discountValue.toFixed(exponent),
460
+ }
461
+ }
462
+
463
+ const breakdownSum = parseFloat(
464
+ (itemsTotalMajor + shippingMajor + taxMajor - discountValue).toFixed(
465
+ exponent
466
+ )
467
+ )
468
+
469
+ if (Math.abs(breakdownSum - totalMajor) > 0.000001) {
470
+ const gap = parseFloat((totalMajor - breakdownSum).toFixed(exponent))
471
+
472
+ if (gap > 0) {
473
+ breakdown.tax_total = {
474
+ currency_code: currency,
475
+ value: parseFloat(
476
+ (Number(breakdown.tax_total?.value || 0) + gap).toFixed(exponent)
477
+ ).toFixed(exponent),
478
+ }
479
+ } else {
480
+ breakdown.shipping_discount = {
481
+ currency_code: currency,
482
+ value: Math.abs(gap).toFixed(exponent),
483
+ }
484
+ }
485
+ }
486
+ }
487
+
488
+ logger.debug(
489
+ `[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}`
490
+ )
491
+
492
+ // Use the module's cached app access token (single-flight refresh, ~9h TTL)
493
+ // instead of minting a fresh OAuth token on every create-order call.
494
+ const base = getPayPalApiBase(creds.environment)
495
+ const accessToken = await paypal.getAppAccessToken()
496
+
497
+ // Deterministic-per-(cart, amount, currency) idempotency key for the PayPal
498
+ // call. The amount/currency MUST be part of the key: PayPal replays the
499
+ // cached response for a reused PayPal-Request-Id, so a key derived from the
500
+ // cart id alone would return the ORIGINAL order (at the original total)
501
+ // when the buyer changes the cart and a fresh order is minted — silently
502
+ // re-charging the stale amount and defeating the staleness check above.
503
+ // Kept distinct from `requestId` (the log/response correlation id declared
504
+ // at the top of POST) so the two never shadow each other.
505
+ const paypalRequestId = resolveIdempotencyKey(
506
+ req,
507
+ `create-order-${cart.id}-${value}-${currency}`,
508
+ `pp-create-${cart.id}-${value}-${currency}`
509
+ )
510
+
511
+ const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
512
+ method: "POST",
513
+ headers: {
514
+ Authorization: `Bearer ${accessToken}`,
515
+ "Content-Type": "application/json",
516
+ "PayPal-Request-Id": paypalRequestId,
517
+ "PayPal-Partner-Attribution-Id": BN_CODE,
518
+ },
519
+ body: JSON.stringify({
520
+ intent: paymentAction,
521
+ purchase_units: [
522
+ {
523
+ reference_id: "default",
524
+ // Set custom_id on the purchase unit (not just the order) so PayPal
525
+ // propagates the cart id onto capture/refund webhook resources,
526
+ // letting webhooks resolve the session directly without a scan.
527
+ custom_id: cart.id,
528
+ invoice_id: invoiceId,
529
+ ...(statementName
530
+ ? { soft_descriptor: statementName.slice(0, 22) }
531
+ : {}),
532
+ amount: {
533
+ currency_code: currency,
534
+ value,
535
+ ...(Object.keys(breakdown).length > 0 ? { breakdown } : {}),
536
+ },
537
+ ...(finalPurchaseItems.length > 0
538
+ ? { items: finalPurchaseItems }
539
+ : {}),
540
+ },
541
+ ],
542
+ ...(threeDsMethod
543
+ ? {
544
+ payment_source: {
545
+ card: {
546
+ attributes: {
547
+ verification: {
548
+ method: threeDsMethod,
549
+ },
550
+ },
551
+ },
552
+ },
553
+ }
554
+ : {}),
555
+ custom_id: cart.id,
556
+ ...(Object.keys(applicationContext).length > 0
557
+ ? { application_context: applicationContext }
558
+ : {}),
559
+ }),
560
+ })
561
+
562
+ const ppText = await ppResp.text()
563
+ debugId = ppResp.headers.get("paypal-debug-id")
564
+ if (!ppResp.ok) {
565
+ throw new Error(
566
+ `PayPal create order error (${ppResp.status}): ${ppText}${
567
+ debugId ? ` debug_id=${debugId}` : ""
568
+ }`
569
+ )
570
+ }
571
+
572
+ const order = JSON.parse(ppText)
573
+
574
+ await attachPayPalOrderToSession(req, cart.id, order.id)
575
+
576
+ try {
577
+ await paypal.recordMetric("create_order_success")
578
+ } catch {
579
+ // Metrics are best-effort; never fail the order because of them.
580
+ }
581
+ return res.json({ id: order.id })
582
+ } catch (e: any) {
583
+ const body = (req.body || {}) as Body
584
+ logger.error(
585
+ `[paypal] create-order failed (request_id=${requestId}, cart_id=${
586
+ body.cart_id ?? "n/a"
587
+ }, debug_id=${debugId ?? "n/a"}): ${e?.message ?? String(e)}`,
588
+ e instanceof Error ? e : undefined
589
+ )
590
+ try {
591
+ await paypal.recordAuditEvent("create_order_failed", {
592
+ cart_id: body.cart_id,
593
+ debug_id: debugId,
594
+ request_id: requestId,
595
+ message: e?.message || String(e),
596
+ })
597
+ await paypal.recordMetric("create_order_failed")
598
+ } catch {
599
+ // Audit/metric writes are best-effort.
600
+ }
601
+ const rawMessage = e?.message || ""
602
+ const isCurrencyError =
603
+ rawMessage.includes("PayPal does not support currency") ||
604
+ rawMessage.includes("PayPal is configured for")
605
+ const status = isCurrencyError ? 400 : 500
606
+ const message = isCurrencyError
607
+ ? rawMessage
608
+ : "Failed to create PayPal order"
609
+ return res.status(status).json({ message, request_id: requestId })
610
+ }
611
+ }