@easypayment/medusa-payment-paypal 0.7.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 (268) hide show
  1. package/.medusa/server/src/admin/index.js +1267 -0
  2. package/.medusa/server/src/admin/index.mjs +1268 -0
  3. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts +3 -0
  4. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js +18 -0
  6. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js.map +1 -0
  7. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts +3 -0
  8. package/.medusa/server/src/api/admin/paypal/disconnect/route.d.ts.map +1 -0
  9. package/.medusa/server/src/api/admin/paypal/disconnect/route.js +9 -0
  10. package/.medusa/server/src/api/admin/paypal/disconnect/route.js.map +1 -0
  11. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts +4 -0
  12. package/.medusa/server/src/api/admin/paypal/environment/route.d.ts.map +1 -0
  13. package/.medusa/server/src/api/admin/paypal/environment/route.js +23 -0
  14. package/.medusa/server/src/api/admin/paypal/environment/route.js.map +1 -0
  15. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +4 -0
  16. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -0
  17. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +31 -0
  18. package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -0
  19. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts +4 -0
  20. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.d.ts.map +1 -0
  21. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js +35 -0
  22. package/.medusa/server/src/api/admin/paypal/onboarding-link/route.js.map +1 -0
  23. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts +3 -0
  24. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.d.ts.map +1 -0
  25. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js +19 -0
  26. package/.medusa/server/src/api/admin/paypal/onboarding-status/route.js.map +1 -0
  27. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts +3 -0
  28. package/.medusa/server/src/api/admin/paypal/save-credentials/route.d.ts.map +1 -0
  29. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js +17 -0
  30. package/.medusa/server/src/api/admin/paypal/save-credentials/route.js.map +1 -0
  31. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts +4 -0
  32. package/.medusa/server/src/api/admin/paypal/settings/route.d.ts.map +1 -0
  33. package/.medusa/server/src/api/admin/paypal/settings/route.js +14 -0
  34. package/.medusa/server/src/api/admin/paypal/settings/route.js.map +1 -0
  35. package/.medusa/server/src/api/admin/paypal/status/route.d.ts +3 -0
  36. package/.medusa/server/src/api/admin/paypal/status/route.d.ts.map +1 -0
  37. package/.medusa/server/src/api/admin/paypal/status/route.js +11 -0
  38. package/.medusa/server/src/api/admin/paypal/status/route.js.map +1 -0
  39. package/.medusa/server/src/api/middlewares.d.ts +3 -0
  40. package/.medusa/server/src/api/middlewares.d.ts.map +1 -0
  41. package/.medusa/server/src/api/middlewares.js +16 -0
  42. package/.medusa/server/src/api/middlewares.js.map +1 -0
  43. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts +3 -0
  44. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -0
  45. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js +43 -0
  46. package/.medusa/server/src/api/store/payment-collections/[id]/payment-sessions/route.js.map +1 -0
  47. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts +3 -0
  48. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -0
  49. package/.medusa/server/src/api/store/paypal/capture-order/route.js +204 -0
  50. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -0
  51. package/.medusa/server/src/api/store/paypal/config/route.d.ts +3 -0
  52. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -0
  53. package/.medusa/server/src/api/store/paypal/config/route.js +77 -0
  54. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -0
  55. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +3 -0
  56. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -0
  57. package/.medusa/server/src/api/store/paypal/create-order/route.js +361 -0
  58. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -0
  59. package/.medusa/server/src/api/store/paypal/settings/route.d.ts +3 -0
  60. package/.medusa/server/src/api/store/paypal/settings/route.d.ts.map +1 -0
  61. package/.medusa/server/src/api/store/paypal/settings/route.js +20 -0
  62. package/.medusa/server/src/api/store/paypal/settings/route.js.map +1 -0
  63. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts +3 -0
  64. package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -0
  65. package/.medusa/server/src/api/store/paypal/webhook/route.js +250 -0
  66. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -0
  67. package/.medusa/server/src/api/store/paypal-complete/route.d.ts +3 -0
  68. package/.medusa/server/src/api/store/paypal-complete/route.d.ts.map +1 -0
  69. package/.medusa/server/src/api/store/paypal-complete/route.js +76 -0
  70. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -0
  71. package/.medusa/server/src/index.d.ts +2 -0
  72. package/.medusa/server/src/index.d.ts.map +1 -0
  73. package/.medusa/server/src/index.js +9 -0
  74. package/.medusa/server/src/index.js.map +1 -0
  75. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts +7 -0
  76. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -0
  77. package/.medusa/server/src/jobs/paypal-webhook-retry.js +132 -0
  78. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -0
  79. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts +15 -0
  80. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts.map +1 -0
  81. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js +67 -0
  82. package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js.map +1 -0
  83. package/.medusa/server/src/modules/paypal/index.d.ts +64 -0
  84. package/.medusa/server/src/modules/paypal/index.d.ts.map +1 -0
  85. package/.medusa/server/src/modules/paypal/index.js +13 -0
  86. package/.medusa/server/src/modules/paypal/index.js.map +1 -0
  87. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.d.ts +6 -0
  88. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.d.ts.map +1 -0
  89. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js +36 -0
  90. package/.medusa/server/src/modules/paypal/migrations/20260115120000_create_paypal_connection.js.map +1 -0
  91. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.d.ts +6 -0
  92. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.d.ts.map +1 -0
  93. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js +25 -0
  94. package/.medusa/server/src/modules/paypal/migrations/20260123090000_create_paypal_settings.js.map +1 -0
  95. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.d.ts +6 -0
  96. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.d.ts.map +1 -0
  97. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js +32 -0
  98. package/.medusa/server/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.js.map +1 -0
  99. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.d.ts +6 -0
  100. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.d.ts.map +1 -0
  101. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js +30 -0
  102. package/.medusa/server/src/modules/paypal/migrations/20260401090000_create_paypal_metric.js.map +1 -0
  103. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.d.ts +6 -0
  104. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.d.ts.map +1 -0
  105. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js +34 -0
  106. package/.medusa/server/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.js.map +1 -0
  107. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.d.ts +6 -0
  108. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.d.ts.map +1 -0
  109. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js +28 -0
  110. package/.medusa/server/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.js.map +1 -0
  111. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.d.ts +6 -0
  112. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.d.ts.map +1 -0
  113. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js +29 -0
  114. package/.medusa/server/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.js.map +1 -0
  115. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts +6 -0
  116. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.d.ts.map +1 -0
  117. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js +14 -0
  118. package/.medusa/server/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.js.map +1 -0
  119. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts +6 -0
  120. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.d.ts.map +1 -0
  121. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js +14 -0
  122. package/.medusa/server/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.js.map +1 -0
  123. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts +6 -0
  124. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.d.ts.map +1 -0
  125. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js +14 -0
  126. package/.medusa/server/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.js.map +1 -0
  127. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.d.ts +6 -0
  128. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.d.ts.map +1 -0
  129. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js +20 -0
  130. package/.medusa/server/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.js.map +1 -0
  131. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts +16 -0
  132. package/.medusa/server/src/modules/paypal/models/paypal_connection.d.ts.map +1 -0
  133. package/.medusa/server/src/modules/paypal/models/paypal_connection.js +19 -0
  134. package/.medusa/server/src/modules/paypal/models/paypal_connection.js.map +1 -0
  135. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts +7 -0
  136. package/.medusa/server/src/modules/paypal/models/paypal_metric.d.ts.map +1 -0
  137. package/.medusa/server/src/modules/paypal/models/paypal_metric.js +10 -0
  138. package/.medusa/server/src/modules/paypal/models/paypal_metric.js.map +1 -0
  139. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts +6 -0
  140. package/.medusa/server/src/modules/paypal/models/paypal_settings.d.ts.map +1 -0
  141. package/.medusa/server/src/modules/paypal/models/paypal_settings.js +9 -0
  142. package/.medusa/server/src/modules/paypal/models/paypal_settings.js.map +1 -0
  143. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts +17 -0
  144. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts.map +1 -0
  145. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js +20 -0
  146. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js.map +1 -0
  147. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +32 -0
  148. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -0
  149. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +625 -0
  150. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -0
  151. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts +6 -0
  152. package/.medusa/server/src/modules/paypal/payment-provider/index.d.ts.map +1 -0
  153. package/.medusa/server/src/modules/paypal/payment-provider/index.js +18 -0
  154. package/.medusa/server/src/modules/paypal/payment-provider/index.js.map +1 -0
  155. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +39 -0
  156. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -0
  157. package/.medusa/server/src/modules/paypal/payment-provider/service.js +869 -0
  158. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -0
  159. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.d.ts +3 -0
  160. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.d.ts.map +1 -0
  161. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.js +74 -0
  162. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.js.map +1 -0
  163. package/.medusa/server/src/modules/paypal/service.d.ts +266 -0
  164. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -0
  165. package/.medusa/server/src/modules/paypal/service.js +1149 -0
  166. package/.medusa/server/src/modules/paypal/service.js.map +1 -0
  167. package/.medusa/server/src/modules/paypal/types/config.d.ts +12 -0
  168. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -0
  169. package/.medusa/server/src/modules/paypal/types/config.js +24 -0
  170. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -0
  171. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +3 -0
  172. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -0
  173. package/.medusa/server/src/modules/paypal/utils/amounts.js +40 -0
  174. package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -0
  175. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts +19 -0
  176. package/.medusa/server/src/modules/paypal/utils/currencies.d.ts.map +1 -0
  177. package/.medusa/server/src/modules/paypal/utils/currencies.js +69 -0
  178. package/.medusa/server/src/modules/paypal/utils/currencies.js.map +1 -0
  179. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts +10 -0
  180. package/.medusa/server/src/modules/paypal/utils/paypal-auth.d.ts.map +1 -0
  181. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js +30 -0
  182. package/.medusa/server/src/modules/paypal/utils/paypal-auth.js.map +1 -0
  183. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts +5 -0
  184. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -0
  185. package/.medusa/server/src/modules/paypal/utils/provider-ids.js +16 -0
  186. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -0
  187. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +29 -0
  188. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -0
  189. package/.medusa/server/src/modules/paypal/webhook-processor.js +267 -0
  190. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -0
  191. package/.medusa/server/src/providers/paypal/index.d.ts +5 -0
  192. package/.medusa/server/src/providers/paypal/index.d.ts.map +1 -0
  193. package/.medusa/server/src/providers/paypal/index.js +10 -0
  194. package/.medusa/server/src/providers/paypal/index.js.map +1 -0
  195. package/.medusa/server/src/providers/paypal_card/index.d.ts +5 -0
  196. package/.medusa/server/src/providers/paypal_card/index.d.ts.map +1 -0
  197. package/.medusa/server/src/providers/paypal_card/index.js +10 -0
  198. package/.medusa/server/src/providers/paypal_card/index.js.map +1 -0
  199. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts +6 -0
  200. package/.medusa/server/src/subscribers/paypal-order-invoice.d.ts.map +1 -0
  201. package/.medusa/server/src/subscribers/paypal-order-invoice.js +124 -0
  202. package/.medusa/server/src/subscribers/paypal-order-invoice.js.map +1 -0
  203. package/LICENSE +21 -0
  204. package/README.md +172 -0
  205. package/package.json +80 -0
  206. package/src/admin/index.ts +7 -0
  207. package/src/admin/routes/settings/paypal/_components/Tabs.tsx +48 -0
  208. package/src/admin/routes/settings/paypal/_components/Toast.tsx +51 -0
  209. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +199 -0
  210. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +183 -0
  211. package/src/admin/routes/settings/paypal/apple-pay/page.tsx +5 -0
  212. package/src/admin/routes/settings/paypal/connection/page.tsx +699 -0
  213. package/src/admin/routes/settings/paypal/google-pay/page.tsx +5 -0
  214. package/src/admin/routes/settings/paypal/page.tsx +13 -0
  215. package/src/admin/routes/settings/paypal/pay-later-messaging/page.tsx +5 -0
  216. package/src/admin/routes/settings/paypal/paypal-settings/page.tsx +351 -0
  217. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +24 -0
  218. package/src/api/admin/paypal/disconnect/route.ts +8 -0
  219. package/src/api/admin/paypal/environment/route.ts +25 -0
  220. package/src/api/admin/paypal/onboard-complete/route.ts +34 -0
  221. package/src/api/admin/paypal/onboarding-link/route.ts +45 -0
  222. package/src/api/admin/paypal/onboarding-status/route.ts +17 -0
  223. package/src/api/admin/paypal/save-credentials/route.ts +22 -0
  224. package/src/api/admin/paypal/settings/route.ts +14 -0
  225. package/src/api/admin/paypal/status/route.ts +12 -0
  226. package/src/api/middlewares.ts +14 -0
  227. package/src/api/store/payment-collections/[id]/payment-sessions/route.ts +56 -0
  228. package/src/api/store/paypal/capture-order/route.ts +265 -0
  229. package/src/api/store/paypal/config/route.ts +100 -0
  230. package/src/api/store/paypal/create-order/route.ts +449 -0
  231. package/src/api/store/paypal/settings/route.ts +19 -0
  232. package/src/api/store/paypal/webhook/route.ts +325 -0
  233. package/src/api/store/paypal-complete/route.ts +95 -0
  234. package/src/index.ts +1 -0
  235. package/src/jobs/paypal-webhook-retry.ts +149 -0
  236. package/src/modules/paypal/clients/paypal-seller.client.ts +62 -0
  237. package/src/modules/paypal/index.ts +8 -0
  238. package/src/modules/paypal/migrations/20260115120000_create_paypal_connection.ts +33 -0
  239. package/src/modules/paypal/migrations/20260123090000_create_paypal_settings.ts +22 -0
  240. package/src/modules/paypal/migrations/20260201090000_create_paypal_webhook_event.ts +29 -0
  241. package/src/modules/paypal/migrations/20260401090000_create_paypal_metric.ts +27 -0
  242. package/src/modules/paypal/migrations/20260701090000_add_paypal_webhook_event_processing.ts +31 -0
  243. package/src/modules/paypal/migrations/20261101090000_remove_paypal_reconciliation_status.ts +25 -0
  244. package/src/modules/paypal/migrations/20261201090000_remove_paypal_audit_log.ts +26 -0
  245. package/src/modules/paypal/migrations/20270101090000_set_paypal_environment_default_live.ts +11 -0
  246. package/src/modules/paypal/migrations/20270102090000_add_paypal_seller_email.ts +11 -0
  247. package/src/modules/paypal/migrations/20270103090000_add_paypal_seller_merchant_id.ts +11 -0
  248. package/src/modules/paypal/migrations/20270201000000_add_webhook_dead_letter.ts +17 -0
  249. package/src/modules/paypal/models/paypal_connection.ts +23 -0
  250. package/src/modules/paypal/models/paypal_metric.ts +9 -0
  251. package/src/modules/paypal/models/paypal_settings.ts +8 -0
  252. package/src/modules/paypal/models/paypal_webhook_event.ts +19 -0
  253. package/src/modules/paypal/payment-provider/README.md +22 -0
  254. package/src/modules/paypal/payment-provider/card-service.ts +767 -0
  255. package/src/modules/paypal/payment-provider/index.ts +15 -0
  256. package/src/modules/paypal/payment-provider/service.ts +1039 -0
  257. package/src/modules/paypal/payment-provider/webhook-utils.ts +88 -0
  258. package/src/modules/paypal/service.ts +1416 -0
  259. package/src/modules/paypal/types/config.ts +33 -0
  260. package/src/modules/paypal/utils/amounts.ts +41 -0
  261. package/src/modules/paypal/utils/currencies.ts +84 -0
  262. package/src/modules/paypal/utils/paypal-auth.ts +31 -0
  263. package/src/modules/paypal/utils/provider-ids.ts +15 -0
  264. package/src/modules/paypal/webhook-processor.ts +363 -0
  265. package/src/providers/paypal/index.ts +8 -0
  266. package/src/providers/paypal_card/index.ts +8 -0
  267. package/src/subscribers/paypal-order-invoice.ts +171 -0
  268. package/tsconfig.json +31 -0
@@ -0,0 +1,869 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PayPalPaymentProvider = void 0;
4
+ const utils_1 = require("@medusajs/framework/utils");
5
+ const crypto_1 = require("crypto");
6
+ const amounts_1 = require("../utils/amounts");
7
+ const currencies_1 = require("../utils/currencies");
8
+ const webhook_utils_1 = require("./webhook-utils");
9
+ const BN_CODE = "MBJTechnolabs_SI_SPB";
10
+ function generateSessionId() {
11
+ try {
12
+ return (0, crypto_1.randomUUID)();
13
+ }
14
+ catch {
15
+ return `pp_${Date.now()}_${Math.random().toString(16).slice(2)}`;
16
+ }
17
+ }
18
+ class PayPalPaymentProvider extends utils_1.AbstractPaymentProvider {
19
+ static identifier = "paypal";
20
+ options_;
21
+ constructor(cradle, options) {
22
+ super(cradle, options);
23
+ this.options_ = options;
24
+ }
25
+ resolvePayPalService() {
26
+ const container = this.container;
27
+ try {
28
+ return container.resolve("paypal_onboarding");
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ async resolveSettings() {
35
+ const paypal = this.resolvePayPalService();
36
+ if (!paypal) {
37
+ try {
38
+ const { Pool: _SettingsPool } = require("pg");
39
+ const _sPool = new _SettingsPool({ connectionString: process.env.DATABASE_URL });
40
+ const _sResult = await _sPool
41
+ .query("SELECT data FROM paypal_settings ORDER BY created_at DESC LIMIT 1")
42
+ .finally(() => _sPool.end());
43
+ const _sData = _sResult.rows[0]?.data || {};
44
+ return {
45
+ additionalSettings: (_sData.additional_settings || {}),
46
+ apiDetails: (_sData.api_details || {}),
47
+ };
48
+ }
49
+ catch {
50
+ return {
51
+ additionalSettings: {},
52
+ apiDetails: {},
53
+ };
54
+ }
55
+ }
56
+ const settings = await paypal.getSettings().catch(() => ({}));
57
+ const data = settings && typeof settings === "object" && "data" in settings
58
+ ? (settings.data ?? {})
59
+ : {};
60
+ return {
61
+ additionalSettings: (data.additional_settings || {}),
62
+ apiDetails: (data.api_details || {}),
63
+ };
64
+ }
65
+ async resolveCurrencyOverride() {
66
+ const { apiDetails } = await this.resolveSettings();
67
+ if (typeof apiDetails.currency_code === "string" && apiDetails.currency_code.trim()) {
68
+ return (0, currencies_1.normalizeCurrencyCode)(apiDetails.currency_code);
69
+ }
70
+ return (0, currencies_1.normalizeCurrencyCode)(process.env.PAYPAL_CURRENCY || "EUR");
71
+ }
72
+ async getPayPalAccessToken() {
73
+ const paypal = this.resolvePayPalService();
74
+ if (!paypal) {
75
+ const { Pool: _FbPool } = require("pg");
76
+ const _fbPool = new _FbPool({ connectionString: process.env.DATABASE_URL });
77
+ const _fbResult = await _fbPool
78
+ .query("SELECT metadata, environment, seller_client_id, seller_client_secret FROM paypal_connection WHERE status='connected' ORDER BY created_at DESC LIMIT 1")
79
+ .finally(() => _fbPool.end());
80
+ const _fbRow = _fbResult.rows[0];
81
+ if (!_fbRow)
82
+ throw new Error("No active PayPal connection found in DB");
83
+ const _fbEnv = _fbRow.environment || "sandbox";
84
+ const _fbCreds = (_fbRow.metadata && _fbRow.metadata.credentials && _fbRow.metadata.credentials[_fbEnv]) || {};
85
+ const _fbId = _fbCreds.client_id || _fbRow.seller_client_id;
86
+ const _fbSec = _fbCreds.client_secret || _fbRow.seller_client_secret;
87
+ const _fbBase = _fbEnv === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com";
88
+ const _fbAuth = Buffer.from(`${_fbId}:${_fbSec}`).toString("base64");
89
+ const _fbResp = await fetch(`${_fbBase}/v1/oauth2/token`, {
90
+ method: "POST",
91
+ headers: {
92
+ Authorization: `Basic ${_fbAuth}`,
93
+ "Content-Type": "application/x-www-form-urlencoded",
94
+ "PayPal-Partner-Attribution-Id": BN_CODE,
95
+ },
96
+ body: "grant_type=client_credentials",
97
+ });
98
+ const _fbText = await _fbResp.text();
99
+ if (!_fbResp.ok)
100
+ throw new Error(`PayPal token error (${_fbResp.status}): ${_fbText}`);
101
+ const _fbJson = JSON.parse(_fbText);
102
+ return { accessToken: String(_fbJson.access_token), base: _fbBase };
103
+ }
104
+ const creds = await paypal.getActiveCredentials();
105
+ const base = creds.environment === "live"
106
+ ? "https://api-m.paypal.com"
107
+ : "https://api-m.sandbox.paypal.com";
108
+ const auth = Buffer.from(`${creds.client_id}:${creds.client_secret}`).toString("base64");
109
+ const resp = await fetch(`${base}/v1/oauth2/token`, {
110
+ method: "POST",
111
+ headers: {
112
+ Authorization: `Basic ${auth}`,
113
+ "Content-Type": "application/x-www-form-urlencoded",
114
+ "PayPal-Partner-Attribution-Id": BN_CODE,
115
+ },
116
+ body: "grant_type=client_credentials",
117
+ });
118
+ const text = await resp.text();
119
+ if (!resp.ok) {
120
+ throw new Error(`PayPal token error (${resp.status}): ${text}`);
121
+ }
122
+ const json = JSON.parse(text);
123
+ return { accessToken: String(json.access_token), base };
124
+ }
125
+ async getOrderDetails(orderId) {
126
+ const { accessToken, base } = await this.getPayPalAccessToken();
127
+ const resp = await fetch(`${base}/v2/checkout/orders/${orderId}`, {
128
+ method: "GET",
129
+ headers: {
130
+ Authorization: `Bearer ${accessToken}`,
131
+ "Content-Type": "application/json",
132
+ "PayPal-Partner-Attribution-Id": BN_CODE,
133
+ },
134
+ });
135
+ const text = await resp.text();
136
+ if (!resp.ok) {
137
+ throw new Error(`PayPal get order error (${resp.status}): ${text}`);
138
+ }
139
+ return JSON.parse(text);
140
+ }
141
+ getIdempotencyKey(input, suffix) {
142
+ const key = input?.context?.idempotency_key?.trim();
143
+ if (key) {
144
+ return `${key}-${suffix}`;
145
+ }
146
+ return `pp-${suffix}-${generateSessionId()}`;
147
+ }
148
+ async normalizePaymentData(input) {
149
+ const data = (input.data || {});
150
+ const amount = Number(data.amount ?? 0);
151
+ const currencyOverride = await this.resolveCurrencyOverride();
152
+ const currencyCode = (0, currencies_1.normalizeCurrencyCode)(data.currency_code || currencyOverride || "EUR");
153
+ (0, currencies_1.assertPayPalCurrencySupported)({
154
+ currencyCode,
155
+ paypalCurrencyOverride: currencyOverride,
156
+ });
157
+ return { data, amount, currencyCode };
158
+ }
159
+ mapCaptureStatus(status) {
160
+ const normalized = String(status || "").toUpperCase();
161
+ if (!normalized)
162
+ return null;
163
+ if (normalized === "COMPLETED")
164
+ return "captured";
165
+ if (normalized === "PENDING")
166
+ return "pending";
167
+ if (["DENIED", "DECLINED", "FAILED"].includes(normalized))
168
+ return "error";
169
+ if (["REFUNDED", "PARTIALLY_REFUNDED", "REVERSED"].includes(normalized))
170
+ return "canceled";
171
+ return null;
172
+ }
173
+ mapAuthorizationStatus(status) {
174
+ const normalized = String(status || "").toUpperCase();
175
+ if (!normalized)
176
+ return null;
177
+ if (["CREATED", "APPROVED", "PENDING"].includes(normalized))
178
+ return "authorized";
179
+ if (["VOIDED", "EXPIRED"].includes(normalized))
180
+ return "canceled";
181
+ if (["DENIED", "DECLINED", "FAILED"].includes(normalized))
182
+ return "error";
183
+ return null;
184
+ }
185
+ serializeError(error) {
186
+ if (error instanceof Error) {
187
+ const errorWithCause = error;
188
+ const cause = errorWithCause.cause;
189
+ return {
190
+ name: error.name,
191
+ message: error.message,
192
+ stack: error.stack,
193
+ cause: cause instanceof Error
194
+ ? { name: cause.name, message: cause.message, stack: cause.stack }
195
+ : cause,
196
+ };
197
+ }
198
+ return { message: String(error) };
199
+ }
200
+ mapOrderStatus(status) {
201
+ const normalized = String(status || "").toUpperCase();
202
+ if (!normalized)
203
+ return "pending";
204
+ if (normalized === "COMPLETED")
205
+ return "captured";
206
+ if (normalized === "APPROVED")
207
+ return "authorized";
208
+ if (["VOIDED", "CANCELLED"].includes(normalized))
209
+ return "canceled";
210
+ if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized))
211
+ return "pending";
212
+ if (["FAILED", "EXPIRED"].includes(normalized))
213
+ return "error";
214
+ return "pending";
215
+ }
216
+ async recordFailure(eventType, metadata) {
217
+ const paypal = this.resolvePayPalService();
218
+ if (!paypal)
219
+ return;
220
+ try {
221
+ await paypal.recordPaymentLog(eventType, metadata);
222
+ await paypal.recordAuditEvent(eventType, metadata);
223
+ await paypal.recordMetric(eventType);
224
+ }
225
+ catch {
226
+ }
227
+ }
228
+ async recordSuccess(metricName) {
229
+ const paypal = this.resolvePayPalService();
230
+ if (!paypal)
231
+ return;
232
+ try {
233
+ await paypal.recordMetric(metricName);
234
+ }
235
+ catch {
236
+ }
237
+ }
238
+ async recordPaymentEvent(eventType, metadata) {
239
+ const paypal = this.resolvePayPalService();
240
+ if (!paypal)
241
+ return;
242
+ try {
243
+ await paypal.recordPaymentLog(eventType, metadata);
244
+ }
245
+ catch {
246
+ }
247
+ }
248
+ async createAccountHolder(input) {
249
+ const customerId = input.context?.customer?.id;
250
+ const externalId = customerId ? `paypal_${customerId}` : `paypal_${generateSessionId()}`;
251
+ return {
252
+ id: externalId,
253
+ data: {
254
+ email: input.context?.customer?.email || null,
255
+ customer_id: customerId || null,
256
+ },
257
+ };
258
+ }
259
+ async initiatePayment(input) {
260
+ const providerId = input.data?.provider_id;
261
+ try {
262
+ const currencyOverride = await this.resolveCurrencyOverride();
263
+ const currencyCode = (0, currencies_1.normalizeCurrencyCode)(input.currency_code || currencyOverride || "EUR");
264
+ (0, currencies_1.assertPayPalCurrencySupported)({
265
+ currencyCode,
266
+ paypalCurrencyOverride: currencyOverride,
267
+ });
268
+ return {
269
+ id: generateSessionId(),
270
+ data: {
271
+ ...(input.data || {}),
272
+ ...(providerId ? { provider_id: providerId } : {}),
273
+ amount: input.amount,
274
+ currency_code: currencyCode,
275
+ },
276
+ };
277
+ }
278
+ catch (error) {
279
+ await this.recordFailure("initiate_failed", {
280
+ error: this.serializeError(error),
281
+ currency_code: input.currency_code,
282
+ amount: input.amount,
283
+ provider_id: providerId,
284
+ data: input.data ?? null,
285
+ });
286
+ throw error;
287
+ }
288
+ }
289
+ async updatePayment(input) {
290
+ const currencyOverride = await this.resolveCurrencyOverride();
291
+ const currencyCode = (0, currencies_1.normalizeCurrencyCode)(input.currency_code || currencyOverride || "EUR");
292
+ (0, currencies_1.assertPayPalCurrencySupported)({
293
+ currencyCode,
294
+ paypalCurrencyOverride: currencyOverride,
295
+ });
296
+ const providerId = input.data?.provider_id;
297
+ return {
298
+ data: {
299
+ ...(input.data || {}),
300
+ ...(providerId ? { provider_id: providerId } : {}),
301
+ amount: input.amount,
302
+ currency_code: currencyCode,
303
+ },
304
+ };
305
+ }
306
+ async authorizePayment(input) {
307
+ const { data, amount, currencyCode } = await this.normalizePaymentData(input);
308
+ const existingPayPal = (data.paypal || {});
309
+ const { additionalSettings } = await this.resolveSettings();
310
+ const paymentActionRaw = typeof additionalSettings.paymentAction === "string"
311
+ ? additionalSettings.paymentAction
312
+ : "capture";
313
+ const returnStatus = paymentActionRaw === "authorize" ? "authorized" : "captured";
314
+ const timestampKey = paymentActionRaw === "authorize" ? "authorized_at" : "captured_at";
315
+ if (existingPayPal.capture_id ||
316
+ existingPayPal.authorization_id ||
317
+ data.authorized_at ||
318
+ data.captured_at) {
319
+ console.info("[PayPal] authorizePayment: session already processed, returning", returnStatus);
320
+ return {
321
+ status: returnStatus,
322
+ data: {
323
+ ...(input.data || {}),
324
+ [timestampKey]: data[timestampKey] || new Date().toISOString(),
325
+ },
326
+ };
327
+ }
328
+ const orderId = String(existingPayPal.order_id || data.order_id || "");
329
+ if (orderId) {
330
+ try {
331
+ console.info("[PayPal] authorizePayment: fetching live order status for", orderId);
332
+ const order = await this.getOrderDetails(orderId);
333
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0];
334
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0];
335
+ if (capture?.id || authorization?.id) {
336
+ console.info("[PayPal] authorizePayment: order already processed by PayPal, returning", returnStatus);
337
+ return {
338
+ status: returnStatus,
339
+ data: {
340
+ ...(input.data || {}),
341
+ paypal: {
342
+ ...existingPayPal,
343
+ order_id: orderId,
344
+ order,
345
+ authorization_id: authorization?.id || existingPayPal.authorization_id,
346
+ capture_id: capture?.id || existingPayPal.capture_id,
347
+ },
348
+ [timestampKey]: new Date().toISOString(),
349
+ },
350
+ };
351
+ }
352
+ if (["APPROVED", "CREATED", "SAVED"].includes(String(order?.status || "").toUpperCase())) {
353
+ console.info("[PayPal] authorizePayment: order approved, marking authorized");
354
+ return {
355
+ status: "authorized",
356
+ data: {
357
+ ...(input.data || {}),
358
+ paypal: {
359
+ ...existingPayPal,
360
+ order_id: orderId,
361
+ order,
362
+ },
363
+ authorized_at: new Date().toISOString(),
364
+ },
365
+ };
366
+ }
367
+ }
368
+ catch (e) {
369
+ console.warn("[PayPal] authorizePayment: order lookup failed:", e?.message);
370
+ }
371
+ }
372
+ const requestId = this.getIdempotencyKey(input, "authorize");
373
+ let debugId = null;
374
+ const orderIntent = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE";
375
+ try {
376
+ const { accessToken, base } = await this.getPayPalAccessToken();
377
+ const value = (0, amounts_1.formatAmountForPayPal)(amount, currencyCode || "EUR");
378
+ const orderPayload = {
379
+ intent: orderIntent,
380
+ purchase_units: [
381
+ {
382
+ reference_id: data.cart_id || data.payment_collection_id || undefined,
383
+ custom_id: data.session_id || data.cart_id || data.payment_collection_id || undefined,
384
+ amount: {
385
+ currency_code: currencyCode || "EUR",
386
+ value,
387
+ },
388
+ },
389
+ ],
390
+ custom_id: data.session_id || data.cart_id || data.payment_collection_id || undefined,
391
+ };
392
+ const ppResp = await fetch(`${base}/v2/checkout/orders`, {
393
+ method: "POST",
394
+ headers: {
395
+ Authorization: `Bearer ${accessToken}`,
396
+ "Content-Type": "application/json",
397
+ "PayPal-Request-Id": requestId,
398
+ "PayPal-Partner-Attribution-Id": BN_CODE,
399
+ },
400
+ body: JSON.stringify(orderPayload),
401
+ });
402
+ const ppText = await ppResp.text();
403
+ debugId = ppResp.headers.get("paypal-debug-id");
404
+ if (!ppResp.ok) {
405
+ throw new Error(`PayPal create order error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`);
406
+ }
407
+ const order = JSON.parse(ppText);
408
+ const newOrderId = String(order.id || "");
409
+ if (!order || !newOrderId) {
410
+ throw new Error("Unable to resolve PayPal order details for authorization.");
411
+ }
412
+ const existingAuthorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0] || null;
413
+ let authorization = null;
414
+ if (existingAuthorization) {
415
+ authorization = order;
416
+ }
417
+ else {
418
+ const authorizeResp = await fetch(`${base}/v2/checkout/orders/${newOrderId}/authorize`, {
419
+ method: "POST",
420
+ headers: {
421
+ Authorization: `Bearer ${accessToken}`,
422
+ "Content-Type": "application/json",
423
+ "PayPal-Request-Id": `${requestId}-auth`,
424
+ "PayPal-Partner-Attribution-Id": BN_CODE,
425
+ },
426
+ });
427
+ const authorizeText = await authorizeResp.text();
428
+ const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id");
429
+ if (!authorizeResp.ok) {
430
+ throw new Error(`PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""}`);
431
+ }
432
+ authorization = JSON.parse(authorizeText);
433
+ }
434
+ const authorizationId = authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
435
+ existingAuthorization?.id;
436
+ await this.recordSuccess("authorize_success");
437
+ await this.recordPaymentEvent("authorize", {
438
+ order_id: newOrderId,
439
+ authorization_id: authorizationId,
440
+ amount,
441
+ currency_code: currencyCode,
442
+ request_id: requestId,
443
+ });
444
+ return {
445
+ status: "authorized",
446
+ data: {
447
+ ...(input.data || {}),
448
+ paypal: {
449
+ ...(input.data || {}).paypal,
450
+ order_id: newOrderId,
451
+ order: order || authorization,
452
+ authorization_id: authorizationId,
453
+ authorizations: authorization?.purchase_units?.[0]?.payments?.authorizations || [],
454
+ },
455
+ authorized_at: new Date().toISOString(),
456
+ },
457
+ };
458
+ }
459
+ catch (error) {
460
+ await this.recordFailure("authorize_failed", {
461
+ request_id: requestId,
462
+ cart_id: data.cart_id,
463
+ payment_collection_id: data.payment_collection_id,
464
+ debug_id: debugId,
465
+ message: error?.message,
466
+ });
467
+ throw error;
468
+ }
469
+ }
470
+ async retrievePayment(input) {
471
+ const data = (input.data || {});
472
+ const paypalData = (data.paypal || {});
473
+ const orderId = String(paypalData.order_id || data.order_id || "");
474
+ if (!orderId) {
475
+ return { data: { ...(input.data || {}) } };
476
+ }
477
+ const order = await this.getOrderDetails(orderId);
478
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0];
479
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0];
480
+ return {
481
+ data: {
482
+ ...(input.data || {}),
483
+ paypal: {
484
+ ...(input.data || {}).paypal,
485
+ order,
486
+ authorization_id: authorization?.id || paypalData.authorization_id,
487
+ capture_id: capture?.id || paypalData.capture_id,
488
+ },
489
+ },
490
+ };
491
+ }
492
+ async getPaymentStatus(input) {
493
+ const data = (input.data || {});
494
+ const paypalData = (data.paypal || {});
495
+ const orderId = String(paypalData.order_id || data.order_id || "");
496
+ if (!orderId) {
497
+ return { status: "pending", data: { ...(input.data || {}) } };
498
+ }
499
+ try {
500
+ const order = await this.getOrderDetails(orderId);
501
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0];
502
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0];
503
+ const mappedStatus = this.mapCaptureStatus(capture?.status) ||
504
+ this.mapAuthorizationStatus(authorization?.status) ||
505
+ this.mapOrderStatus(order?.status) ||
506
+ "pending";
507
+ await this.recordSuccess("status_success");
508
+ return {
509
+ status: mappedStatus,
510
+ data: {
511
+ ...(input.data || {}),
512
+ paypal: {
513
+ ...(input.data || {}).paypal,
514
+ order,
515
+ authorization_id: authorization?.id || paypalData.authorization_id,
516
+ capture_id: capture?.id || paypalData.capture_id,
517
+ },
518
+ },
519
+ };
520
+ }
521
+ catch (error) {
522
+ await this.recordFailure("status_failed", {
523
+ order_id: orderId,
524
+ message: error?.message,
525
+ });
526
+ throw error;
527
+ }
528
+ }
529
+ async capturePayment(input) {
530
+ const data = (input.data || {});
531
+ const paypalData = (data.paypal || {});
532
+ const orderId = String(paypalData.order_id || data.order_id || "");
533
+ let authorizationId = String(paypalData.authorization_id || data.authorization_id || "");
534
+ if (!orderId) {
535
+ throw new Error("PayPal order_id is required to capture payment");
536
+ }
537
+ if (paypalData.capture_id || paypalData.capture) {
538
+ return {
539
+ data: {
540
+ ...(input.data || {}),
541
+ paypal: {
542
+ ...(input.data || {}).paypal,
543
+ capture_id: paypalData.capture_id,
544
+ capture: paypalData.capture,
545
+ },
546
+ captured_at: new Date().toISOString(),
547
+ },
548
+ };
549
+ }
550
+ const requestId = this.getIdempotencyKey(input, `capture-${orderId}`);
551
+ const { amount, currencyCode } = await this.normalizePaymentData(input);
552
+ let debugId = null;
553
+ try {
554
+ const { accessToken, base } = await this.getPayPalAccessToken();
555
+ const order = await this.getOrderDetails(orderId).catch(() => null);
556
+ const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0];
557
+ if (existingCapture?.id) {
558
+ return {
559
+ data: {
560
+ ...(input.data || {}),
561
+ paypal: {
562
+ ...(input.data || {}).paypal,
563
+ capture_id: existingCapture.id,
564
+ capture: existingCapture,
565
+ },
566
+ captured_at: new Date().toISOString(),
567
+ },
568
+ };
569
+ }
570
+ const resolvedIntent = String(order?.intent || paypalData.order?.intent || data.intent || "").toUpperCase();
571
+ if (!authorizationId && resolvedIntent === "AUTHORIZE") {
572
+ const authorizeResp = await fetch(`${base}/v2/checkout/orders/${orderId}/authorize`, {
573
+ method: "POST",
574
+ headers: {
575
+ Authorization: `Bearer ${accessToken}`,
576
+ "Content-Type": "application/json",
577
+ "PayPal-Request-Id": `${requestId}-auth`,
578
+ "PayPal-Partner-Attribution-Id": BN_CODE,
579
+ },
580
+ });
581
+ const authorizeText = await authorizeResp.text();
582
+ debugId = authorizeResp.headers.get("paypal-debug-id");
583
+ if (!authorizeResp.ok) {
584
+ throw new Error(`PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${debugId ? ` debug_id=${debugId}` : ""}`);
585
+ }
586
+ const authorization = JSON.parse(authorizeText);
587
+ authorizationId =
588
+ authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id;
589
+ }
590
+ const isFinalCapture = paypalData.is_final_capture ??
591
+ data.is_final_capture ??
592
+ data.final_capture ??
593
+ undefined;
594
+ const captureExponent = (0, amounts_1.getCurrencyExponent)(currencyCode || "EUR");
595
+ const capturePayload = amount > 0
596
+ ? {
597
+ amount: {
598
+ currency_code: currencyCode || "EUR",
599
+ value: amount.toFixed(captureExponent),
600
+ },
601
+ ...(typeof isFinalCapture === "boolean"
602
+ ? { is_final_capture: isFinalCapture }
603
+ : {}),
604
+ }
605
+ : {
606
+ ...(typeof isFinalCapture === "boolean"
607
+ ? { is_final_capture: isFinalCapture }
608
+ : {}),
609
+ };
610
+ const captureUrl = authorizationId
611
+ ? `${base}/v2/payments/authorizations/${authorizationId}/capture`
612
+ : `${base}/v2/checkout/orders/${orderId}/capture`;
613
+ const ppResp = await fetch(captureUrl, {
614
+ method: "POST",
615
+ headers: {
616
+ Authorization: `Bearer ${accessToken}`,
617
+ "Content-Type": "application/json",
618
+ "PayPal-Request-Id": requestId,
619
+ "PayPal-Partner-Attribution-Id": BN_CODE,
620
+ },
621
+ body: JSON.stringify(capturePayload),
622
+ });
623
+ const ppText = await ppResp.text();
624
+ debugId = ppResp.headers.get("paypal-debug-id");
625
+ if (!ppResp.ok) {
626
+ throw new Error(`PayPal capture error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`);
627
+ }
628
+ const capture = JSON.parse(ppText);
629
+ const captureId = capture?.id || capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id;
630
+ const existingCaptures = Array.isArray(paypalData.captures) ? paypalData.captures : [];
631
+ const captureEntry = {
632
+ id: captureId,
633
+ status: capture?.status,
634
+ amount: capture?.amount,
635
+ raw: capture,
636
+ };
637
+ await this.recordSuccess("capture_success");
638
+ await this.recordPaymentEvent("capture", {
639
+ order_id: orderId,
640
+ capture_id: captureId,
641
+ authorization_id: authorizationId || undefined,
642
+ amount,
643
+ currency_code: currencyCode,
644
+ request_id: requestId,
645
+ });
646
+ return {
647
+ data: {
648
+ ...(input.data || {}),
649
+ paypal: {
650
+ ...(input.data || {}).paypal,
651
+ order_id: orderId,
652
+ capture_id: captureId,
653
+ capture,
654
+ authorization_id: authorizationId || paypalData.authorization_id,
655
+ captures: [...existingCaptures, captureEntry],
656
+ },
657
+ captured_at: new Date().toISOString(),
658
+ },
659
+ };
660
+ }
661
+ catch (error) {
662
+ await this.recordFailure("capture_failed", {
663
+ order_id: orderId,
664
+ request_id: requestId,
665
+ debug_id: debugId,
666
+ message: error?.message,
667
+ });
668
+ throw error;
669
+ }
670
+ }
671
+ async refundPayment(input) {
672
+ const data = (input.data || {});
673
+ const paypalData = (data.paypal || {});
674
+ const captureId = String(paypalData.capture_id || data.capture_id || "");
675
+ const refundReason = String(paypalData.refund_reason || data.refund_reason || data.reason || "").trim();
676
+ const refundReasonCode = String(paypalData.refund_reason_code || data.refund_reason_code || data.reason_code || "").trim();
677
+ if (!captureId) {
678
+ return {
679
+ data: {
680
+ ...(input.data || {}),
681
+ refunded_at: new Date().toISOString(),
682
+ },
683
+ };
684
+ }
685
+ const requestId = this.getIdempotencyKey(input, `refund-${captureId}`);
686
+ const currencyOverride = await this.resolveCurrencyOverride();
687
+ const currencyCode = (0, currencies_1.normalizeCurrencyCode)(data.currency_code || currencyOverride || "EUR");
688
+ const exponent = currencyCode.toUpperCase() === "JPY" ? 0
689
+ : ["BHD", "JOD", "KWD", "OMR", "TND"].includes(currencyCode.toUpperCase()) ? 3
690
+ : 2;
691
+ const refundAmount = Number(input.amount ?? 0);
692
+ const refundValue = refundAmount > 0 ? refundAmount.toFixed(exponent) : null;
693
+ let debugId = null;
694
+ try {
695
+ const { accessToken, base } = await this.getPayPalAccessToken();
696
+ const refundPayload = refundValue
697
+ ? {
698
+ amount: {
699
+ currency_code: currencyCode || "EUR",
700
+ value: refundValue,
701
+ },
702
+ }
703
+ : {};
704
+ if (refundReason) {
705
+ refundPayload.note_to_payer = refundReason;
706
+ }
707
+ const ppResp = await fetch(`${base}/v2/payments/captures/${captureId}/refund`, {
708
+ method: "POST",
709
+ headers: {
710
+ Authorization: `Bearer ${accessToken}`,
711
+ "Content-Type": "application/json",
712
+ "PayPal-Request-Id": requestId,
713
+ "PayPal-Partner-Attribution-Id": BN_CODE,
714
+ },
715
+ body: JSON.stringify(refundPayload),
716
+ });
717
+ const ppText = await ppResp.text();
718
+ debugId = ppResp.headers.get("paypal-debug-id");
719
+ if (!ppResp.ok) {
720
+ throw new Error(`PayPal refund error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`);
721
+ }
722
+ const refund = JSON.parse(ppText);
723
+ const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : [];
724
+ const refundEntry = {
725
+ id: refund?.id,
726
+ status: refund?.status,
727
+ amount: refund?.amount,
728
+ reason: refundReason || refund?.note_to_payer,
729
+ reason_code: refundReasonCode || refund?.reason_code,
730
+ raw: refund,
731
+ };
732
+ await this.recordSuccess("refund_success");
733
+ await this.recordPaymentEvent("refund", {
734
+ capture_id: captureId,
735
+ refund_id: refund?.id,
736
+ amount: refundAmount,
737
+ currency_code: currencyCode,
738
+ request_id: requestId,
739
+ reason: refundReason,
740
+ reason_code: refundReasonCode,
741
+ });
742
+ return {
743
+ data: {
744
+ ...(input.data || {}),
745
+ paypal: {
746
+ ...(input.data || {}).paypal,
747
+ refund_id: refund?.id,
748
+ refund_status: refund?.status,
749
+ refund_reason: refundReason || refund?.note_to_payer,
750
+ refund_reason_code: refundReasonCode || refund?.reason_code,
751
+ refunds: [...existingRefunds, refundEntry],
752
+ refund,
753
+ },
754
+ refunded_at: new Date().toISOString(),
755
+ },
756
+ };
757
+ }
758
+ catch (error) {
759
+ await this.recordFailure("refund_failed", {
760
+ capture_id: captureId,
761
+ request_id: requestId,
762
+ debug_id: debugId,
763
+ message: error?.message,
764
+ });
765
+ throw error;
766
+ }
767
+ }
768
+ async cancelPayment(input) {
769
+ const data = (input.data || {});
770
+ const paypalData = (data.paypal || {});
771
+ const orderId = String(paypalData.order_id || data.order_id || "");
772
+ const captureId = String(paypalData.capture_id || data.capture_id || "");
773
+ const storedAuthorizationId = String(paypalData.authorization_id || data.authorization_id || "");
774
+ let debugId = null;
775
+ try {
776
+ const order = orderId ? await this.getOrderDetails(orderId) : null;
777
+ const intent = String(order?.intent || "").toUpperCase();
778
+ const authorizationId = order?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
779
+ storedAuthorizationId;
780
+ if (intent === "AUTHORIZE" && authorizationId) {
781
+ const { accessToken, base } = await this.getPayPalAccessToken();
782
+ const requestId = this.getIdempotencyKey(input, `void-${authorizationId}`);
783
+ const resp = await fetch(`${base}/v2/payments/authorizations/${authorizationId}/void`, {
784
+ method: "POST",
785
+ headers: {
786
+ Authorization: `Bearer ${accessToken}`,
787
+ "Content-Type": "application/json",
788
+ "PayPal-Request-Id": requestId,
789
+ "PayPal-Partner-Attribution-Id": BN_CODE,
790
+ },
791
+ });
792
+ if (!resp.ok) {
793
+ const text = await resp.text();
794
+ debugId = resp.headers.get("paypal-debug-id");
795
+ throw new Error(`PayPal void error (${resp.status}): ${text}${debugId ? ` debug_id=${debugId}` : ""}`);
796
+ }
797
+ await this.recordSuccess("void_success");
798
+ await this.recordPaymentEvent("void", {
799
+ order_id: orderId,
800
+ authorization_id: authorizationId,
801
+ });
802
+ }
803
+ else if (captureId) {
804
+ const { accessToken, base } = await this.getPayPalAccessToken();
805
+ const requestId = this.getIdempotencyKey(input, `refund-${captureId}`);
806
+ const resp = await fetch(`${base}/v2/payments/captures/${captureId}/refund`, {
807
+ method: "POST",
808
+ headers: {
809
+ Authorization: `Bearer ${accessToken}`,
810
+ "Content-Type": "application/json",
811
+ "PayPal-Request-Id": requestId,
812
+ "PayPal-Partner-Attribution-Id": BN_CODE,
813
+ },
814
+ body: JSON.stringify({}),
815
+ });
816
+ if (!resp.ok) {
817
+ const text = await resp.text();
818
+ debugId = resp.headers.get("paypal-debug-id");
819
+ throw new Error(`PayPal refund error (${resp.status}): ${text}${debugId ? ` debug_id=${debugId}` : ""}`);
820
+ }
821
+ const refund = await resp.json().catch(() => ({}));
822
+ const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : [];
823
+ const refundEntry = {
824
+ id: refund?.id,
825
+ status: refund?.status,
826
+ amount: refund?.amount,
827
+ raw: refund,
828
+ };
829
+ paypalData.refund_id = refund?.id;
830
+ paypalData.refund_status = refund?.status;
831
+ paypalData.refunds = [...existingRefunds, refundEntry];
832
+ await this.recordSuccess("cancel_refund_success");
833
+ }
834
+ return {
835
+ data: {
836
+ ...(input.data || {}),
837
+ paypal: {
838
+ ...(input.data || {}).paypal,
839
+ order: order || undefined,
840
+ authorization_id: authorizationId || storedAuthorizationId,
841
+ capture_id: captureId || paypalData.capture_id,
842
+ refund_id: paypalData.refund_id,
843
+ refund_status: paypalData.refund_status,
844
+ refunds: paypalData.refunds,
845
+ },
846
+ canceled_at: new Date().toISOString(),
847
+ },
848
+ };
849
+ }
850
+ catch (error) {
851
+ await this.recordFailure("cancel_failed", {
852
+ order_id: orderId,
853
+ capture_id: captureId,
854
+ debug_id: debugId,
855
+ message: error?.message,
856
+ });
857
+ throw error;
858
+ }
859
+ }
860
+ async deletePayment(_input) {
861
+ return { data: {} };
862
+ }
863
+ async getWebhookActionAndData(payload) {
864
+ return (0, webhook_utils_1.getPayPalWebhookActionAndData)(payload);
865
+ }
866
+ }
867
+ exports.PayPalPaymentProvider = PayPalPaymentProvider;
868
+ exports.default = PayPalPaymentProvider;
869
+ //# sourceMappingURL=service.js.map