create-brainerce-store 1.19.0 → 1.20.1

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,519 +1,565 @@
1
- 'use client';
2
-
3
- import { useEffect, useState, useRef, useCallback } from 'react';
4
- import type { PaymentIntent, PaymentClientSdk } from 'brainerce';
5
- import { getClient } from '@/lib/brainerce';
6
- import { useTranslations } from '@/lib/translations';
7
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
8
- import { cn } from '@/lib/utils';
9
-
10
- /**
11
- * Backward-compat defaults when backend doesn't return clientSdk.
12
- */
13
- const LEGACY_GROW_SDK: PaymentClientSdk = {
14
- renderType: 'sdk-widget',
15
- scriptUrl: 'https://cdn.meshulam.co.il/sdk/gs.min.js',
16
- globalName: 'growPayment',
17
- initMethod: 'init',
18
- renderMethod: 'renderPaymentOptions',
19
- containerId: 'grow-payment-container',
20
- initConfig: { version: 1, environment: 'DEV' },
21
- additionalScripts: [
22
- { url: 'https://meshulam.co.il/_media/js/apple_pay_sdk/sdk.min.js', optional: true },
23
- ],
24
- bodyStyles:
25
- '[id*="Gr0W8-"],[id*="Gr0W8-"] *,[class*="Gr0W8-"],[class*="Gr0W8-"] *{direction:ltr !important;text-align:left}',
26
- };
27
-
28
- interface PaymentStepProps {
29
- checkoutId: string;
30
- className?: string;
31
- }
32
-
33
- function resolveClientSdk(
34
- intent: PaymentIntent | null,
35
- preloadedSdk?: PaymentClientSdk | null
36
- ): PaymentClientSdk {
37
- const fullSdk = [preloadedSdk, intent?.clientSdk].find((s) => s?.renderType);
38
- const runtimeSdk = intent?.clientSdk;
39
- if (fullSdk) {
40
- if (!runtimeSdk || runtimeSdk === fullSdk) return fullSdk;
41
- return {
42
- ...fullSdk,
43
- ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
44
- ...(runtimeSdk.initConfig
45
- ? { initConfig: { ...fullSdk.initConfig, ...runtimeSdk.initConfig } }
46
- : {}),
47
- };
48
- }
49
- const legacy = intent?.provider === 'grow' ? LEGACY_GROW_SDK : null;
50
- if (legacy && runtimeSdk) {
51
- return {
52
- ...legacy,
53
- ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
54
- ...(runtimeSdk.initConfig
55
- ? { initConfig: { ...legacy.initConfig, ...runtimeSdk.initConfig } }
56
- : {}),
57
- };
58
- }
59
- if (legacy) return legacy;
60
- return { renderType: 'redirect' };
61
- }
62
-
63
- function extractMessage(response: unknown): string {
64
- if (typeof response === 'string') return response;
65
- return (response as { message?: string })?.message || '';
66
- }
67
-
68
- export function PaymentStep({ checkoutId, className }: PaymentStepProps) {
69
- const t = useTranslations('checkout');
70
- const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null);
71
- const [preloadedSdk, setPreloadedSdk] = useState<PaymentClientSdk | null>(null);
72
- const [loading, setLoading] = useState(true);
73
- const [error, setError] = useState<string | null>(null);
74
- const [sdkReady, setSdkReady] = useState(false);
75
- const walletOpenRef = useRef(false);
76
- const initialized = useRef(false);
77
-
78
- // Stable refs for SDK event callbacks (avoids stale closures in onload)
79
- const cbRef = useRef({
80
- onSuccess: (_r: unknown) => {},
81
- onFailure: (_r: unknown) => {},
82
- onError: (_r: unknown) => {},
83
- onTimeout: () => {},
84
- onWalletChange: (_s: string) => {},
85
- retryRender: () => {},
86
- });
87
-
88
- const handleSuccess = useCallback(
89
- async (response: unknown) => {
90
- console.info('Payment SDK success:', JSON.stringify(response));
91
- try {
92
- const client = getClient();
93
- const resp = response as Record<string, unknown>;
94
- const data = (resp?.data && typeof resp.data === 'object' ? resp.data : resp) as
95
- | Record<string, unknown>
96
- | undefined;
97
- await client.confirmSdkPayment(checkoutId, data || undefined);
98
- } catch (err) {
99
- console.warn('Failed to confirm payment with backend:', err);
100
- }
101
- window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
102
- },
103
- [checkoutId]
104
- );
105
-
106
- cbRef.current = {
107
- onSuccess: handleSuccess,
108
- onFailure: (response: unknown) => {
109
- console.error('Payment SDK failure:', response);
110
- setError(extractMessage(response) || t('paymentError'));
111
- },
112
- onError: (response: unknown) => {
113
- const TRANSIENT = [
114
- 'Wallet not initialized',
115
- "SDK was not loaded as needed and therefore can't run",
116
- ];
117
- const msg = extractMessage(response);
118
- if (TRANSIENT.some((e) => msg.includes(e))) {
119
- console.info('Payment SDK: transient error, retrying render in 1s:', msg);
120
- setTimeout(() => cbRef.current.retryRender(), 1000);
121
- return;
122
- }
123
- console.error('Payment SDK error:', response);
124
- setError(msg || t('paymentError'));
125
- },
126
- onTimeout: () => {
127
- console.warn('Payment SDK: wallet timed out');
128
- setError(t('paymentTimedOut'));
129
- },
130
- onWalletChange: (state: string) => {
131
- console.info('Payment SDK wallet state:', state);
132
- if (state === 'open') {
133
- walletOpenRef.current = true;
134
- setSdkReady(true);
135
- }
136
- if (state === 'close') setSdkReady(false);
137
- },
138
- retryRender: () => {},
139
- };
140
-
141
- // =========================================================================
142
- // MAIN EFFECT — Follows Grow SDK docs exactly:
143
- //
144
- // Step 1: Load gs.min.js (insertBefore, as docs show)
145
- // Step 2: s.onload → growPayment.init({ environment, version, events })
146
- // This triggers the SDK to load mp.min.js → CSS, HTML, params, services
147
- // Step 3: createPaymentIntent (starts wallet timer — should be AFTER init)
148
- // Step 4: growPayment.renderPaymentOptions(authCode)
149
- //
150
- // "call createPaymentProcess right before you need to render the wallet"
151
- // =========================================================================
152
- useEffect(() => {
153
- if (initialized.current) return;
154
- initialized.current = true;
155
-
156
- const client = getClient();
157
- const successUrl = `${window.location.origin}/order-confirmation?checkout_id=${checkoutId}`;
158
- const cancelUrl = `${window.location.origin}/checkout?checkout_id=${checkoutId}&canceled=true`;
159
-
160
- let sdkInitDone = false;
161
- let currentSdk: PaymentClientSdk | null = null;
162
- const cleanups: (() => void)[] = [];
163
-
164
- // --- Load SDK script exactly as Grow docs show ---
165
- function loadScript(sdk: PaymentClientSdk) {
166
- if (!sdk.scriptUrl || !sdk.globalName) return;
167
-
168
- // Inject bodyStyles
169
- if (sdk.bodyStyles && !document.querySelector('style[data-payment-sdk]')) {
170
- const style = document.createElement('style');
171
- style.setAttribute('data-payment-sdk', 'true');
172
- style.textContent = sdk.bodyStyles;
173
- document.head.appendChild(style);
174
- cleanups.push(() => style.remove());
175
- }
176
-
177
- // Additional scripts (Apple Pay etc.) — fire and forget
178
- if (sdk.additionalScripts) {
179
- for (const extra of sdk.additionalScripts) {
180
- if (document.querySelector(`script[src="${extra.url}"]`)) continue;
181
- const s = document.createElement('script');
182
- s.type = 'text/javascript';
183
- s.async = true;
184
- s.src = extra.url;
185
- const ref = document.getElementsByTagName('script')[0];
186
- if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
187
- else document.head.appendChild(s);
188
- }
189
- }
190
-
191
- // Already loaded? Init immediately
192
- if ((window as any)[sdk.globalName]) {
193
- initSdk(sdk);
194
- return;
195
- }
196
-
197
- // Already loading (from a previous call)? Wait for it instead of duplicating
198
- if (document.querySelector(`script[src="${sdk.scriptUrl}"]`)) {
199
- const waitId = setInterval(() => {
200
- if ((window as any)[sdk.globalName!]) {
201
- clearInterval(waitId);
202
- initSdk(sdk);
203
- }
204
- }, 100);
205
- cleanups.push(() => clearInterval(waitId));
206
- return;
207
- }
208
-
209
- // Load main SDK — insertBefore first <script> as Grow docs show
210
- const s = document.createElement('script');
211
- s.type = 'text/javascript';
212
- s.async = true;
213
- s.src = sdk.scriptUrl;
214
- s.onload = () => initSdk(sdk); // init DIRECTLY in onload
215
- s.onerror = () => {
216
- console.error('Payment SDK: script load failed');
217
- setError(t('failedToLoadPaymentSdk'));
218
- };
219
- const ref = document.getElementsByTagName('script')[0];
220
- if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
221
- else document.head.appendChild(s);
222
- }
223
-
224
- // --- Init: called in s.onload (as Grow docs require) ---
225
- function initSdk(sdk: PaymentClientSdk) {
226
- if (sdkInitDone) return; // Guard against double init
227
-
228
- const global = (window as any)[sdk.globalName!];
229
- if (!global) {
230
- setError(t('failedToLoadPaymentSdk'));
231
- return;
232
- }
233
-
234
- const method = sdk.initMethod || 'init';
235
- const config = {
236
- ...(sdk.initConfig || {}),
237
- events: {
238
- onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
239
- onFailure: (r: unknown) => cbRef.current.onFailure(r),
240
- onError: (r: unknown) => cbRef.current.onError(r),
241
- onTimeout: () => cbRef.current.onTimeout(),
242
- onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
243
- },
244
- };
245
-
246
- console.info(`Payment SDK: calling ${method}()`);
247
- global[method](config);
248
- sdkInitDone = true;
249
- }
250
-
251
- // --- Render: call once, then safety-net retries if wallet doesn't open ---
252
- // Grow SDK sometimes silently swallows renderPaymentOptions when its
253
- // internal resources (mp.min.js etc.) aren't fully loaded yet.
254
- // Strategy: render once, then retry up to 3 times with increasing delays
255
- // (2s, 3s, 4s) if onWalletChange("open") hasn't fired.
256
- let pendingRender: { sdk: PaymentClientSdk; intent: PaymentIntent } | null = null;
257
- let renderAttempts = 0;
258
- const MAX_RENDER_ATTEMPTS = 4;
259
-
260
- function renderPayment(sdk: PaymentClientSdk, intent: PaymentIntent) {
261
- const global = (window as any)[sdk.globalName!];
262
- if (!global || walletOpenRef.current) return;
263
-
264
- const renderMethod = sdk.renderMethod || 'renderPaymentOptions';
265
- const renderArg = sdk.renderArg || intent.clientSecret;
266
- renderAttempts++;
267
-
268
- try {
269
- global[renderMethod](renderArg);
270
- console.info(`Payment SDK: renderPaymentOptions called (attempt ${renderAttempts})`);
271
- } catch (err) {
272
- console.info('Payment SDK: render threw, will retry in 1s');
273
- }
274
-
275
- // Safety net: if wallet doesn't open within a delay, retry
276
- if (renderAttempts < MAX_RENDER_ATTEMPTS) {
277
- const delay = 1000 + renderAttempts * 1000; // 2s, 3s, 4s
278
- const retryId = setTimeout(() => {
279
- if (!walletOpenRef.current) {
280
- console.info(`Payment SDK: wallet not open after ${delay}ms, retrying render...`);
281
- renderPayment(sdk, intent);
282
- }
283
- }, delay);
284
- cleanups.push(() => clearTimeout(retryId));
285
- }
286
- }
287
-
288
- function retryRender() {
289
- if (pendingRender && !walletOpenRef.current) {
290
- renderPayment(pendingRender.sdk, pendingRender.intent);
291
- }
292
- }
293
-
294
- // =============================================
295
- // Execution flow
296
- // =============================================
297
-
298
- // A) Get SDK config from providers (fast, no wallet timer)
299
- const providerPromise = client
300
- .getPaymentProviders()
301
- .then((res) => {
302
- const sdk = res.defaultProvider?.clientSdk;
303
- if (sdk) setPreloadedSdk(sdk);
304
- return sdk || null;
305
- })
306
- .catch(() => null);
307
-
308
- // B) Load + init SDK as early as possible (skip for sandbox)
309
- providerPromise.then((providerSdk) => {
310
- if (providerSdk?.renderType === 'sandbox') return;
311
- if (providerSdk?.renderType === 'sdk-widget' && providerSdk.scriptUrl) {
312
- currentSdk = providerSdk;
313
- loadScript(providerSdk);
314
- }
315
- });
316
-
317
- // C) Create payment intent (starts wallet timer)
318
- const intentPromise = client
319
- .createPaymentIntent(checkoutId, { successUrl, cancelUrl })
320
- .then((intent) => {
321
- setPaymentIntent(intent);
322
- return intent;
323
- })
324
- .catch((err) => {
325
- setError(err instanceof Error ? err.message : t('paymentError'));
326
- return null;
327
- })
328
- .finally(() => setLoading(false));
329
-
330
- // D) When both ready: resolve final SDK config and render
331
- Promise.all([providerPromise, intentPromise]).then(([providerSdk, intent]) => {
332
- if (!intent) return;
333
-
334
- const sdk = resolveClientSdk(intent, providerSdk);
335
- currentSdk = sdk;
336
-
337
- // Sandbox mode — no SDK to load, UI handles it
338
- if (sdk.renderType === 'sandbox') return;
339
-
340
- if (sdk.renderType === 'redirect') {
341
- window.location.href = intent.clientSecret;
342
- return;
343
- }
344
- if (sdk.renderType !== 'sdk-widget' || !sdk.globalName) return;
345
-
346
- // Store for retryRender from onError callback
347
- pendingRender = { sdk, intent };
348
- cbRef.current.retryRender = retryRender;
349
-
350
- // If SDK wasn't loaded from providers, load + init now
351
- if (!sdkInitDone) {
352
- loadScript(sdk);
353
- // Wait for init to complete, then render once
354
- const id = setInterval(() => {
355
- if (sdkInitDone) {
356
- clearInterval(id);
357
- renderPayment(sdk, intent);
358
- }
359
- }, 100);
360
- cleanups.push(() => clearInterval(id));
361
- return;
362
- }
363
-
364
- // Re-init with final config if environment changed
365
- if (sdk.initConfig?.environment && currentSdk) {
366
- const global = (window as any)[sdk.globalName];
367
- if (global) {
368
- const method = sdk.initMethod || 'init';
369
- global[method]({
370
- ...(sdk.initConfig || {}),
371
- events: {
372
- onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
373
- onFailure: (r: unknown) => cbRef.current.onFailure(r),
374
- onError: (r: unknown) => cbRef.current.onError(r),
375
- onTimeout: () => cbRef.current.onTimeout(),
376
- onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
377
- },
378
- });
379
- }
380
- }
381
-
382
- // SDK ready render once
383
- renderPayment(sdk, intent);
384
- });
385
-
386
- return () => cleanups.forEach((fn) => fn());
387
- }, [checkoutId]);
388
-
389
- // --- UI ---
390
-
391
- if (loading) {
392
- return (
393
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
394
- <LoadingSpinner size="lg" />
395
- <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
396
- </div>
397
- );
398
- }
399
-
400
- if (error) {
401
- const isNotConfigured =
402
- error.toLowerCase().includes('not configured') ||
403
- error.toLowerCase().includes('no payment') ||
404
- error.toLowerCase().includes('provider');
405
- return (
406
- <div className={cn('py-12 text-center', className)}>
407
- <svg
408
- className="text-muted-foreground mx-auto mb-4 h-12 w-12"
409
- fill="none"
410
- viewBox="0 0 24 24"
411
- stroke="currentColor"
412
- >
413
- <path
414
- strokeLinecap="round"
415
- strokeLinejoin="round"
416
- strokeWidth={1.5}
417
- d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
418
- />
419
- </svg>
420
- <h3 className="text-foreground mb-2 text-lg font-semibold">
421
- {isNotConfigured ? t('paymentNotConfigured') : t('paymentError')}
422
- </h3>
423
- <p className="text-muted-foreground mx-auto max-w-md text-sm">
424
- {isNotConfigured ? t('paymentNotConfiguredDesc') : error}
425
- </p>
426
- </div>
427
- );
428
- }
429
-
430
- if (!paymentIntent) return null;
431
-
432
- const sdk = resolveClientSdk(paymentIntent, preloadedSdk);
433
-
434
- if (sdk.renderType === 'sandbox') {
435
- const handleCompleteSandbox = async () => {
436
- setLoading(true);
437
- try {
438
- const client = getClient();
439
- await client.completeGuestCheckout(checkoutId);
440
- window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
441
- } catch (err) {
442
- setError(err instanceof Error ? err.message : t('paymentError'));
443
- setLoading(false);
444
- }
445
- };
446
-
447
- return (
448
- <div className={cn('py-8 text-center', className)}>
449
- <div className="mx-auto max-w-md rounded-lg border border-amber-200 bg-amber-50 p-6">
450
- <svg
451
- className="mx-auto mb-3 h-10 w-10 text-amber-500"
452
- fill="none"
453
- viewBox="0 0 24 24"
454
- stroke="currentColor"
455
- >
456
- <path
457
- strokeLinecap="round"
458
- strokeLinejoin="round"
459
- strokeWidth={1.5}
460
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"
461
- />
462
- </svg>
463
- <h3 className="text-foreground mb-1 text-lg font-semibold">{t('sandboxTitle')}</h3>
464
- <p className="text-muted-foreground mb-4 text-sm">{t('sandboxDescription')}</p>
465
- <button
466
- onClick={handleCompleteSandbox}
467
- className="inline-flex items-center rounded-md bg-amber-500 px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-amber-600"
468
- >
469
- {t('completeTestOrder')}
470
- </button>
471
- </div>
472
- </div>
473
- );
474
- }
475
-
476
- if (sdk.renderType === 'sdk-widget') {
477
- const containerId =
478
- sdk.containerId || `${paymentIntent.provider || 'payment'}-payment-container`;
479
- return (
480
- <div className={cn('py-4', className)}>
481
- {!sdkReady && (
482
- <div className="flex flex-col items-center justify-center py-8">
483
- <LoadingSpinner size="lg" />
484
- <p className="text-muted-foreground mt-4 text-sm">{t('loadingPaymentOptions')}</p>
485
- </div>
486
- )}
487
- <div id={containerId} />
488
- </div>
489
- );
490
- }
491
-
492
- if (sdk.renderType === 'iframe') {
493
- return (
494
- <div className={cn('py-4', className)}>
495
- <iframe
496
- src={paymentIntent.clientSecret}
497
- className="w-full border-0"
498
- style={{ minHeight: '500px' }}
499
- title={t('payment')}
500
- allow="payment"
501
- />
502
- </div>
503
- );
504
- }
505
-
506
- return (
507
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
508
- <LoadingSpinner size="lg" />
509
- <p className="text-muted-foreground mt-4 text-sm">{t('redirectingToPayment')}</p>
510
- <p className="text-muted-foreground mt-2 text-xs">
511
- {t('redirectingHint')}
512
- <a href={paymentIntent.clientSecret} className="text-primary hover:underline">
513
- {t('clickHere')}
514
- </a>
515
- .
516
- </p>
517
- </div>
518
- );
519
- }
1
+ 'use client';
2
+
3
+ import { useEffect, useState, useRef, useCallback } from 'react';
4
+ import type { PaymentIntent, PaymentClientSdk } from 'brainerce';
5
+ import { getClient } from '@/lib/brainerce';
6
+ import { useTranslations } from '@/lib/translations';
7
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
8
+ import { cn } from '@/lib/utils';
9
+
10
+ /**
11
+ * Backward-compat defaults when backend doesn't return clientSdk.
12
+ */
13
+ const LEGACY_GROW_SDK: PaymentClientSdk = {
14
+ renderType: 'sdk-widget',
15
+ scriptUrl: 'https://cdn.meshulam.co.il/sdk/gs.min.js',
16
+ globalName: 'growPayment',
17
+ initMethod: 'init',
18
+ renderMethod: 'renderPaymentOptions',
19
+ containerId: 'grow-payment-container',
20
+ initConfig: { version: 1, environment: 'DEV' },
21
+ additionalScripts: [
22
+ { url: 'https://meshulam.co.il/_media/js/apple_pay_sdk/sdk.min.js', optional: true },
23
+ ],
24
+ bodyStyles:
25
+ '[id*="Gr0W8-"],[id*="Gr0W8-"] *,[class*="Gr0W8-"],[class*="Gr0W8-"] *{direction:ltr !important;text-align:left}',
26
+ };
27
+
28
+ interface PaymentStepProps {
29
+ checkoutId: string;
30
+ className?: string;
31
+ }
32
+
33
+ function resolveClientSdk(
34
+ intent: PaymentIntent | null,
35
+ preloadedSdk?: PaymentClientSdk | null
36
+ ): PaymentClientSdk {
37
+ const fullSdk = [preloadedSdk, intent?.clientSdk].find((s) => s?.renderType);
38
+ const runtimeSdk = intent?.clientSdk;
39
+ if (fullSdk) {
40
+ if (!runtimeSdk || runtimeSdk === fullSdk) return fullSdk;
41
+ return {
42
+ ...fullSdk,
43
+ ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
44
+ ...(runtimeSdk.initConfig
45
+ ? { initConfig: { ...fullSdk.initConfig, ...runtimeSdk.initConfig } }
46
+ : {}),
47
+ };
48
+ }
49
+ const legacy = intent?.provider === 'grow' ? LEGACY_GROW_SDK : null;
50
+ if (legacy && runtimeSdk) {
51
+ return {
52
+ ...legacy,
53
+ ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
54
+ ...(runtimeSdk.initConfig
55
+ ? { initConfig: { ...legacy.initConfig, ...runtimeSdk.initConfig } }
56
+ : {}),
57
+ };
58
+ }
59
+ if (legacy) return legacy;
60
+ return { renderType: 'redirect' };
61
+ }
62
+
63
+ function extractMessage(response: unknown): string {
64
+ if (typeof response === 'string') return response;
65
+ return (response as { message?: string })?.message || '';
66
+ }
67
+
68
+ export function PaymentStep({ checkoutId, className }: PaymentStepProps) {
69
+ const t = useTranslations('checkout');
70
+ const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null);
71
+ const [preloadedSdk, setPreloadedSdk] = useState<PaymentClientSdk | null>(null);
72
+ const [loading, setLoading] = useState(true);
73
+ const [error, setError] = useState<string | null>(null);
74
+ const [sdkReady, setSdkReady] = useState(false);
75
+ const walletOpenRef = useRef(false);
76
+ const initialized = useRef(false);
77
+
78
+ // Stable refs for SDK event callbacks (avoids stale closures in onload)
79
+ const cbRef = useRef({
80
+ onSuccess: (_r: unknown) => {},
81
+ onFailure: (_r: unknown) => {},
82
+ onError: (_r: unknown) => {},
83
+ onTimeout: () => {},
84
+ onWalletChange: (_s: string) => {},
85
+ retryRender: () => {},
86
+ });
87
+
88
+ const handleSuccess = useCallback(
89
+ async (response: unknown) => {
90
+ console.info('Payment SDK success:', JSON.stringify(response));
91
+ try {
92
+ const client = getClient();
93
+ const resp = response as Record<string, unknown>;
94
+ const data = (resp?.data && typeof resp.data === 'object' ? resp.data : resp) as
95
+ | Record<string, unknown>
96
+ | undefined;
97
+ await client.confirmSdkPayment(checkoutId, data || undefined);
98
+ } catch (err) {
99
+ console.warn('Failed to confirm payment with backend:', err);
100
+ }
101
+ window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
102
+ },
103
+ [checkoutId]
104
+ );
105
+
106
+ cbRef.current = {
107
+ onSuccess: handleSuccess,
108
+ onFailure: (response: unknown) => {
109
+ console.error('Payment SDK failure:', response);
110
+ setError(extractMessage(response) || t('paymentError'));
111
+ },
112
+ onError: (response: unknown) => {
113
+ const TRANSIENT = [
114
+ 'Wallet not initialized',
115
+ "SDK was not loaded as needed and therefore can't run",
116
+ ];
117
+ const msg = extractMessage(response);
118
+ if (TRANSIENT.some((e) => msg.includes(e))) {
119
+ console.info('Payment SDK: transient error, retrying render in 1s:', msg);
120
+ setTimeout(() => cbRef.current.retryRender(), 1000);
121
+ return;
122
+ }
123
+ console.error('Payment SDK error:', response);
124
+ setError(msg || t('paymentError'));
125
+ },
126
+ onTimeout: () => {
127
+ console.warn('Payment SDK: wallet timed out');
128
+ setError(t('paymentTimedOut'));
129
+ },
130
+ onWalletChange: (state: string) => {
131
+ console.info('Payment SDK wallet state:', state);
132
+ if (state === 'open') {
133
+ walletOpenRef.current = true;
134
+ setSdkReady(true);
135
+ }
136
+ if (state === 'close') setSdkReady(false);
137
+ },
138
+ retryRender: () => {},
139
+ };
140
+
141
+ // =========================================================================
142
+ // MAIN EFFECT — Follows Grow SDK docs exactly:
143
+ //
144
+ // Step 1: Load gs.min.js (insertBefore, as docs show)
145
+ // Step 2: s.onload → growPayment.init({ environment, version, events })
146
+ // This triggers the SDK to load mp.min.js → CSS, HTML, params, services
147
+ // Step 3: createPaymentIntent (starts wallet timer — should be AFTER init)
148
+ // Step 4: growPayment.renderPaymentOptions(authCode)
149
+ //
150
+ // "call createPaymentProcess right before you need to render the wallet"
151
+ // =========================================================================
152
+ useEffect(() => {
153
+ if (initialized.current) return;
154
+ initialized.current = true;
155
+
156
+ const client = getClient();
157
+ // For iframe-based providers, redirect inside the iframe goes to a
158
+ // lightweight callback page that sends postMessage to the parent window.
159
+ // For redirect-based providers, go straight to order-confirmation.
160
+ const iframeSuccessUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}`;
161
+ const iframeFailedUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}&failed=true`;
162
+ const redirectSuccessUrl = `${window.location.origin}/order-confirmation?checkout_id=${checkoutId}`;
163
+ const cancelUrl = `${window.location.origin}/checkout?checkout_id=${checkoutId}&canceled=true`;
164
+
165
+ let sdkInitDone = false;
166
+ let currentSdk: PaymentClientSdk | null = null;
167
+ const cleanups: (() => void)[] = [];
168
+
169
+ // --- Load SDK script exactly as Grow docs show ---
170
+ function loadScript(sdk: PaymentClientSdk) {
171
+ if (!sdk.scriptUrl || !sdk.globalName) return;
172
+
173
+ // Inject bodyStyles
174
+ if (sdk.bodyStyles && !document.querySelector('style[data-payment-sdk]')) {
175
+ const style = document.createElement('style');
176
+ style.setAttribute('data-payment-sdk', 'true');
177
+ style.textContent = sdk.bodyStyles;
178
+ document.head.appendChild(style);
179
+ cleanups.push(() => style.remove());
180
+ }
181
+
182
+ // Additional scripts (Apple Pay etc.) fire and forget
183
+ if (sdk.additionalScripts) {
184
+ for (const extra of sdk.additionalScripts) {
185
+ if (document.querySelector(`script[src="${extra.url}"]`)) continue;
186
+ const s = document.createElement('script');
187
+ s.type = 'text/javascript';
188
+ s.async = true;
189
+ s.src = extra.url;
190
+ const ref = document.getElementsByTagName('script')[0];
191
+ if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
192
+ else document.head.appendChild(s);
193
+ }
194
+ }
195
+
196
+ // Already loaded? Init immediately
197
+ if ((window as any)[sdk.globalName]) {
198
+ initSdk(sdk);
199
+ return;
200
+ }
201
+
202
+ // Already loading (from a previous call)? Wait for it instead of duplicating
203
+ if (document.querySelector(`script[src="${sdk.scriptUrl}"]`)) {
204
+ const waitId = setInterval(() => {
205
+ if ((window as any)[sdk.globalName!]) {
206
+ clearInterval(waitId);
207
+ initSdk(sdk);
208
+ }
209
+ }, 100);
210
+ cleanups.push(() => clearInterval(waitId));
211
+ return;
212
+ }
213
+
214
+ // Load main SDK insertBefore first <script> as Grow docs show
215
+ const s = document.createElement('script');
216
+ s.type = 'text/javascript';
217
+ s.async = true;
218
+ s.src = sdk.scriptUrl;
219
+ s.onload = () => initSdk(sdk); // init DIRECTLY in onload
220
+ s.onerror = () => {
221
+ console.error('Payment SDK: script load failed');
222
+ setError(t('failedToLoadPaymentSdk'));
223
+ };
224
+ const ref = document.getElementsByTagName('script')[0];
225
+ if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
226
+ else document.head.appendChild(s);
227
+ }
228
+
229
+ // --- Init: called in s.onload (as Grow docs require) ---
230
+ function initSdk(sdk: PaymentClientSdk) {
231
+ if (sdkInitDone) return; // Guard against double init
232
+
233
+ const global = (window as any)[sdk.globalName!];
234
+ if (!global) {
235
+ setError(t('failedToLoadPaymentSdk'));
236
+ return;
237
+ }
238
+
239
+ const method = sdk.initMethod || 'init';
240
+ const config = {
241
+ ...(sdk.initConfig || {}),
242
+ events: {
243
+ onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
244
+ onFailure: (r: unknown) => cbRef.current.onFailure(r),
245
+ onError: (r: unknown) => cbRef.current.onError(r),
246
+ onTimeout: () => cbRef.current.onTimeout(),
247
+ onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
248
+ },
249
+ };
250
+
251
+ console.info(`Payment SDK: calling ${method}()`);
252
+ global[method](config);
253
+ sdkInitDone = true;
254
+ }
255
+
256
+ // --- Render: call once, then safety-net retries if wallet doesn't open ---
257
+ // Grow SDK sometimes silently swallows renderPaymentOptions when its
258
+ // internal resources (mp.min.js etc.) aren't fully loaded yet.
259
+ // Strategy: render once, then retry up to 3 times with increasing delays
260
+ // (2s, 3s, 4s) if onWalletChange("open") hasn't fired.
261
+ let pendingRender: { sdk: PaymentClientSdk; intent: PaymentIntent } | null = null;
262
+ let renderAttempts = 0;
263
+ const MAX_RENDER_ATTEMPTS = 4;
264
+
265
+ function renderPayment(sdk: PaymentClientSdk, intent: PaymentIntent) {
266
+ const global = (window as any)[sdk.globalName!];
267
+ if (!global || walletOpenRef.current) return;
268
+
269
+ const renderMethod = sdk.renderMethod || 'renderPaymentOptions';
270
+ const renderArg = sdk.renderArg || intent.clientSecret;
271
+ renderAttempts++;
272
+
273
+ try {
274
+ global[renderMethod](renderArg);
275
+ console.info(`Payment SDK: renderPaymentOptions called (attempt ${renderAttempts})`);
276
+ } catch (err) {
277
+ console.info('Payment SDK: render threw, will retry in 1s');
278
+ }
279
+
280
+ // Safety net: if wallet doesn't open within a delay, retry
281
+ if (renderAttempts < MAX_RENDER_ATTEMPTS) {
282
+ const delay = 1000 + renderAttempts * 1000; // 2s, 3s, 4s
283
+ const retryId = setTimeout(() => {
284
+ if (!walletOpenRef.current) {
285
+ console.info(`Payment SDK: wallet not open after ${delay}ms, retrying render...`);
286
+ renderPayment(sdk, intent);
287
+ }
288
+ }, delay);
289
+ cleanups.push(() => clearTimeout(retryId));
290
+ }
291
+ }
292
+
293
+ function retryRender() {
294
+ if (pendingRender && !walletOpenRef.current) {
295
+ renderPayment(pendingRender.sdk, pendingRender.intent);
296
+ }
297
+ }
298
+
299
+ // =============================================
300
+ // Execution flow
301
+ // =============================================
302
+
303
+ // A) Get SDK config from providers (fast, no wallet timer)
304
+ const providerPromise = client
305
+ .getPaymentProviders()
306
+ .then((res) => {
307
+ const sdk = res.defaultProvider?.clientSdk;
308
+ if (sdk) setPreloadedSdk(sdk);
309
+ return sdk || null;
310
+ })
311
+ .catch(() => null);
312
+
313
+ // B) Load + init SDK as early as possible (skip for sandbox)
314
+ providerPromise.then((providerSdk) => {
315
+ if (providerSdk?.renderType === 'sandbox') return;
316
+ if (providerSdk?.renderType === 'sdk-widget' && providerSdk.scriptUrl) {
317
+ currentSdk = providerSdk;
318
+ loadScript(providerSdk);
319
+ }
320
+ });
321
+
322
+ // C) Create payment intent (starts wallet timer)
323
+ // Wait for provider info so we can choose the right success URL:
324
+ // iframe providers redirect inside the iframe to /payment-complete (postMessage),
325
+ // redirect providers go straight to /order-confirmation.
326
+ const intentPromise = providerPromise
327
+ .then((providerSdk) => {
328
+ const isIframe = providerSdk?.renderType === 'iframe';
329
+ const successUrl = isIframe ? iframeSuccessUrl : redirectSuccessUrl;
330
+ const failedUrl = isIframe ? iframeFailedUrl : cancelUrl;
331
+ return client.createPaymentIntent(checkoutId, {
332
+ successUrl,
333
+ cancelUrl: failedUrl,
334
+ });
335
+ })
336
+ .then((intent) => {
337
+ setPaymentIntent(intent);
338
+ return intent;
339
+ })
340
+ .catch((err) => {
341
+ setError(err instanceof Error ? err.message : t('paymentError'));
342
+ return null;
343
+ })
344
+ .finally(() => setLoading(false));
345
+
346
+ // D) When both ready: resolve final SDK config and render
347
+ Promise.all([providerPromise, intentPromise]).then(([providerSdk, intent]) => {
348
+ if (!intent) return;
349
+
350
+ const sdk = resolveClientSdk(intent, providerSdk);
351
+ currentSdk = sdk;
352
+
353
+ // Sandbox mode no SDK to load, UI handles it
354
+ if (sdk.renderType === 'sandbox') return;
355
+
356
+ if (sdk.renderType === 'redirect') {
357
+ window.location.href = intent.clientSecret;
358
+ return;
359
+ }
360
+
361
+ // Iframe mode: listen for postMessage from the /payment-complete callback
362
+ // page that loads inside the iframe after the provider redirects on completion.
363
+ if (sdk.renderType === 'iframe') {
364
+ const handleMessage = (event: MessageEvent) => {
365
+ if (event.origin !== window.location.origin) return;
366
+ if (event.data?.type !== 'brainerce:payment-complete') return;
367
+
368
+ const params = event.data.data as Record<string, string> | undefined;
369
+ if (params?.failed === 'true') {
370
+ setError(t('paymentError'));
371
+ return;
372
+ }
373
+
374
+ // Map provider-specific params to normalized format for
375
+ // server-side verification (e.g. CardCom lowprofilecode → paymentIntentId)
376
+ const lowProfileCode = params?.lowprofilecode || params?.LowProfileCode;
377
+ const normalized: Record<string, unknown> = { ...params };
378
+ if (lowProfileCode) {
379
+ normalized.paymentIntentId = lowProfileCode;
380
+ }
381
+
382
+ // Trigger server-side verification + order creation
383
+ handleSuccess(normalized);
384
+ };
385
+ window.addEventListener('message', handleMessage);
386
+ cleanups.push(() => window.removeEventListener('message', handleMessage));
387
+ return;
388
+ }
389
+
390
+ if (sdk.renderType !== 'sdk-widget' || !sdk.globalName) return;
391
+
392
+ // Store for retryRender from onError callback
393
+ pendingRender = { sdk, intent };
394
+ cbRef.current.retryRender = retryRender;
395
+
396
+ // If SDK wasn't loaded from providers, load + init now
397
+ if (!sdkInitDone) {
398
+ loadScript(sdk);
399
+ // Wait for init to complete, then render once
400
+ const id = setInterval(() => {
401
+ if (sdkInitDone) {
402
+ clearInterval(id);
403
+ renderPayment(sdk, intent);
404
+ }
405
+ }, 100);
406
+ cleanups.push(() => clearInterval(id));
407
+ return;
408
+ }
409
+
410
+ // Re-init with final config if environment changed
411
+ if (sdk.initConfig?.environment && currentSdk) {
412
+ const global = (window as any)[sdk.globalName];
413
+ if (global) {
414
+ const method = sdk.initMethod || 'init';
415
+ global[method]({
416
+ ...(sdk.initConfig || {}),
417
+ events: {
418
+ onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
419
+ onFailure: (r: unknown) => cbRef.current.onFailure(r),
420
+ onError: (r: unknown) => cbRef.current.onError(r),
421
+ onTimeout: () => cbRef.current.onTimeout(),
422
+ onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
423
+ },
424
+ });
425
+ }
426
+ }
427
+
428
+ // SDK ready — render once
429
+ renderPayment(sdk, intent);
430
+ });
431
+
432
+ return () => cleanups.forEach((fn) => fn());
433
+ }, [checkoutId]);
434
+
435
+ // --- UI ---
436
+
437
+ if (loading) {
438
+ return (
439
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
440
+ <LoadingSpinner size="lg" />
441
+ <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
442
+ </div>
443
+ );
444
+ }
445
+
446
+ if (error) {
447
+ const isNotConfigured =
448
+ error.toLowerCase().includes('not configured') ||
449
+ error.toLowerCase().includes('no payment') ||
450
+ error.toLowerCase().includes('provider');
451
+ return (
452
+ <div className={cn('py-12 text-center', className)}>
453
+ <svg
454
+ className="text-muted-foreground mx-auto mb-4 h-12 w-12"
455
+ fill="none"
456
+ viewBox="0 0 24 24"
457
+ stroke="currentColor"
458
+ >
459
+ <path
460
+ strokeLinecap="round"
461
+ strokeLinejoin="round"
462
+ strokeWidth={1.5}
463
+ d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
464
+ />
465
+ </svg>
466
+ <h3 className="text-foreground mb-2 text-lg font-semibold">
467
+ {isNotConfigured ? t('paymentNotConfigured') : t('paymentError')}
468
+ </h3>
469
+ <p className="text-muted-foreground mx-auto max-w-md text-sm">
470
+ {isNotConfigured ? t('paymentNotConfiguredDesc') : error}
471
+ </p>
472
+ </div>
473
+ );
474
+ }
475
+
476
+ if (!paymentIntent) return null;
477
+
478
+ const sdk = resolveClientSdk(paymentIntent, preloadedSdk);
479
+
480
+ if (sdk.renderType === 'sandbox') {
481
+ const handleCompleteSandbox = async () => {
482
+ setLoading(true);
483
+ try {
484
+ const client = getClient();
485
+ await client.completeGuestCheckout(checkoutId);
486
+ window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
487
+ } catch (err) {
488
+ setError(err instanceof Error ? err.message : t('paymentError'));
489
+ setLoading(false);
490
+ }
491
+ };
492
+
493
+ return (
494
+ <div className={cn('py-8 text-center', className)}>
495
+ <div className="mx-auto max-w-md rounded-lg border border-amber-200 bg-amber-50 p-6">
496
+ <svg
497
+ className="mx-auto mb-3 h-10 w-10 text-amber-500"
498
+ fill="none"
499
+ viewBox="0 0 24 24"
500
+ stroke="currentColor"
501
+ >
502
+ <path
503
+ strokeLinecap="round"
504
+ strokeLinejoin="round"
505
+ strokeWidth={1.5}
506
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"
507
+ />
508
+ </svg>
509
+ <h3 className="text-foreground mb-1 text-lg font-semibold">{t('sandboxTitle')}</h3>
510
+ <p className="text-muted-foreground mb-4 text-sm">{t('sandboxDescription')}</p>
511
+ <button
512
+ onClick={handleCompleteSandbox}
513
+ className="inline-flex items-center rounded-md bg-amber-500 px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-amber-600"
514
+ >
515
+ {t('completeTestOrder')}
516
+ </button>
517
+ </div>
518
+ </div>
519
+ );
520
+ }
521
+
522
+ if (sdk.renderType === 'sdk-widget') {
523
+ const containerId =
524
+ sdk.containerId || `${paymentIntent.provider || 'payment'}-payment-container`;
525
+ return (
526
+ <div className={cn('py-4', className)}>
527
+ {!sdkReady && (
528
+ <div className="flex flex-col items-center justify-center py-8">
529
+ <LoadingSpinner size="lg" />
530
+ <p className="text-muted-foreground mt-4 text-sm">{t('loadingPaymentOptions')}</p>
531
+ </div>
532
+ )}
533
+ <div id={containerId} />
534
+ </div>
535
+ );
536
+ }
537
+
538
+ if (sdk.renderType === 'iframe') {
539
+ return (
540
+ <div className={cn('py-4', className)}>
541
+ <iframe
542
+ src={paymentIntent.clientSecret}
543
+ className="w-full border-0"
544
+ style={{ minHeight: '500px' }}
545
+ title={t('payment')}
546
+ allow="payment"
547
+ />
548
+ </div>
549
+ );
550
+ }
551
+
552
+ return (
553
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
554
+ <LoadingSpinner size="lg" />
555
+ <p className="text-muted-foreground mt-4 text-sm">{t('redirectingToPayment')}</p>
556
+ <p className="text-muted-foreground mt-2 text-xs">
557
+ {t('redirectingHint')}
558
+ <a href={paymentIntent.clientSecret} className="text-primary hover:underline">
559
+ {t('clickHere')}
560
+ </a>
561
+ .
562
+ </p>
563
+ </div>
564
+ );
565
+ }