@easypayment/medusa-paypal-ui 1.0.49 → 1.0.51

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.
@@ -1,6 +1,6 @@
1
1
  "use client"
2
2
  import React, { useMemo, useState } from "react"
3
- import { PayPalButtons } from "@paypal/react-paypal-js"
3
+ import { PayPalButtons, usePayPalScriptReducer } from "@paypal/react-paypal-js"
4
4
  import { createPayPalStoreApi, markPaymentComplete } from "../client/paypal"
5
5
  import type { PayPalConfig } from "../client/types"
6
6
 
@@ -29,6 +29,7 @@ export function PayPalSmartButtons(props: {
29
29
 
30
30
  const [error, setError] = useState<string | null>(null)
31
31
  const [processing, setProcessing] = useState(false)
32
+ const [{ isPending, isResolved }] = usePayPalScriptReducer()
32
33
 
33
34
  if (!config.currency_supported) return null
34
35
 
@@ -75,7 +76,38 @@ export function PayPalSmartButtons(props: {
75
76
  </div>
76
77
  )}
77
78
 
78
- {config.environment === "sandbox" && (
79
+ {isPending && (
80
+ <div
81
+ style={{
82
+ display: "flex",
83
+ alignItems: "center",
84
+ justifyContent: "center",
85
+ gap: 10,
86
+ padding: "18px 16px",
87
+ background: "#f9fafb",
88
+ border: "1px solid #e5e7eb",
89
+ borderRadius: 8,
90
+ minHeight: 55,
91
+ }}
92
+ >
93
+ <div
94
+ style={{
95
+ width: 22,
96
+ height: 22,
97
+ borderRadius: "50%",
98
+ border: "2.5px solid #e5e7eb",
99
+ borderTopColor: "#0070ba",
100
+ animation: "_pp_spin .7s linear infinite",
101
+ flexShrink: 0,
102
+ }}
103
+ />
104
+ <div style={{ fontSize: 13, fontWeight: 500, color: "#6b7280" }}>
105
+ Loading PayPal…
106
+ </div>
107
+ </div>
108
+ )}
109
+
110
+ {config.environment === "sandbox" && isResolved && (
79
111
  <div
80
112
  style={{
81
113
  display: "flex",
@@ -111,47 +143,50 @@ export function PayPalSmartButtons(props: {
111
143
  </div>
112
144
  )}
113
145
 
114
- <PayPalButtons
115
- style={{
116
- layout: "vertical",
117
- color: config.button_color,
118
- shape: config.button_shape,
119
- label: config.button_label,
120
- height: config.button_height,
121
- }}
122
- createOrder={async () => {
123
- setError(null)
124
- const r = await api.createOrder(cartId)
125
- return r.id
126
- }}
127
- onApprove={async (data: { orderID?: string }) => {
128
- try {
129
- setProcessing(true)
146
+ {isResolved && (
147
+ <PayPalButtons
148
+ forceReRender={[config.currency, config.intent, cartId]}
149
+ style={{
150
+ layout: "vertical",
151
+ color: config.button_color,
152
+ shape: config.button_shape,
153
+ label: config.button_label,
154
+ height: config.button_height,
155
+ }}
156
+ createOrder={async () => {
130
157
  setError(null)
131
- const orderId = String(data?.orderID || "")
132
- const result = await api.captureOrder(cartId, orderId)
158
+ const r = await api.createOrder(cartId)
159
+ return r.id
160
+ }}
161
+ onApprove={async (data: { orderID?: string }) => {
162
+ try {
163
+ setProcessing(true)
164
+ setError(null)
165
+ const orderId = String(data?.orderID || "")
166
+ const result = await api.captureOrder(cartId, orderId)
133
167
 
134
- const completeResult = await markPaymentComplete(baseUrl, cartId, publishableApiKey)
168
+ const completeResult = await markPaymentComplete(baseUrl, cartId, publishableApiKey)
135
169
 
136
- onPaid?.({ ...result, ...completeResult })
137
- } catch (e: unknown) {
138
- const msg = e instanceof Error ? e.message : "Payment capture failed"
170
+ onPaid?.({ ...result, ...completeResult })
171
+ } catch (e: unknown) {
172
+ const msg = e instanceof Error ? e.message : "Payment capture failed"
173
+ setError(msg)
174
+ onError?.(msg)
175
+ } finally {
176
+ setProcessing(false)
177
+ }
178
+ }}
179
+ onCancel={() => {
180
+ setProcessing(false)
181
+ }}
182
+ onError={(err: Error | { message?: string }) => {
183
+ setProcessing(false)
184
+ const msg = err instanceof Error ? err.message : err?.message || "PayPal error"
139
185
  setError(msg)
140
186
  onError?.(msg)
141
- } finally {
142
- setProcessing(false)
143
- }
144
- }}
145
- onCancel={() => {
146
- setProcessing(false)
147
- }}
148
- onError={(err: Error | { message?: string }) => {
149
- setProcessing(false)
150
- const msg = err instanceof Error ? err.message : err?.message || "PayPal error"
151
- setError(msg)
152
- onError?.(msg)
153
- }}
154
- />
187
+ }}
188
+ />
189
+ )}
155
190
 
156
191
  {error ? (
157
192
  <div
package/src/order.ts ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Server-safe helpers for displaying PayPal payments on order / confirmation
3
+ * pages.
4
+ *
5
+ * This module is intentionally free of React and any client-only code, so it
6
+ * can be imported from Next.js **server components** (e.g. the order
7
+ * confirmation page) without pulling in the checkout UI.
8
+ *
9
+ * @example
10
+ * import { getPaymentLabel, fetchPayPalConfig } from "@easypayment/medusa-paypal-ui/order"
11
+ *
12
+ * // In the (async) server component that renders the payment method:
13
+ * const titles = await fetchPayPalConfig({
14
+ * baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL!,
15
+ * publishableApiKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
16
+ * })
17
+ *
18
+ * <Text>
19
+ * {getPaymentLabel(
20
+ * payment.provider_id,
21
+ * paymentInfoMap[payment.provider_id]?.title,
22
+ * titles
23
+ * )}
24
+ * </Text>
25
+ */
26
+
27
+ export const PAYPAL_WALLET_PROVIDER_ID = "pp_paypal_paypal"
28
+ export const PAYPAL_CARD_PROVIDER_ID = "pp_paypal_card_paypal_card"
29
+
30
+ export type PayPalPaymentInfo = { title: string }
31
+
32
+ /** Built-in fallback titles, used only when admin titles aren't supplied. */
33
+ export const paypalPaymentInfoMap: Record<string, PayPalPaymentInfo> = {
34
+ [PAYPAL_WALLET_PROVIDER_ID]: { title: "PayPal" },
35
+ [PAYPAL_CARD_PROVIDER_ID]: { title: "Credit or Debit Card" },
36
+ }
37
+
38
+ /** Admin-configured titles, as returned by `GET /store/paypal/config`. */
39
+ export type PayPalConfigTitles = {
40
+ paypal_title?: string | null
41
+ card_title?: string | null
42
+ }
43
+
44
+ /** True when the provider id belongs to this PayPal plugin. */
45
+ export function isPayPalProviderId(providerId?: string | null): boolean {
46
+ return (
47
+ providerId === PAYPAL_WALLET_PROVIDER_ID ||
48
+ providerId === PAYPAL_CARD_PROVIDER_ID
49
+ )
50
+ }
51
+
52
+ /**
53
+ * Null-safe payment label resolver for order / confirmation pages.
54
+ *
55
+ * Precedence for the PayPal providers: **admin-configured title** (`titles`,
56
+ * from {@link fetchPayPalConfig}) → built-in default. For any other provider:
57
+ * `fallback` → raw id. Never throws on an unknown / missing provider, which is
58
+ * what causes the common `Cannot read properties of undefined (reading 'title')`
59
+ * crash on the order confirmation page.
60
+ *
61
+ * @param titles Admin titles so the order page shows the same labels configured
62
+ * in Medusa Admin → Settings → PayPal (e.g. a custom "Credit or Debit Card").
63
+ */
64
+ export function getPaymentLabel(
65
+ providerId: string | undefined | null,
66
+ fallback?: string,
67
+ titles?: PayPalConfigTitles
68
+ ): string {
69
+ if (!providerId) {
70
+ return fallback ?? ""
71
+ }
72
+ if (providerId === PAYPAL_WALLET_PROVIDER_ID) {
73
+ return (
74
+ titles?.paypal_title?.trim() ||
75
+ paypalPaymentInfoMap[PAYPAL_WALLET_PROVIDER_ID].title
76
+ )
77
+ }
78
+ if (providerId === PAYPAL_CARD_PROVIDER_ID) {
79
+ return (
80
+ titles?.card_title?.trim() ||
81
+ paypalPaymentInfoMap[PAYPAL_CARD_PROVIDER_ID].title
82
+ )
83
+ }
84
+ return fallback ?? providerId
85
+ }
86
+
87
+ /**
88
+ * Fetch the admin-configured PayPal titles from the storefront API
89
+ * (`GET /store/paypal/config`). Server-safe (uses the global `fetch`).
90
+ *
91
+ * Returns `{}` on any error/network failure so callers can fall back to the
92
+ * built-in defaults without their own try/catch.
93
+ */
94
+ export async function fetchPayPalConfig(opts: {
95
+ baseUrl: string
96
+ publishableApiKey?: string
97
+ signal?: AbortSignal
98
+ }): Promise<PayPalConfigTitles> {
99
+ const { baseUrl, publishableApiKey, signal } = opts
100
+ if (!baseUrl) {
101
+ return {}
102
+ }
103
+ try {
104
+ const res = await fetch(`${baseUrl.replace(/\/$/, "")}/store/paypal/config`, {
105
+ headers: {
106
+ accept: "application/json",
107
+ ...(publishableApiKey ? { "x-publishable-api-key": publishableApiKey } : {}),
108
+ },
109
+ signal,
110
+ })
111
+ if (!res.ok) {
112
+ return {}
113
+ }
114
+ const cfg = (await res.json()) as Record<string, unknown>
115
+ return {
116
+ paypal_title:
117
+ typeof cfg.paypal_title === "string" ? cfg.paypal_title : undefined,
118
+ card_title:
119
+ typeof cfg.card_title === "string" ? cfg.card_title : undefined,
120
+ }
121
+ } catch {
122
+ return {}
123
+ }
124
+ }