@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,908 +1,974 @@
1
- import React, {
2
- useCallback,
3
- useEffect,
4
- useLayoutEffect,
5
- useMemo,
6
- useRef,
7
- useState,
8
- } from "react"
9
- import { defineRouteConfig } from "@medusajs/admin-sdk"
10
- import PayPalTabs from "../_components/Tabs"
11
-
12
- export const config = defineRouteConfig({
13
- label: "PayPal Connection",
14
- })
15
-
16
- // Let partner.js own the entire onboarding flow: it opens PayPal's mini-browser
17
- // itself (synchronously inside the click, so no new tab / no popup block), it
18
- // receives PayPal's completion postMessage, and it invokes the callback named in
19
- // `data-paypal-onboard-complete` with (authCode, sharedId). This is PayPal's
20
- // documented integration and matches the official @easypayment WooCommerce
21
- // plugin. Opening the popup ourselves (a previous attempt at fixing the "opens a
22
- // new tab" issue) stopped partner.js from receiving completion, which left the
23
- // popup stranded on PayPal's "isuDone" page and never saved credentials.
24
- const PARTNER_JS_URL =
25
- "https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js"
26
-
27
- declare global {
28
- interface Window {
29
- PAYPAL?: {
30
- apps?: {
31
- Signup?: {
32
- miniBrowser?: { init?: () => void; closeFlow?: () => void }
33
- MiniBrowser?: { init?: () => void; closeFlow?: () => void }
34
- }
35
- }
36
- }
37
- onboardingCallback?: (authCode: string, sharedId: string) => void
38
- }
39
- }
40
-
41
- const SERVICE_URL = "/admin/paypal/onboarding-link"
42
- const CACHE_PREFIX = "pp_onboard_cache"
43
- const CACHE_EXPIRY = 6 * 60 * 60 * 1000 // 6 hours
44
-
45
- const ONBOARDING_COMPLETE_ENDPOINT = "/admin/paypal/onboard-complete"
46
- const STATUS_ENDPOINT = "/admin/paypal/status"
47
- const SAVE_CREDENTIALS_ENDPOINT = "/admin/paypal/save-credentials"
48
- const DISCONNECT_ENDPOINT = "/admin/paypal/disconnect"
49
- const ENVIRONMENT_ENDPOINT = "/admin/paypal/environment"
50
-
51
- type Env = "sandbox" | "live"
52
-
53
- const cacheKeyFor = (env: Env) => `${CACHE_PREFIX}_${env}`
54
-
55
- function readCachedUrl(env: Env): string | null {
56
- if (typeof window === "undefined") return null
57
- try {
58
- const raw = localStorage.getItem(cacheKeyFor(env))
59
- if (!raw) return null
60
- const data = JSON.parse(raw)
61
- if (
62
- data &&
63
- typeof data.url === "string" &&
64
- Date.now() - (Number(data.ts) || 0) < CACHE_EXPIRY
65
- ) {
66
- return data.url
67
- }
68
- } catch {
69
- /* ignore malformed cache */
70
- }
71
- return null
72
- }
73
-
74
- function writeCachedUrl(env: Env, url: string) {
75
- try {
76
- localStorage.setItem(cacheKeyFor(env), JSON.stringify({ url, ts: Date.now() }))
77
- } catch {
78
- /* ignore */
79
- }
80
- }
81
-
82
- function clearCachedUrl(env?: Env) {
83
- try {
84
- if (env) {
85
- localStorage.removeItem(cacheKeyFor(env))
86
- } else {
87
- localStorage.removeItem(cacheKeyFor("sandbox"))
88
- localStorage.removeItem(cacheKeyFor("live"))
89
- }
90
- } catch {
91
- /* ignore */
92
- }
93
- }
94
-
95
- export default function PayPalConnectionPage() {
96
- const [env, setEnv] = useState<Env>("live")
97
- const [envReady, setEnvReady] = useState(false)
98
-
99
- const [connState, setConnState] = useState<
100
- "loading" | "ready" | "connected" | "error"
101
- >("loading")
102
- const [error, setError] = useState<string | null>(null)
103
- const [finalUrl, setFinalUrl] = useState<string>("")
104
- const [showManual, setShowManual] = useState(false)
105
- const [clientId, setClientId] = useState("")
106
- const [secret, setSecret] = useState("")
107
- const [statusInfo, setStatusInfo] = useState<{
108
- seller_client_id_masked?: string | null
109
- seller_client_secret_masked?: string | null
110
- seller_email?: string | null
111
- } | null>(null)
112
-
113
- const [onboardingInProgress, setOnboardingInProgress] = useState(false)
114
-
115
- const initLoaderRef = useRef<HTMLDivElement>(null)
116
- const paypalButtonRef = useRef<HTMLAnchorElement | null>(null)
117
- const errorLogRef = useRef<HTMLDivElement>(null)
118
- const runIdRef = useRef(0)
119
- const currentRunId = useRef(0)
120
- const completedRef = useRef(false)
121
-
122
- // Long-lived listeners/timers read the current env through a ref so they never
123
- // capture a stale value from the render that registered them.
124
- const envRef = useRef<Env>(env)
125
- envRef.current = env
126
-
127
- const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
128
- const pollAttemptsRef = useRef(0)
129
-
130
- const ppBtnMeasureRef = useRef<HTMLAnchorElement | null>(null)
131
- const [ppBtnWidth, setPpBtnWidth] = useState<number | null>(null)
132
-
133
- const canSaveManual = useMemo(() => {
134
- return clientId.trim().length > 0 && secret.trim().length > 0
135
- }, [clientId, secret])
136
-
137
- const showError = useCallback((msg: string) => {
138
- setConnState("error")
139
- setError(msg)
140
- }, [])
141
-
142
- // Close PayPal's mini-browser via partner.js's API (works under both the
143
- // `miniBrowser` and `MiniBrowser` casings PayPal has shipped over time).
144
- const closeMiniBrowser = useCallback(() => {
145
- try {
146
- const close1 = window.PAYPAL?.apps?.Signup?.MiniBrowser?.closeFlow
147
- if (typeof close1 === "function") close1()
148
- } catch {}
149
- try {
150
- const close2 = window.PAYPAL?.apps?.Signup?.miniBrowser?.closeFlow
151
- if (typeof close2 === "function") close2()
152
- } catch {}
153
- }, [])
154
-
155
- const stopStatusPolling = useCallback(() => {
156
- if (pollTimerRef.current) {
157
- clearTimeout(pollTimerRef.current)
158
- pollTimerRef.current = null
159
- }
160
- pollAttemptsRef.current = 0
161
- }, [])
162
-
163
- // Fetch status for an env and, if the seller credentials are present, flip the
164
- // UI to "connected" and close the PayPal popup. Returns true once connected.
165
- const refreshStatusAndMaybeConnect = useCallback(
166
- async (activeEnv: Env): Promise<boolean> => {
167
- try {
168
- const res = await fetch(`${STATUS_ENDPOINT}?environment=${activeEnv}`, {
169
- method: "GET",
170
- credentials: "include",
171
- })
172
- const st = await res.json().catch(() => ({}))
173
- const connected =
174
- st?.status === "connected" && st?.seller_client_id_present === true
175
- if (connected) {
176
- completedRef.current = true
177
- setStatusInfo(st)
178
- setConnState("connected")
179
- setShowManual(false)
180
- setOnboardingInProgress(false)
181
- clearCachedUrl(activeEnv)
182
- closeMiniBrowser()
183
- stopStatusPolling()
184
- }
185
- return connected
186
- } catch {
187
- return false
188
- }
189
- },
190
- [closeMiniBrowser, stopStatusPolling]
191
- )
192
-
193
- // While a connect attempt is in flight, the seller may complete onboarding via
194
- // a path that never reaches the opener (e.g. partner.js fails to fire its
195
- // callback, or the popup's completion message is blocked). The return_url
196
- // bridge still saves credentials server-side, so poll status as the reliable
197
- // fallback: the moment credentials land, this flips to "connected" and closes
198
- // the stranded popup.
199
- const startStatusPolling = useCallback(() => {
200
- stopStatusPolling()
201
- const MAX_ATTEMPTS = 100 // ~5 min at 3s intervals
202
- const tick = async () => {
203
- pollAttemptsRef.current += 1
204
- const connected = await refreshStatusAndMaybeConnect(envRef.current)
205
- if (connected || completedRef.current) return
206
- if (pollAttemptsRef.current >= MAX_ATTEMPTS) {
207
- stopStatusPolling()
208
- return
209
- }
210
- pollTimerRef.current = setTimeout(tick, 3000)
211
- }
212
- pollTimerRef.current = setTimeout(tick, 3000)
213
- }, [refreshStatusAndMaybeConnect, stopStatusPolling])
214
-
215
- // Shared completion: exchange authCode/sharedId for seller credentials, then
216
- // close the popup and refresh status. Invoked by partner.js's onboardingCallback
217
- // and by the return_url bridge's postMessage. Guarded + server-idempotent so
218
- // redundant invocations are harmless.
219
- const completeOnboarding = useCallback(
220
- async (authCode: string, sharedId: string) => {
221
- if (!authCode || !sharedId) return
222
- if (completedRef.current) return
223
- completedRef.current = true
224
-
225
- try {
226
- window.onbeforeunload = null
227
- } catch {}
228
-
229
- const activeEnv: Env = envRef.current === "sandbox" ? "sandbox" : "live"
230
-
231
- setOnboardingInProgress(true)
232
- setConnState("loading")
233
- setError(null)
234
-
235
- try {
236
- const res = await fetch(ONBOARDING_COMPLETE_ENDPOINT, {
237
- method: "POST",
238
- headers: { "content-type": "application/json" },
239
- credentials: "include",
240
- body: JSON.stringify({ authCode, sharedId, env: activeEnv }),
241
- })
242
-
243
- if (!res.ok) {
244
- const txt = await res.text().catch(() => "")
245
- throw new Error(txt || `Onboarding exchange failed (${res.status})`)
246
- }
247
-
248
- closeMiniBrowser()
249
- clearCachedUrl(activeEnv)
250
-
251
- try {
252
- const statusRes = await fetch(
253
- `${STATUS_ENDPOINT}?environment=${activeEnv}`,
254
- { method: "GET", credentials: "include" }
255
- )
256
- const refreshedStatus = await statusRes.json().catch(() => ({}))
257
- setStatusInfo(refreshedStatus || null)
258
- } catch {}
259
-
260
- setConnState("connected")
261
- setShowManual(false)
262
- stopStatusPolling()
263
- } catch (e: any) {
264
- completedRef.current = false
265
- console.error(e)
266
- // The bridge may have already saved credentials server-side; if so the
267
- // poll will surface "connected". Don't strand the user on an error.
268
- setConnState("error")
269
- setError(e?.message || "Exchange failed while saving credentials.")
270
- } finally {
271
- setOnboardingInProgress(false)
272
- }
273
- },
274
- [closeMiniBrowser, stopStatusPolling]
275
- )
276
-
277
- // Bind partner.js to the connect button once it has a real onboarding URL.
278
- const initPartner = useCallback(() => {
279
- const signup = window.PAYPAL?.apps?.Signup
280
- const init =
281
- (signup?.miniBrowser && signup.miniBrowser.init) ||
282
- (signup?.MiniBrowser && signup.MiniBrowser.init)
283
- if (typeof init === "function") {
284
- try {
285
- init()
286
- } catch (e) {
287
- console.error("[paypal] partner.js init failed:", e)
288
- }
289
- }
290
- }, [])
291
-
292
- // Load partner.js once for the lifetime of the page.
293
- useEffect(() => {
294
- const existingScript = document.getElementById("paypal-partner-js")
295
- if (existingScript) return
296
-
297
- const preloadHref = PARTNER_JS_URL
298
- let preloadLink: HTMLLinkElement | null = null
299
- if (!document.head.querySelector(`link[rel="preload"][href="${preloadHref}"]`)) {
300
- preloadLink = document.createElement("link")
301
- preloadLink.rel = "preload"
302
- preloadLink.href = preloadHref
303
- preloadLink.as = "script"
304
- document.head.appendChild(preloadLink)
305
- }
306
-
307
- const ppScript = document.createElement("script")
308
- ppScript.id = "paypal-partner-js"
309
- ppScript.src = preloadHref
310
- ppScript.async = true
311
- document.head.appendChild(ppScript)
312
-
313
- return () => {
314
- if (preloadLink?.parentNode) preloadLink.parentNode.removeChild(preloadLink)
315
- if (ppScript.parentNode) ppScript.parentNode.removeChild(ppScript)
316
- }
317
- }, [])
318
-
319
- // Put the (cached or freshly generated) onboarding URL on the button, then wait
320
- // for partner.js to be present before showing the button + initializing it. The
321
- // button is only revealed once partner.js is ready, which is what guarantees
322
- // the first click opens the mini-browser popup (never a new tab).
323
- const activatePayPal = useCallback(
324
- (url: string, runId: number) => {
325
- if (paypalButtonRef.current) {
326
- paypalButtonRef.current.href = url
327
- }
328
- setFinalUrl(url)
329
-
330
- let attempts = 0
331
- const MAX_ATTEMPTS = 200 // ~10s
332
-
333
- const tryInit = () => {
334
- if (runId !== currentRunId.current) return
335
- if (window.PAYPAL?.apps?.Signup) {
336
- initPartner()
337
- setConnState("ready")
338
- return
339
- }
340
- attempts++
341
- if (attempts >= MAX_ATTEMPTS) {
342
- showError(
343
- "PayPal partner script failed to load. Please refresh and try again."
344
- )
345
- return
346
- }
347
- setTimeout(tryInit, 50)
348
- }
349
-
350
- tryInit()
351
- },
352
- [initPartner, showError]
353
- )
354
-
355
- const fetchFreshLink = useCallback(
356
- async (targetEnv: Env, runId: number) => {
357
- if (initLoaderRef.current) {
358
- const loaderText = initLoaderRef.current.querySelector("#loader-text")
359
- if (loaderText) loaderText.textContent = "Generating onboarding session..."
360
- }
361
-
362
- try {
363
- const res = await fetch(SERVICE_URL, {
364
- method: "POST",
365
- headers: { "content-type": "application/json" },
366
- credentials: "include",
367
- body: JSON.stringify({ products: ["PPCP"], environment: targetEnv }),
368
- })
369
-
370
- const data = await res.json()
371
-
372
- if (!res.ok) {
373
- throw new Error(data?.message || `Service returned ${res.status}`)
374
- }
375
- if (runId !== currentRunId.current) return
376
-
377
- const href = data?.onboarding_url
378
- if (!href) {
379
- showError("Onboarding URL not returned.")
380
- return
381
- }
382
-
383
- const url =
384
- href + (href.includes("?") ? "&" : "?") + "displayMode=minibrowser"
385
-
386
- writeCachedUrl(targetEnv, url)
387
- activatePayPal(url, runId)
388
- } catch (err: any) {
389
- if (runId !== currentRunId.current) return
390
- showError(err?.message || "Unable to connect to service.")
391
- }
392
- },
393
- [activatePayPal, showError]
394
- )
395
-
396
- // Resolve the server environment first.
397
- useEffect(() => {
398
- let alive = true
399
- fetch(ENVIRONMENT_ENDPOINT, { method: "GET", credentials: "include" })
400
- .then((r) => r.json())
401
- .then((d) => {
402
- if (!alive) return
403
- setEnv(d?.environment === "sandbox" ? "sandbox" : "live")
404
- })
405
- .catch(() => {})
406
- .finally(() => {
407
- if (alive) setEnvReady(true)
408
- })
409
- return () => {
410
- alive = false
411
- }
412
- }, [])
413
-
414
- // Page-load flow: connected? -> cached link? -> else generate a fresh link.
415
- useEffect(() => {
416
- if (!envReady) return
417
-
418
- currentRunId.current = ++runIdRef.current
419
- const runId = currentRunId.current
420
-
421
- let cancelled = false
422
- completedRef.current = false
423
-
424
- const run = async () => {
425
- setConnState("loading")
426
- setError(null)
427
- setFinalUrl("")
428
-
429
- try {
430
- const r = await fetch(`${STATUS_ENDPOINT}?environment=${env}`, {
431
- method: "GET",
432
- credentials: "include",
433
- })
434
- const st = await r.json().catch(() => ({}))
435
-
436
- if (cancelled || runId !== currentRunId.current) return
437
-
438
- setStatusInfo(st)
439
-
440
- const isConnected =
441
- st?.status === "connected" && st?.seller_client_id_present === true
442
-
443
- if (isConnected) {
444
- setConnState("connected")
445
- setShowManual(false)
446
- return
447
- }
448
- } catch (e) {
449
- console.error(e)
450
- }
451
-
452
- if (cancelled || runId !== currentRunId.current) return
453
-
454
- const cached = readCachedUrl(env)
455
- if (cached) {
456
- activatePayPal(cached, runId)
457
- return
458
- }
459
-
460
- await fetchFreshLink(env, runId)
461
- }
462
-
463
- run()
464
-
465
- return () => {
466
- cancelled = true
467
- }
468
- }, [env, envReady, fetchFreshLink, activatePayPal])
469
-
470
- // partner.js invokes this by name (data-paypal-onboard-complete) once PayPal
471
- // returns the seller's authCode + sharedId.
472
- useLayoutEffect(() => {
473
- window.onboardingCallback = (authCode: string, sharedId: string) => {
474
- void completeOnboarding(authCode, sharedId)
475
- }
476
-
477
- return () => {
478
- window.onboardingCallback = undefined
479
- }
480
- }, [completeOnboarding])
481
-
482
- // The return_url bridge (/store/paypal/onboard-return), which runs inside the
483
- // popup after PayPal redirects to it, posts its params back here. The bridge has
484
- // already exchanged credentials server-side, so we just refresh status to flip
485
- // to "connected" and close the popup. If for some reason credentials aren't yet
486
- // saved but PayPal forwarded an authCode/sharedId, complete it from here too.
487
- useEffect(() => {
488
- const onMessage = (event: MessageEvent) => {
489
- const data = event?.data as
490
- | { source?: string; params?: Record<string, string> }
491
- | undefined
492
- if (!data || data.source !== "paypal-onboarding-return") return
493
-
494
- const params = data.params || {}
495
- const authCode = params.authCode || params.auth_code
496
- const sharedId = params.sharedId || params.shared_id
497
- const activeEnv = envRef.current
498
-
499
- void (async () => {
500
- const connected = await refreshStatusAndMaybeConnect(activeEnv)
501
- if (!connected && authCode && sharedId) {
502
- await completeOnboarding(authCode, sharedId)
503
- }
504
- })()
505
- }
506
-
507
- window.addEventListener("message", onMessage)
508
- return () => window.removeEventListener("message", onMessage)
509
- }, [completeOnboarding, refreshStatusAndMaybeConnect])
510
-
511
- // Always stop polling when the component unmounts.
512
- useEffect(() => stopStatusPolling, [stopStatusPolling])
513
-
514
- useLayoutEffect(() => {
515
- const el = ppBtnMeasureRef.current
516
- if (!el) return
517
-
518
- const update = () => {
519
- const w = Math.round(el.getBoundingClientRect().width || 0)
520
- if (w > 0) setPpBtnWidth(w)
521
- }
522
-
523
- update()
524
-
525
- let ro: ResizeObserver | null = null
526
- if (typeof ResizeObserver !== "undefined") {
527
- ro = new ResizeObserver(() => update())
528
- ro.observe(el)
529
- } else {
530
- window.addEventListener("resize", update)
531
- }
532
-
533
- return () => {
534
- if (ro) ro.disconnect()
535
- else window.removeEventListener("resize", update)
536
- }
537
- }, [connState, env, finalUrl])
538
-
539
- // Only block the click while we are not ready; when ready, let the native click
540
- // through so partner.js can open the mini-browser. Start polling status so we
541
- // detect completion (and close the popup) even if no completion message reaches
542
- // this page.
543
- const handleConnectClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
544
- if (connState !== "ready" || !finalUrl || onboardingInProgress) {
545
- e.preventDefault()
546
- return
547
- }
548
- completedRef.current = false
549
- startStatusPolling()
550
- }
551
-
552
- const handleSaveManual = async () => {
553
- if (!canSaveManual || onboardingInProgress) return
554
- setOnboardingInProgress(true)
555
- setConnState("loading")
556
- setError(null)
557
-
558
- try {
559
- const res = await fetch(SAVE_CREDENTIALS_ENDPOINT, {
560
- method: "POST",
561
- headers: { "content-type": "application/json" },
562
- credentials: "include",
563
- body: JSON.stringify({
564
- clientId: clientId.trim(),
565
- clientSecret: secret.trim(),
566
- environment: env,
567
- }),
568
- })
569
-
570
- if (!res.ok) {
571
- const txt = await res.text().catch(() => "")
572
- throw new Error(txt || `Save credentials failed (${res.status})`)
573
- }
574
-
575
- const statusRes = await fetch(`${STATUS_ENDPOINT}?environment=${env}`, {
576
- method: "GET",
577
- credentials: "include",
578
- })
579
- const refreshedStatus = await statusRes.json().catch(() => ({}))
580
-
581
- setConnState("connected")
582
- setStatusInfo(refreshedStatus || null)
583
- setShowManual(false)
584
-
585
- clearCachedUrl(env)
586
- } catch (e: any) {
587
- console.error(e)
588
- setConnState("error")
589
- setError(e?.message || "Failed to save credentials.")
590
- } finally {
591
- setOnboardingInProgress(false)
592
- }
593
- }
594
-
595
- const handleDisconnect = async () => {
596
- if (onboardingInProgress) return
597
- if (!window.confirm("Disconnect PayPal for this environment?")) return
598
-
599
- stopStatusPolling()
600
- setOnboardingInProgress(true)
601
- setConnState("loading")
602
- setError(null)
603
- setFinalUrl("")
604
- setShowManual(false)
605
- setStatusInfo(null)
606
-
607
- try {
608
- const res = await fetch(DISCONNECT_ENDPOINT, {
609
- method: "POST",
610
- headers: { "content-type": "application/json" },
611
- credentials: "include",
612
- body: JSON.stringify({ environment: env }),
613
- })
614
-
615
- if (!res.ok) {
616
- const t = await res.text().catch(() => "")
617
- throw new Error(t || `Disconnect failed (${res.status})`)
618
- }
619
-
620
- clearCachedUrl(env)
621
- completedRef.current = false
622
-
623
- currentRunId.current = ++runIdRef.current
624
- await fetchFreshLink(env, currentRunId.current)
625
- } catch (e: any) {
626
- console.error(e)
627
- setConnState("error")
628
- setError(e?.message || "Failed to disconnect.")
629
- } finally {
630
- setOnboardingInProgress(false)
631
- }
632
- }
633
-
634
- const handleEnvChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
635
- const next = e.target.value as Env
636
- if (next === env || onboardingInProgress) return
637
-
638
- stopStatusPolling()
639
- completedRef.current = false
640
- clearCachedUrl()
641
- setConnState("loading")
642
-
643
- try {
644
- await fetch(ENVIRONMENT_ENDPOINT, {
645
- method: "POST",
646
- headers: { "content-type": "application/json" },
647
- credentials: "include",
648
- body: JSON.stringify({ environment: next }),
649
- })
650
- } catch {}
651
-
652
- setEnv(next)
653
- }
654
-
655
- return (
656
- <div className="p-6">
657
- <div className="flex flex-col gap-6">
658
- <div className="flex items-start justify-between gap-4">
659
- <div>
660
- <h1 className="text-xl font-semibold text-ui-fg-base">PayPal Gateway By Easy Payment</h1>
661
- </div>
662
- </div>
663
-
664
- <PayPalTabs />
665
-
666
- <div className="rounded-xl border border-ui-border-base bg-ui-bg-base shadow-sm">
667
- <div className="grid grid-cols-1 gap-y-6 p-4 md:grid-cols-[260px_1fr] md:items-start">
668
- <div className="text-sm font-medium pt-2">Environment</div>
669
- <div className="max-w-xl">
670
- <select
671
- value={env}
672
- onChange={handleEnvChange}
673
- disabled={onboardingInProgress}
674
- className="w-full rounded-md border border-ui-border-base bg-transparent px-3 py-2 text-sm"
675
- >
676
- <option value="sandbox">Sandbox (Test Mode)</option>
677
- <option value="live">Live (Production)</option>
678
- </select>
679
- </div>
680
-
681
- <div className="text-sm font-medium pt-2">
682
- {env === "sandbox" ? "Connect to PayPal (Sandbox)" : "Connect to PayPal"}
683
- </div>
684
-
685
- <div className="max-w-xl">
686
- {connState === "connected" ? (
687
- <div>
688
- <div className="text-sm text-green-600 bg-green-50 p-3 rounded border border-green-200">
689
- ✅ Successfully connected to PayPal!
690
- <a
691
- data-paypal-button="true"
692
- data-paypal-onboard-complete="onboardingCallback"
693
- href="#"
694
- style={{ display: "none" }}
695
- >
696
- PayPal
697
- </a>
698
- </div>
699
- <div className="mt-3 rounded-md border border-ui-border-base bg-ui-bg-subtle p-3 text-xs text-ui-fg-subtle">
700
- <div className="font-medium text-ui-fg-base">
701
- Connected PayPal account
702
- </div>
703
- <div className="mt-1">
704
- Email:{" "}
705
- <span className="font-mono text-ui-fg-base">
706
- {statusInfo?.seller_email || "Unavailable"}
707
- </span>
708
- </div>
709
- </div>
710
- <div className="mt-3 flex items-center gap-2">
711
- <button
712
- type="button"
713
- onClick={handleDisconnect}
714
- disabled={onboardingInProgress}
715
- className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
716
- >
717
- Disconnect
718
- </button>
719
- </div>
720
- </div>
721
- ) : (
722
- <>
723
- <div
724
- ref={initLoaderRef}
725
- id="init-loader"
726
- className={`status-msg mb-4 ${
727
- connState !== "loading" ? "hidden" : "block"
728
- }`}
729
- >
730
- <div className="loader inline-block align-middle mr-2"></div>
731
- <span id="loader-text" className="text-sm">
732
- {onboardingInProgress
733
- ? "Configuring connection to PayPal…"
734
- : "Checking connection..."}
735
- </span>
736
- </div>
737
-
738
- <div className={`${connState === "ready" ? "block" : "hidden"}`}>
739
- <a
740
- ref={(node) => {
741
- paypalButtonRef.current = node
742
- ppBtnMeasureRef.current = node
743
- }}
744
- id="paypal-button"
745
- data-paypal-button="true"
746
- href={finalUrl || "#"}
747
- data-paypal-onboard-complete="onboardingCallback"
748
- onClick={handleConnectClick}
749
- className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none no-underline shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
750
- style={{
751
- cursor: onboardingInProgress ? "not-allowed" : "pointer",
752
- opacity: onboardingInProgress ? 0.6 : 1,
753
- pointerEvents: onboardingInProgress ? "none" : "auto",
754
- }}
755
- >
756
- Connect to PayPal
757
- </a>
758
-
759
- <div
760
- className="mt-2"
761
- style={{
762
- width: ppBtnWidth ? `${ppBtnWidth}px` : "auto",
763
- marginTop: "20px",
764
- marginBottom: "10px",
765
- }}
766
- >
767
- <div className="flex justify-center">
768
- <span className="text-[11px] text-ui-fg-muted leading-none">
769
- OR
770
- </span>
771
- </div>
772
- </div>
773
-
774
- <div className="mt-1">
775
- <button
776
- type="button"
777
- onClick={() => setShowManual(!showManual)}
778
- disabled={onboardingInProgress}
779
- className="text-sm text-ui-fg-interactive underline whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
780
- >
781
- Click here to insert credentials manually
782
- </button>
783
- </div>
784
- </div>
785
-
786
- <div className={`${connState === "ready" ? "hidden" : "block"} mt-3`}>
787
- <button
788
- type="button"
789
- onClick={() => setShowManual(!showManual)}
790
- disabled={onboardingInProgress}
791
- className="text-sm text-ui-fg-interactive underline whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
792
- >
793
- Click here to insert credentials manually
794
- </button>
795
- </div>
796
-
797
- <div
798
- ref={errorLogRef}
799
- id="error-log"
800
- className={`mt-4 text-left text-xs bg-red-50 text-red-600 p-3 border border-red-200 rounded ${
801
- connState === "error" && error ? "block" : "hidden"
802
- }`}
803
- >
804
- {error}
805
- </div>
806
- </>
807
- )}
808
- </div>
809
-
810
- {showManual && (
811
- <div className="md:col-span-2">
812
- <div className="ml-[260px] max-w-xl mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
813
- <div className="flex flex-col gap-1">
814
- <label htmlFor="pp-manual-client-id" className="text-sm font-medium">Client ID</label>
815
- <input
816
- id="pp-manual-client-id"
817
- type="text"
818
- value={clientId}
819
- onChange={(e) => setClientId(e.target.value)}
820
- disabled={onboardingInProgress}
821
- className="rounded-md border border-ui-border-base bg-transparent px-3 py-2 text-sm disabled:opacity-50"
822
- placeholder={
823
- env === "sandbox" ? "Sandbox Client ID" : "Live Client ID"
824
- }
825
- />
826
- </div>
827
-
828
- <div className="flex flex-col gap-1">
829
- <label htmlFor="pp-manual-secret" className="text-sm font-medium">Secret</label>
830
- <input
831
- id="pp-manual-secret"
832
- type="password"
833
- value={secret}
834
- onChange={(e) => setSecret(e.target.value)}
835
- disabled={onboardingInProgress}
836
- className="rounded-md border border-ui-border-base bg-transparent px-3 py-2 text-sm disabled:opacity-50"
837
- placeholder={env === "sandbox" ? "Sandbox Secret" : "Live Secret"}
838
- />
839
- </div>
840
-
841
- <div className="md:col-span-2 rounded-md border border-ui-border-base bg-ui-bg-subtle p-4 text-sm text-ui-fg-subtle">
842
- <p className="font-medium text-ui-fg-base">
843
- Get your Client ID and Secret in 3 steps:
844
- </p>
845
- <ol className="mt-2 list-decimal space-y-2 pl-5">
846
- <li>
847
- Open{" "}
848
- <a
849
- href="https://developer.paypal.com/dashboard/"
850
- target="_blank"
851
- rel="noreferrer"
852
- className="text-ui-fg-interactive underline"
853
- >
854
- Log in to Dashboard
855
- </a>{" "}
856
- and sign in or create an account.
857
- </li>
858
- <li>Select <span className="font-medium text-ui-fg-base">Apps & Credentials</span>, then choose <span className="font-medium text-ui-fg-base">Create App</span> if you need a new project.</li>
859
- <li>Copy your app's <span className="font-medium text-ui-fg-base">Client ID</span> and <span className="font-medium text-ui-fg-base">Secret</span>, paste them above, then click <span className="font-medium text-ui-fg-base">Save credentials</span>.</li>
860
- </ol>
861
- </div>
862
-
863
- <div className="md:col-span-2 flex items-center gap-2 mt-2">
864
- <button
865
- type="button"
866
- className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
867
- onClick={() => setShowManual(false)}
868
- disabled={onboardingInProgress}
869
- >
870
- Cancel
871
- </button>
872
-
873
- <button
874
- type="button"
875
- className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
876
- disabled={!canSaveManual || onboardingInProgress}
877
- onClick={handleSaveManual}
878
- >
879
- Save credentials
880
- </button>
881
- </div>
882
- </div>
883
- </div>
884
- )}
885
- </div>
886
- </div>
887
- </div>
888
-
889
- <style>{`
890
- .loader {
891
- border: 3px solid #f3f3f3;
892
- border-top: 3px solid #0070ba;
893
- border-radius: 50%;
894
- width: 18px;
895
- height: 18px;
896
- animation: spin 1s linear infinite;
897
- display: inline-block;
898
- vertical-align: middle;
899
- margin-right: 8px;
900
- }
901
- @keyframes spin {
902
- 0% { transform: rotate(0deg); }
903
- 100% { transform: rotate(360deg); }
904
- }
905
- `}</style>
906
- </div>
907
- )
908
- }
1
+ import React, {
2
+ useCallback,
3
+ useEffect,
4
+ useLayoutEffect,
5
+ useMemo,
6
+ useRef,
7
+ useState,
8
+ } from "react"
9
+ import { defineRouteConfig } from "@medusajs/admin-sdk"
10
+ import PayPalTabs from "../_components/Tabs"
11
+
12
+ export const config = defineRouteConfig({
13
+ label: "PayPal Connection",
14
+ })
15
+
16
+ // Let partner.js own the entire onboarding flow: it opens PayPal's mini-browser
17
+ // itself (synchronously inside the click, so no new tab / no popup block), it
18
+ // receives PayPal's completion postMessage, and it invokes the callback named in
19
+ // `data-paypal-onboard-complete` with (authCode, sharedId). This is PayPal's
20
+ // documented integration and matches the official @easypayment WooCommerce
21
+ // plugin. Opening the popup ourselves (a previous attempt at fixing the "opens a
22
+ // new tab" issue) stopped partner.js from receiving completion, which left the
23
+ // popup stranded on PayPal's "isuDone" page and never saved credentials.
24
+ const PARTNER_JS_URL =
25
+ "https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js"
26
+
27
+ declare global {
28
+ interface Window {
29
+ PAYPAL?: {
30
+ apps?: {
31
+ Signup?: {
32
+ miniBrowser?: { init?: () => void; closeFlow?: () => void }
33
+ MiniBrowser?: { init?: () => void; closeFlow?: () => void }
34
+ }
35
+ }
36
+ }
37
+ onboardingCallback?: (authCode: string, sharedId: string) => void
38
+ }
39
+ }
40
+
41
+ const SERVICE_URL = "/admin/paypal/onboarding-link"
42
+
43
+ // Generated onboarding URLs are cached in localStorage per environment so a
44
+ // page reload doesn't mint a new partner-referral session every time.
45
+ const CACHE_PREFIX = "pp_onboard_cache"
46
+ const CACHE_EXPIRY = 6 * 60 * 60 * 1000 // 6 hours
47
+
48
+ const ONBOARDING_COMPLETE_ENDPOINT = "/admin/paypal/onboard-complete"
49
+ const STATUS_ENDPOINT = "/admin/paypal/status"
50
+ const SAVE_CREDENTIALS_ENDPOINT = "/admin/paypal/save-credentials"
51
+ const DISCONNECT_ENDPOINT = "/admin/paypal/disconnect"
52
+ const ENVIRONMENT_ENDPOINT = "/admin/paypal/environment"
53
+
54
+ type Env = "sandbox" | "live"
55
+
56
+ const cacheKeyFor = (env: Env) => `${CACHE_PREFIX}_${env}`
57
+
58
+ function readCachedUrl(env: Env): string | null {
59
+ if (typeof window === "undefined") return null
60
+ try {
61
+ const raw = localStorage.getItem(cacheKeyFor(env))
62
+ if (!raw) return null
63
+ const data = JSON.parse(raw)
64
+ if (
65
+ data &&
66
+ typeof data.url === "string" &&
67
+ Date.now() - (Number(data.ts) || 0) < CACHE_EXPIRY
68
+ ) {
69
+ return data.url
70
+ }
71
+ } catch {
72
+ /* ignore malformed cache */
73
+ }
74
+ return null
75
+ }
76
+
77
+ function writeCachedUrl(env: Env, url: string) {
78
+ try {
79
+ localStorage.setItem(
80
+ cacheKeyFor(env),
81
+ JSON.stringify({ url, ts: Date.now() })
82
+ )
83
+ } catch {
84
+ /* ignore */
85
+ }
86
+ }
87
+
88
+ function clearCachedUrl(env?: Env) {
89
+ try {
90
+ if (env) {
91
+ localStorage.removeItem(cacheKeyFor(env))
92
+ } else {
93
+ localStorage.removeItem(cacheKeyFor("sandbox"))
94
+ localStorage.removeItem(cacheKeyFor("live"))
95
+ }
96
+ } catch {
97
+ /* ignore */
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Settings → PayPal → PayPal Connection.
103
+ *
104
+ * Drives partner onboarding through PayPal's `partner.js` mini-browser, with
105
+ * a manual client-id/secret fallback, per-environment (sandbox/live)
106
+ * switching, and status polling so the page flips to "connected" even when
107
+ * the popup's completion callback never reaches the opener.
108
+ */
109
+ export default function PayPalConnectionPage() {
110
+ const [env, setEnv] = useState<Env>("live")
111
+ const [envReady, setEnvReady] = useState(false)
112
+
113
+ const [connState, setConnState] = useState<
114
+ "loading" | "ready" | "connected" | "error"
115
+ >("loading")
116
+ const [error, setError] = useState<string | null>(null)
117
+ const [finalUrl, setFinalUrl] = useState<string>("")
118
+ const [showManual, setShowManual] = useState(false)
119
+ const [clientId, setClientId] = useState("")
120
+ const [secret, setSecret] = useState("")
121
+ const [statusInfo, setStatusInfo] = useState<{
122
+ seller_client_id_masked?: string | null
123
+ seller_client_secret_masked?: string | null
124
+ seller_email?: string | null
125
+ } | null>(null)
126
+
127
+ const [onboardingInProgress, setOnboardingInProgress] = useState(false)
128
+
129
+ const initLoaderRef = useRef<HTMLDivElement>(null)
130
+ const paypalButtonRef = useRef<HTMLAnchorElement | null>(null)
131
+ const errorLogRef = useRef<HTMLDivElement>(null)
132
+ const runIdRef = useRef(0)
133
+ const currentRunId = useRef(0)
134
+ const completedRef = useRef(false)
135
+
136
+ // Long-lived listeners/timers read the current env through a ref so they never
137
+ // capture a stale value from the render that registered them.
138
+ const envRef = useRef<Env>(env)
139
+ envRef.current = env
140
+
141
+ const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
142
+ const pollAttemptsRef = useRef(0)
143
+
144
+ const ppBtnMeasureRef = useRef<HTMLAnchorElement | null>(null)
145
+ const [ppBtnWidth, setPpBtnWidth] = useState<number | null>(null)
146
+
147
+ const canSaveManual = useMemo(() => {
148
+ return clientId.trim().length > 0 && secret.trim().length > 0
149
+ }, [clientId, secret])
150
+
151
+ const showError = useCallback((msg: string) => {
152
+ setConnState("error")
153
+ setError(msg)
154
+ }, [])
155
+
156
+ // Close PayPal's mini-browser via partner.js's API (works under both the
157
+ // `miniBrowser` and `MiniBrowser` casings PayPal has shipped over time).
158
+ const closeMiniBrowser = useCallback(() => {
159
+ try {
160
+ const close1 = window.PAYPAL?.apps?.Signup?.MiniBrowser?.closeFlow
161
+ if (typeof close1 === "function") close1()
162
+ } catch {}
163
+ try {
164
+ const close2 = window.PAYPAL?.apps?.Signup?.miniBrowser?.closeFlow
165
+ if (typeof close2 === "function") close2()
166
+ } catch {}
167
+ }, [])
168
+
169
+ const stopStatusPolling = useCallback(() => {
170
+ if (pollTimerRef.current) {
171
+ clearTimeout(pollTimerRef.current)
172
+ pollTimerRef.current = null
173
+ }
174
+ pollAttemptsRef.current = 0
175
+ }, [])
176
+
177
+ // Fetch status for an env and, if the seller credentials are present, flip the
178
+ // UI to "connected" and close the PayPal popup. Returns true once connected.
179
+ const refreshStatusAndMaybeConnect = useCallback(
180
+ async (activeEnv: Env): Promise<boolean> => {
181
+ try {
182
+ const res = await fetch(`${STATUS_ENDPOINT}?environment=${activeEnv}`, {
183
+ method: "GET",
184
+ credentials: "include",
185
+ })
186
+ const st = await res.json().catch(() => ({}))
187
+ const connected =
188
+ st?.status === "connected" && st?.seller_client_id_present === true
189
+ if (connected) {
190
+ completedRef.current = true
191
+ setStatusInfo(st)
192
+ setConnState("connected")
193
+ setShowManual(false)
194
+ setOnboardingInProgress(false)
195
+ clearCachedUrl(activeEnv)
196
+ closeMiniBrowser()
197
+ stopStatusPolling()
198
+ }
199
+ return connected
200
+ } catch {
201
+ return false
202
+ }
203
+ },
204
+ [closeMiniBrowser, stopStatusPolling]
205
+ )
206
+
207
+ // While a connect attempt is in flight, the seller may complete onboarding via
208
+ // a path that never reaches the opener (e.g. partner.js fails to fire its
209
+ // callback, or the popup's completion message is blocked). The return_url
210
+ // bridge still saves credentials server-side, so poll status as the reliable
211
+ // fallback: the moment credentials land, this flips to "connected" and closes
212
+ // the stranded popup.
213
+ const startStatusPolling = useCallback(() => {
214
+ stopStatusPolling()
215
+ const MAX_ATTEMPTS = 100 // ~5 min at 3s intervals
216
+ const tick = async () => {
217
+ pollAttemptsRef.current += 1
218
+ const connected = await refreshStatusAndMaybeConnect(envRef.current)
219
+ if (connected || completedRef.current) return
220
+ if (pollAttemptsRef.current >= MAX_ATTEMPTS) {
221
+ stopStatusPolling()
222
+ return
223
+ }
224
+ pollTimerRef.current = setTimeout(tick, 3000)
225
+ }
226
+ pollTimerRef.current = setTimeout(tick, 3000)
227
+ }, [refreshStatusAndMaybeConnect, stopStatusPolling])
228
+
229
+ // Shared completion: exchange authCode/sharedId for seller credentials, then
230
+ // close the popup and refresh status. Invoked by partner.js's onboardingCallback
231
+ // and by the return_url bridge's postMessage. Guarded + server-idempotent so
232
+ // redundant invocations are harmless.
233
+ const completeOnboarding = useCallback(
234
+ async (authCode: string, sharedId: string) => {
235
+ if (!authCode || !sharedId) return
236
+ if (completedRef.current) return
237
+ completedRef.current = true
238
+
239
+ try {
240
+ window.onbeforeunload = null
241
+ } catch {}
242
+
243
+ const activeEnv: Env = envRef.current === "sandbox" ? "sandbox" : "live"
244
+
245
+ setOnboardingInProgress(true)
246
+ setConnState("loading")
247
+ setError(null)
248
+
249
+ try {
250
+ const res = await fetch(ONBOARDING_COMPLETE_ENDPOINT, {
251
+ method: "POST",
252
+ headers: { "content-type": "application/json" },
253
+ credentials: "include",
254
+ body: JSON.stringify({ authCode, sharedId, env: activeEnv }),
255
+ })
256
+
257
+ if (!res.ok) {
258
+ const txt = await res.text().catch(() => "")
259
+ throw new Error(txt || `Onboarding exchange failed (${res.status})`)
260
+ }
261
+
262
+ closeMiniBrowser()
263
+ clearCachedUrl(activeEnv)
264
+
265
+ try {
266
+ const statusRes = await fetch(
267
+ `${STATUS_ENDPOINT}?environment=${activeEnv}`,
268
+ { method: "GET", credentials: "include" }
269
+ )
270
+ const refreshedStatus = await statusRes.json().catch(() => ({}))
271
+ setStatusInfo(refreshedStatus || null)
272
+ } catch {}
273
+
274
+ setConnState("connected")
275
+ setShowManual(false)
276
+ stopStatusPolling()
277
+ } catch (e: any) {
278
+ completedRef.current = false
279
+ console.error(e)
280
+ // The bridge may have already saved credentials server-side; if so the
281
+ // poll will surface "connected". Don't strand the user on an error.
282
+ setConnState("error")
283
+ setError(e?.message || "Exchange failed while saving credentials.")
284
+ } finally {
285
+ setOnboardingInProgress(false)
286
+ }
287
+ },
288
+ [closeMiniBrowser, stopStatusPolling]
289
+ )
290
+
291
+ // Bind partner.js to the connect button once it has a real onboarding URL.
292
+ const initPartner = useCallback(() => {
293
+ const signup = window.PAYPAL?.apps?.Signup
294
+ const init =
295
+ (signup?.miniBrowser && signup.miniBrowser.init) ||
296
+ (signup?.MiniBrowser && signup.MiniBrowser.init)
297
+ if (typeof init === "function") {
298
+ try {
299
+ init()
300
+ } catch (e) {
301
+ console.error("[paypal] partner.js init failed:", e)
302
+ }
303
+ }
304
+ }, [])
305
+
306
+ // Load partner.js once for the lifetime of the page.
307
+ useEffect(() => {
308
+ const existingScript = document.getElementById("paypal-partner-js")
309
+ if (existingScript) return
310
+
311
+ const preloadHref = PARTNER_JS_URL
312
+ let preloadLink: HTMLLinkElement | null = null
313
+ if (
314
+ !document.head.querySelector(`link[rel="preload"][href="${preloadHref}"]`)
315
+ ) {
316
+ preloadLink = document.createElement("link")
317
+ preloadLink.rel = "preload"
318
+ preloadLink.href = preloadHref
319
+ preloadLink.as = "script"
320
+ document.head.appendChild(preloadLink)
321
+ }
322
+
323
+ const ppScript = document.createElement("script")
324
+ ppScript.id = "paypal-partner-js"
325
+ ppScript.src = preloadHref
326
+ ppScript.async = true
327
+ document.head.appendChild(ppScript)
328
+
329
+ return () => {
330
+ if (preloadLink?.parentNode)
331
+ preloadLink.parentNode.removeChild(preloadLink)
332
+ if (ppScript.parentNode) ppScript.parentNode.removeChild(ppScript)
333
+ }
334
+ }, [])
335
+
336
+ // Put the (cached or freshly generated) onboarding URL on the button, then wait
337
+ // for partner.js to be present before showing the button + initializing it. The
338
+ // button is only revealed once partner.js is ready, which is what guarantees
339
+ // the first click opens the mini-browser popup (never a new tab).
340
+ const activatePayPal = useCallback(
341
+ (url: string, runId: number) => {
342
+ if (paypalButtonRef.current) {
343
+ paypalButtonRef.current.href = url
344
+ }
345
+ setFinalUrl(url)
346
+
347
+ let attempts = 0
348
+ const MAX_ATTEMPTS = 200 // ~10s
349
+
350
+ const tryInit = () => {
351
+ if (runId !== currentRunId.current) return
352
+ if (window.PAYPAL?.apps?.Signup) {
353
+ initPartner()
354
+ setConnState("ready")
355
+ return
356
+ }
357
+ attempts++
358
+ if (attempts >= MAX_ATTEMPTS) {
359
+ showError(
360
+ "PayPal partner script failed to load. Please refresh and try again."
361
+ )
362
+ return
363
+ }
364
+ setTimeout(tryInit, 50)
365
+ }
366
+
367
+ tryInit()
368
+ },
369
+ [initPartner, showError]
370
+ )
371
+
372
+ const fetchFreshLink = useCallback(
373
+ async (targetEnv: Env, runId: number) => {
374
+ if (initLoaderRef.current) {
375
+ const loaderText = initLoaderRef.current.querySelector("#loader-text")
376
+ if (loaderText)
377
+ loaderText.textContent = "Generating onboarding session..."
378
+ }
379
+
380
+ try {
381
+ const res = await fetch(SERVICE_URL, {
382
+ method: "POST",
383
+ headers: { "content-type": "application/json" },
384
+ credentials: "include",
385
+ body: JSON.stringify({ products: ["PPCP"], environment: targetEnv }),
386
+ })
387
+
388
+ const data = await res.json()
389
+
390
+ if (!res.ok) {
391
+ throw new Error(data?.message || `Service returned ${res.status}`)
392
+ }
393
+ if (runId !== currentRunId.current) return
394
+
395
+ const href = data?.onboarding_url
396
+ if (!href) {
397
+ showError("Onboarding URL not returned.")
398
+ return
399
+ }
400
+
401
+ const url =
402
+ href + (href.includes("?") ? "&" : "?") + "displayMode=minibrowser"
403
+
404
+ writeCachedUrl(targetEnv, url)
405
+ activatePayPal(url, runId)
406
+ } catch (err: any) {
407
+ if (runId !== currentRunId.current) return
408
+ showError(err?.message || "Unable to connect to service.")
409
+ }
410
+ },
411
+ [activatePayPal, showError]
412
+ )
413
+
414
+ // Resolve the server environment first.
415
+ useEffect(() => {
416
+ let alive = true
417
+ fetch(ENVIRONMENT_ENDPOINT, { method: "GET", credentials: "include" })
418
+ .then((r) => r.json())
419
+ .then((d) => {
420
+ if (!alive) return
421
+ setEnv(d?.environment === "sandbox" ? "sandbox" : "live")
422
+ })
423
+ .catch(() => {})
424
+ .finally(() => {
425
+ if (alive) setEnvReady(true)
426
+ })
427
+ return () => {
428
+ alive = false
429
+ }
430
+ }, [])
431
+
432
+ // Page-load flow: connected? -> cached link? -> else generate a fresh link.
433
+ useEffect(() => {
434
+ if (!envReady) return
435
+
436
+ currentRunId.current = ++runIdRef.current
437
+ const runId = currentRunId.current
438
+
439
+ let cancelled = false
440
+ completedRef.current = false
441
+
442
+ const run = async () => {
443
+ setConnState("loading")
444
+ setError(null)
445
+ setFinalUrl("")
446
+
447
+ try {
448
+ const r = await fetch(`${STATUS_ENDPOINT}?environment=${env}`, {
449
+ method: "GET",
450
+ credentials: "include",
451
+ })
452
+ const st = await r.json().catch(() => ({}))
453
+
454
+ if (cancelled || runId !== currentRunId.current) return
455
+
456
+ setStatusInfo(st)
457
+
458
+ const isConnected =
459
+ st?.status === "connected" && st?.seller_client_id_present === true
460
+
461
+ if (isConnected) {
462
+ setConnState("connected")
463
+ setShowManual(false)
464
+ return
465
+ }
466
+ } catch (e) {
467
+ console.error(e)
468
+ }
469
+
470
+ if (cancelled || runId !== currentRunId.current) return
471
+
472
+ const cached = readCachedUrl(env)
473
+ if (cached) {
474
+ activatePayPal(cached, runId)
475
+ return
476
+ }
477
+
478
+ await fetchFreshLink(env, runId)
479
+ }
480
+
481
+ run()
482
+
483
+ return () => {
484
+ cancelled = true
485
+ }
486
+ }, [env, envReady, fetchFreshLink, activatePayPal])
487
+
488
+ // partner.js invokes this by name (data-paypal-onboard-complete) once PayPal
489
+ // returns the seller's authCode + sharedId.
490
+ useLayoutEffect(() => {
491
+ window.onboardingCallback = (authCode: string, sharedId: string) => {
492
+ void completeOnboarding(authCode, sharedId)
493
+ }
494
+
495
+ return () => {
496
+ window.onboardingCallback = undefined
497
+ }
498
+ }, [completeOnboarding])
499
+
500
+ // The return_url bridge (/store/paypal/onboard-return), which runs inside the
501
+ // popup after PayPal redirects to it, posts its params back here. The bridge has
502
+ // already exchanged credentials server-side, so we just refresh status to flip
503
+ // to "connected" and close the popup. If for some reason credentials aren't yet
504
+ // saved but PayPal forwarded an authCode/sharedId, complete it from here too.
505
+ useEffect(() => {
506
+ const onMessage = (event: MessageEvent) => {
507
+ const data = event?.data as
508
+ | { source?: string; params?: Record<string, string> }
509
+ | undefined
510
+ if (!data || data.source !== "paypal-onboarding-return") return
511
+
512
+ const params = data.params || {}
513
+ const authCode = params.authCode || params.auth_code
514
+ const sharedId = params.sharedId || params.shared_id
515
+ const activeEnv = envRef.current
516
+
517
+ void (async () => {
518
+ const connected = await refreshStatusAndMaybeConnect(activeEnv)
519
+ if (!connected && authCode && sharedId) {
520
+ await completeOnboarding(authCode, sharedId)
521
+ }
522
+ })()
523
+ }
524
+
525
+ window.addEventListener("message", onMessage)
526
+ return () => window.removeEventListener("message", onMessage)
527
+ }, [completeOnboarding, refreshStatusAndMaybeConnect])
528
+
529
+ // Always stop polling when the component unmounts.
530
+ useEffect(() => stopStatusPolling, [stopStatusPolling])
531
+
532
+ useLayoutEffect(() => {
533
+ const el = ppBtnMeasureRef.current
534
+ if (!el) return
535
+
536
+ const update = () => {
537
+ const w = Math.round(el.getBoundingClientRect().width || 0)
538
+ if (w > 0) setPpBtnWidth(w)
539
+ }
540
+
541
+ update()
542
+
543
+ let ro: ResizeObserver | null = null
544
+ if (typeof ResizeObserver !== "undefined") {
545
+ ro = new ResizeObserver(() => update())
546
+ ro.observe(el)
547
+ } else {
548
+ window.addEventListener("resize", update)
549
+ }
550
+
551
+ return () => {
552
+ if (ro) ro.disconnect()
553
+ else window.removeEventListener("resize", update)
554
+ }
555
+ }, [connState, env, finalUrl])
556
+
557
+ // Only block the click while we are not ready; when ready, let the native click
558
+ // through so partner.js can open the mini-browser. Start polling status so we
559
+ // detect completion (and close the popup) even if no completion message reaches
560
+ // this page.
561
+ const handleConnectClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
562
+ if (connState !== "ready" || !finalUrl || onboardingInProgress) {
563
+ e.preventDefault()
564
+ return
565
+ }
566
+ completedRef.current = false
567
+ startStatusPolling()
568
+ }
569
+
570
+ const handleSaveManual = async () => {
571
+ if (!canSaveManual || onboardingInProgress) return
572
+ setOnboardingInProgress(true)
573
+ setConnState("loading")
574
+ setError(null)
575
+
576
+ try {
577
+ const res = await fetch(SAVE_CREDENTIALS_ENDPOINT, {
578
+ method: "POST",
579
+ headers: { "content-type": "application/json" },
580
+ credentials: "include",
581
+ body: JSON.stringify({
582
+ clientId: clientId.trim(),
583
+ clientSecret: secret.trim(),
584
+ environment: env,
585
+ }),
586
+ })
587
+
588
+ if (!res.ok) {
589
+ const txt = await res.text().catch(() => "")
590
+ throw new Error(txt || `Save credentials failed (${res.status})`)
591
+ }
592
+
593
+ const statusRes = await fetch(`${STATUS_ENDPOINT}?environment=${env}`, {
594
+ method: "GET",
595
+ credentials: "include",
596
+ })
597
+ const refreshedStatus = await statusRes.json().catch(() => ({}))
598
+
599
+ setConnState("connected")
600
+ setStatusInfo(refreshedStatus || null)
601
+ setShowManual(false)
602
+
603
+ clearCachedUrl(env)
604
+ } catch (e: any) {
605
+ console.error(e)
606
+ setConnState("error")
607
+ setError(e?.message || "Failed to save credentials.")
608
+ } finally {
609
+ setOnboardingInProgress(false)
610
+ }
611
+ }
612
+
613
+ const handleDisconnect = async () => {
614
+ if (onboardingInProgress) return
615
+ if (!window.confirm("Disconnect PayPal for this environment?")) return
616
+
617
+ stopStatusPolling()
618
+ setOnboardingInProgress(true)
619
+ setConnState("loading")
620
+ setError(null)
621
+ setFinalUrl("")
622
+ setShowManual(false)
623
+ setStatusInfo(null)
624
+
625
+ try {
626
+ const res = await fetch(DISCONNECT_ENDPOINT, {
627
+ method: "POST",
628
+ headers: { "content-type": "application/json" },
629
+ credentials: "include",
630
+ body: JSON.stringify({ environment: env }),
631
+ })
632
+
633
+ if (!res.ok) {
634
+ const t = await res.text().catch(() => "")
635
+ throw new Error(t || `Disconnect failed (${res.status})`)
636
+ }
637
+
638
+ clearCachedUrl(env)
639
+ completedRef.current = false
640
+
641
+ currentRunId.current = ++runIdRef.current
642
+ await fetchFreshLink(env, currentRunId.current)
643
+ } catch (e: any) {
644
+ console.error(e)
645
+ setConnState("error")
646
+ setError(e?.message || "Failed to disconnect.")
647
+ } finally {
648
+ setOnboardingInProgress(false)
649
+ }
650
+ }
651
+
652
+ const handleEnvChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
653
+ const next = e.target.value as Env
654
+ if (next === env || onboardingInProgress) return
655
+
656
+ stopStatusPolling()
657
+ completedRef.current = false
658
+ clearCachedUrl()
659
+ setConnState("loading")
660
+
661
+ try {
662
+ await fetch(ENVIRONMENT_ENDPOINT, {
663
+ method: "POST",
664
+ headers: { "content-type": "application/json" },
665
+ credentials: "include",
666
+ body: JSON.stringify({ environment: next }),
667
+ })
668
+ } catch {}
669
+
670
+ setEnv(next)
671
+ }
672
+
673
+ return (
674
+ <div className="p-6">
675
+ <div className="flex flex-col gap-6">
676
+ <div className="flex items-start justify-between gap-4">
677
+ <div>
678
+ <h1 className="text-xl font-semibold text-ui-fg-base">
679
+ PayPal Gateway By Easy Payment
680
+ </h1>
681
+ </div>
682
+ </div>
683
+
684
+ <PayPalTabs />
685
+
686
+ <div className="rounded-xl border border-ui-border-base bg-ui-bg-base shadow-sm">
687
+ <div className="grid grid-cols-1 gap-y-6 p-4 md:grid-cols-[260px_1fr] md:items-start">
688
+ <div className="text-sm font-medium pt-2">Environment</div>
689
+ <div className="max-w-xl">
690
+ <select
691
+ value={env}
692
+ onChange={handleEnvChange}
693
+ disabled={onboardingInProgress}
694
+ className="w-full rounded-md border border-ui-border-base bg-transparent px-3 py-2 text-sm"
695
+ >
696
+ <option value="sandbox">Sandbox (Test Mode)</option>
697
+ <option value="live">Live (Production)</option>
698
+ </select>
699
+ </div>
700
+
701
+ <div className="text-sm font-medium pt-2">
702
+ {env === "sandbox"
703
+ ? "Connect to PayPal (Sandbox)"
704
+ : "Connect to PayPal"}
705
+ </div>
706
+
707
+ <div className="max-w-xl">
708
+ {connState === "connected" ? (
709
+ <div>
710
+ <div className="text-sm text-green-600 bg-green-50 p-3 rounded border border-green-200">
711
+ ✅ Successfully connected to PayPal!
712
+ <a
713
+ data-paypal-button="true"
714
+ data-paypal-onboard-complete="onboardingCallback"
715
+ href="#"
716
+ style={{ display: "none" }}
717
+ >
718
+ PayPal
719
+ </a>
720
+ </div>
721
+ <div className="mt-3 rounded-md border border-ui-border-base bg-ui-bg-subtle p-3 text-xs text-ui-fg-subtle">
722
+ <div className="font-medium text-ui-fg-base">
723
+ Connected PayPal account
724
+ </div>
725
+ <div className="mt-1">
726
+ Email:{" "}
727
+ <span className="font-mono text-ui-fg-base">
728
+ {statusInfo?.seller_email || "Unavailable"}
729
+ </span>
730
+ </div>
731
+ </div>
732
+ <div className="mt-3 flex items-center gap-2">
733
+ <button
734
+ type="button"
735
+ onClick={handleDisconnect}
736
+ disabled={onboardingInProgress}
737
+ className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
738
+ >
739
+ Disconnect
740
+ </button>
741
+ </div>
742
+ </div>
743
+ ) : (
744
+ <>
745
+ <div
746
+ ref={initLoaderRef}
747
+ id="init-loader"
748
+ className={`status-msg mb-4 ${
749
+ connState !== "loading" ? "hidden" : "block"
750
+ }`}
751
+ >
752
+ <div className="loader inline-block align-middle mr-2"></div>
753
+ <span id="loader-text" className="text-sm">
754
+ {onboardingInProgress
755
+ ? "Configuring connection to PayPal…"
756
+ : "Checking connection..."}
757
+ </span>
758
+ </div>
759
+
760
+ <div
761
+ className={`${connState === "ready" ? "block" : "hidden"}`}
762
+ >
763
+ <a
764
+ ref={(node) => {
765
+ paypalButtonRef.current = node
766
+ ppBtnMeasureRef.current = node
767
+ }}
768
+ id="paypal-button"
769
+ data-paypal-button="true"
770
+ href={finalUrl || "#"}
771
+ data-paypal-onboard-complete="onboardingCallback"
772
+ onClick={handleConnectClick}
773
+ className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none no-underline shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
774
+ style={{
775
+ cursor: onboardingInProgress
776
+ ? "not-allowed"
777
+ : "pointer",
778
+ opacity: onboardingInProgress ? 0.6 : 1,
779
+ pointerEvents: onboardingInProgress ? "none" : "auto",
780
+ }}
781
+ >
782
+ Connect to PayPal
783
+ </a>
784
+
785
+ <div
786
+ className="mt-2"
787
+ style={{
788
+ width: ppBtnWidth ? `${ppBtnWidth}px` : "auto",
789
+ marginTop: "20px",
790
+ marginBottom: "10px",
791
+ }}
792
+ >
793
+ <div className="flex justify-center">
794
+ <span className="text-[11px] text-ui-fg-muted leading-none">
795
+ OR
796
+ </span>
797
+ </div>
798
+ </div>
799
+
800
+ <div className="mt-1">
801
+ <button
802
+ type="button"
803
+ onClick={() => setShowManual(!showManual)}
804
+ disabled={onboardingInProgress}
805
+ className="text-sm text-ui-fg-interactive underline whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
806
+ >
807
+ Click here to insert credentials manually
808
+ </button>
809
+ </div>
810
+ </div>
811
+
812
+ <div
813
+ className={`${connState === "ready" ? "hidden" : "block"} mt-3`}
814
+ >
815
+ <button
816
+ type="button"
817
+ onClick={() => setShowManual(!showManual)}
818
+ disabled={onboardingInProgress}
819
+ className="text-sm text-ui-fg-interactive underline whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
820
+ >
821
+ Click here to insert credentials manually
822
+ </button>
823
+ </div>
824
+
825
+ <div
826
+ ref={errorLogRef}
827
+ id="error-log"
828
+ className={`mt-4 text-left text-xs bg-red-50 text-red-600 p-3 border border-red-200 rounded ${
829
+ connState === "error" && error ? "block" : "hidden"
830
+ }`}
831
+ >
832
+ {error}
833
+ </div>
834
+ </>
835
+ )}
836
+ </div>
837
+
838
+ {showManual && (
839
+ <div className="md:col-span-2">
840
+ <div className="ml-[260px] max-w-xl mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
841
+ <div className="flex flex-col gap-1">
842
+ <label
843
+ htmlFor="pp-manual-client-id"
844
+ className="text-sm font-medium"
845
+ >
846
+ Client ID
847
+ </label>
848
+ <input
849
+ id="pp-manual-client-id"
850
+ type="text"
851
+ value={clientId}
852
+ onChange={(e) => setClientId(e.target.value)}
853
+ disabled={onboardingInProgress}
854
+ className="rounded-md border border-ui-border-base bg-transparent px-3 py-2 text-sm disabled:opacity-50"
855
+ placeholder={
856
+ env === "sandbox"
857
+ ? "Sandbox Client ID"
858
+ : "Live Client ID"
859
+ }
860
+ />
861
+ </div>
862
+
863
+ <div className="flex flex-col gap-1">
864
+ <label
865
+ htmlFor="pp-manual-secret"
866
+ className="text-sm font-medium"
867
+ >
868
+ Secret
869
+ </label>
870
+ <input
871
+ id="pp-manual-secret"
872
+ type="password"
873
+ value={secret}
874
+ onChange={(e) => setSecret(e.target.value)}
875
+ disabled={onboardingInProgress}
876
+ className="rounded-md border border-ui-border-base bg-transparent px-3 py-2 text-sm disabled:opacity-50"
877
+ placeholder={
878
+ env === "sandbox" ? "Sandbox Secret" : "Live Secret"
879
+ }
880
+ />
881
+ </div>
882
+
883
+ <div className="md:col-span-2 rounded-md border border-ui-border-base bg-ui-bg-subtle p-4 text-sm text-ui-fg-subtle">
884
+ <p className="font-medium text-ui-fg-base">
885
+ Get your Client ID and Secret in 3 steps:
886
+ </p>
887
+ <ol className="mt-2 list-decimal space-y-2 pl-5">
888
+ <li>
889
+ Open{" "}
890
+ <a
891
+ href="https://developer.paypal.com/dashboard/"
892
+ target="_blank"
893
+ rel="noreferrer"
894
+ className="text-ui-fg-interactive underline"
895
+ >
896
+ Log in to Dashboard
897
+ </a>{" "}
898
+ and sign in or create an account.
899
+ </li>
900
+ <li>
901
+ Select{" "}
902
+ <span className="font-medium text-ui-fg-base">
903
+ Apps & Credentials
904
+ </span>
905
+ , then choose{" "}
906
+ <span className="font-medium text-ui-fg-base">
907
+ Create App
908
+ </span>{" "}
909
+ if you need a new project.
910
+ </li>
911
+ <li>
912
+ Copy your app's{" "}
913
+ <span className="font-medium text-ui-fg-base">
914
+ Client ID
915
+ </span>{" "}
916
+ and{" "}
917
+ <span className="font-medium text-ui-fg-base">
918
+ Secret
919
+ </span>
920
+ , paste them above, then click{" "}
921
+ <span className="font-medium text-ui-fg-base">
922
+ Save credentials
923
+ </span>
924
+ .
925
+ </li>
926
+ </ol>
927
+ </div>
928
+
929
+ <div className="md:col-span-2 flex items-center gap-2 mt-2">
930
+ <button
931
+ type="button"
932
+ className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
933
+ onClick={() => setShowManual(false)}
934
+ disabled={onboardingInProgress}
935
+ >
936
+ Cancel
937
+ </button>
938
+
939
+ <button
940
+ type="button"
941
+ className="transition-fg relative inline-flex w-fit items-center justify-center overflow-hidden rounded-md outline-none shadow-buttons-neutral text-ui-fg-base bg-ui-button-neutral after:transition-fg after:absolute after:inset-0 after:content-[''] after:button-neutral-gradient hover:bg-ui-button-neutral-hover hover:after:button-neutral-hover-gradient active:bg-ui-button-neutral-pressed active:after:button-neutral-pressed-gradient focus-visible:shadow-buttons-neutral-focus disabled:bg-ui-bg-disabled disabled:border-ui-border-base disabled:text-ui-fg-disabled disabled:shadow-buttons-neutral disabled:after:hidden txt-compact-small-plus px-3 py-1.5"
942
+ disabled={!canSaveManual || onboardingInProgress}
943
+ onClick={handleSaveManual}
944
+ >
945
+ Save credentials
946
+ </button>
947
+ </div>
948
+ </div>
949
+ </div>
950
+ )}
951
+ </div>
952
+ </div>
953
+ </div>
954
+
955
+ <style>{`
956
+ .loader {
957
+ border: 3px solid #f3f3f3;
958
+ border-top: 3px solid #0070ba;
959
+ border-radius: 50%;
960
+ width: 18px;
961
+ height: 18px;
962
+ animation: spin 1s linear infinite;
963
+ display: inline-block;
964
+ vertical-align: middle;
965
+ margin-right: 8px;
966
+ }
967
+ @keyframes spin {
968
+ 0% { transform: rotate(0deg); }
969
+ 100% { transform: rotate(360deg); }
970
+ }
971
+ `}</style>
972
+ </div>
973
+ )
974
+ }