create-brainerce-store 1.83.0 → 1.84.0

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,761 +1,776 @@
1
- 'use client';
2
-
3
- import { useEffect, useState, useRef, useCallback, type CSSProperties } from 'react';
4
- import type { PaymentIntent, PaymentClientSdk } from 'brainerce';
5
- import { formatPrice } from 'brainerce';
6
- import { BrainerceError } from 'brainerce';
7
- import { getClient } from '@/core/lib/brainerce';
8
- import { useTranslations } from '@/core/lib/translations';
9
- import { LoadingSpinner } from '@/ui/shared/loading-spinner';
10
- import { useStoreInfo } from '@/core/providers/store-provider';
11
- import { cn } from '@/core/lib/utils';
12
- import { isAllowedPaymentUrl, isValidCheckoutId, safePaymentRedirect } from '@/core/lib/safe-redirect';
13
-
14
- /**
15
- * Backward-compat defaults when backend doesn't return clientSdk.
16
- */
17
- const LEGACY_GROW_SDK: PaymentClientSdk = {
18
- renderType: 'sdk-widget',
19
- scriptUrl: 'https://cdn.meshulam.co.il/sdk/gs.min.js',
20
- globalName: 'growPayment',
21
- initMethod: 'init',
22
- renderMethod: 'renderPaymentOptions',
23
- containerId: 'grow-payment-container',
24
- initConfig: { version: 1, environment: 'DEV' },
25
- additionalScripts: [
26
- { url: 'https://meshulam.co.il/_media/js/apple_pay_sdk/sdk.min.js', optional: true },
27
- ],
28
- bodyStyles:
29
- '[id*="Gr0W8-"],[id*="Gr0W8-"] *,[class*="Gr0W8-"],[class*="Gr0W8-"] *{direction:ltr !important;text-align:left}',
30
- };
31
-
32
- interface PaymentStepProps {
33
- checkoutId: string;
34
- className?: string;
35
- }
36
-
37
- function resolveClientSdk(
38
- intent: PaymentIntent | null,
39
- preloadedSdk?: PaymentClientSdk | null
40
- ): PaymentClientSdk {
41
- // Runtime SDK (returned by the payment app in the intent) wins over the
42
- // preloaded manifest SDK. This lets a provider return a different renderType
43
- // per-installation (e.g. Cardcom returning 'embedded-fields' when the
44
- // merchant opts in, while the manifest default stays 'iframe').
45
- const fullSdk = [intent?.clientSdk, preloadedSdk].find((s) => s?.renderType);
46
- const runtimeSdk = intent?.clientSdk;
47
- if (fullSdk) {
48
- if (!runtimeSdk || runtimeSdk === fullSdk) return fullSdk;
49
- return {
50
- ...fullSdk,
51
- ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
52
- ...(runtimeSdk.initConfig
53
- ? { initConfig: { ...fullSdk.initConfig, ...runtimeSdk.initConfig } }
54
- : {}),
55
- };
56
- }
57
- const legacy = intent?.provider === 'grow' ? LEGACY_GROW_SDK : null;
58
- if (legacy && runtimeSdk) {
59
- return {
60
- ...legacy,
61
- ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
62
- ...(runtimeSdk.initConfig
63
- ? { initConfig: { ...legacy.initConfig, ...runtimeSdk.initConfig } }
64
- : {}),
65
- };
66
- }
67
- if (legacy) return legacy;
68
- return { renderType: 'redirect' };
69
- }
70
-
71
- function extractMessage(response: unknown): string {
72
- if (typeof response === 'string') return response;
73
- return (response as { message?: string })?.message || '';
74
- }
75
-
76
- export function PaymentStep({ checkoutId, className }: PaymentStepProps) {
77
- const t = useTranslations('checkout');
78
- const { storeInfo } = useStoreInfo();
79
-
80
- const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null);
81
-
82
- // The provider's payment URL. `clientSdk.renderArg` is the URL; `clientSecret`
83
- // is only a fallback for providers that duplicate it there. Reading
84
- // clientSecret alone breaks providers that return a real identifier (MAX,
85
- // Takbull) the iframe/link silently points at an id instead of a page.
86
- const paymentIntentUrl =
87
- paymentIntent?.clientSdk?.renderArg || paymentIntent?.clientSecret || '';
88
- const [preloadedSdk, setPreloadedSdk] = useState<PaymentClientSdk | null>(null);
89
- const [loading, setLoading] = useState(true);
90
- const [error, setError] = useState<string | null>(null);
91
- const [sdkReady, setSdkReady] = useState(false);
92
- // Set by the Cardcom OpenFields embed page via `brainerce:resize` postMessage.
93
- // Presence of this value is how we distinguish our own compact embed page
94
- // from a provider's hosted page — used to narrow the modal + auto-size the
95
- // iframe instead of reserving the tall LowProfile footprint.
96
- const [embeddedIframeHeight, setEmbeddedIframeHeight] = useState<number | null>(null);
97
- const walletOpenRef = useRef(false);
98
- const initialized = useRef(false);
99
-
100
- // Stable refs for SDK event callbacks (avoids stale closures in onload)
101
- const cbRef = useRef({
102
- onSuccess: (_r: unknown) => {},
103
- onFailure: (_r: unknown) => {},
104
- onError: (_r: unknown) => {},
105
- onTimeout: () => {},
106
- onWalletChange: (_s: string) => {},
107
- retryRender: () => {},
108
- });
109
-
110
- const handleSuccess = useCallback(
111
- async (response: unknown) => {
112
- console.info('Payment SDK success:', JSON.stringify(response));
113
- try {
114
- const client = getClient();
115
- const resp = response as Record<string, unknown>;
116
- const data = (resp?.data && typeof resp.data === 'object' ? resp.data : resp) as
117
- | Record<string, unknown>
118
- | undefined;
119
- await client.confirmSdkPayment(checkoutId, data || undefined);
120
- } catch (err) {
121
- console.warn('Failed to confirm payment with backend:', err);
122
- }
123
- window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
124
- },
125
- [checkoutId]
126
- );
127
-
128
- cbRef.current = {
129
- onSuccess: handleSuccess,
130
- onFailure: (response: unknown) => {
131
- console.error('Payment SDK failure:', response);
132
- setError(extractMessage(response) || t('paymentError'));
133
- },
134
- onError: (response: unknown) => {
135
- const TRANSIENT = [
136
- 'Wallet not initialized',
137
- "SDK was not loaded as needed and therefore can't run",
138
- ];
139
- const msg = extractMessage(response);
140
- if (TRANSIENT.some((e) => msg.includes(e))) {
141
- console.info('Payment SDK: transient error, retrying render in 1s:', msg);
142
- setTimeout(() => cbRef.current.retryRender(), 1000);
143
- return;
144
- }
145
- console.error('Payment SDK error:', response);
146
- setError(msg || t('paymentError'));
147
- },
148
- onTimeout: () => {
149
- console.warn('Payment SDK: wallet timed out');
150
- setError(t('paymentTimedOut'));
151
- },
152
- onWalletChange: (state: string) => {
153
- console.info('Payment SDK wallet state:', state);
154
- if (state === 'open') {
155
- walletOpenRef.current = true;
156
- setSdkReady(true);
157
- }
158
- if (state === 'close') setSdkReady(false);
159
- },
160
- retryRender: () => {},
161
- };
162
-
163
- // =========================================================================
164
- // MAIN EFFECT — Follows Grow SDK docs exactly:
165
- //
166
- // Step 1: Load gs.min.js (insertBefore, as docs show)
167
- // Step 2: s.onload → growPayment.init({ environment, version, events })
168
- // This triggers the SDK to load mp.min.js CSS, HTML, params, services
169
- // Step 3: createPaymentIntent (starts wallet timer — should be AFTER init)
170
- // Step 4: growPayment.renderPaymentOptions(authCode)
171
- //
172
- // "call createPaymentProcess right before you need to render the wallet"
173
- // =========================================================================
174
- useEffect(() => {
175
- // Defense in depth: the parent already validates checkoutId from URL
176
- // params, but we re-check here so the component is safe to render in any
177
- // context. Invalid id → no SDK loading, no API calls (error UI below).
178
- if (!isValidCheckoutId(checkoutId)) return;
179
- if (initialized.current) return;
180
- initialized.current = true;
181
-
182
- const client = getClient();
183
- const iframeSuccessUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}`;
184
- const iframeFailedUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}&failed=true`;
185
- const redirectSuccessUrl = `${window.location.origin}/order-confirmation?checkout_id=${checkoutId}`;
186
- const cancelUrl = `${window.location.origin}/checkout?checkout_id=${checkoutId}&canceled=true`;
187
-
188
- let sdkInitDone = false;
189
- let currentSdk: PaymentClientSdk | null = null;
190
- const cleanups: (() => void)[] = [];
191
-
192
- // --- Load SDK script exactly as Grow docs show ---
193
- function loadScript(sdk: PaymentClientSdk) {
194
- if (!sdk.scriptUrl || !sdk.globalName) return;
195
-
196
- // Inject bodyStyles
197
- if (sdk.bodyStyles && !document.querySelector('style[data-payment-sdk]')) {
198
- const style = document.createElement('style');
199
- style.setAttribute('data-payment-sdk', 'true');
200
- style.textContent = sdk.bodyStyles;
201
- document.head.appendChild(style);
202
- cleanups.push(() => style.remove());
203
- }
204
-
205
- // Additional scripts (Apple Pay etc.) — fire and forget
206
- if (sdk.additionalScripts) {
207
- for (const extra of sdk.additionalScripts) {
208
- if (document.querySelector(`script[src="${extra.url}"]`)) continue;
209
- const s = document.createElement('script');
210
- s.type = 'text/javascript';
211
- s.async = true;
212
- s.src = extra.url;
213
- const ref = document.getElementsByTagName('script')[0];
214
- if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
215
- else document.head.appendChild(s);
216
- }
217
- }
218
-
219
- // Already loaded? Init immediately
220
- if ((window as any)[sdk.globalName]) {
221
- initSdk(sdk);
222
- return;
223
- }
224
-
225
- // Already loading (from a previous call)? Wait for it instead of duplicating
226
- if (document.querySelector(`script[src="${sdk.scriptUrl}"]`)) {
227
- const waitId = setInterval(() => {
228
- if ((window as any)[sdk.globalName!]) {
229
- clearInterval(waitId);
230
- initSdk(sdk);
231
- }
232
- }, 100);
233
- cleanups.push(() => clearInterval(waitId));
234
- return;
235
- }
236
-
237
- // Load main SDK — insertBefore first <script> as Grow docs show
238
- const s = document.createElement('script');
239
- s.type = 'text/javascript';
240
- s.async = true;
241
- s.src = sdk.scriptUrl;
242
- s.onload = () => initSdk(sdk); // init DIRECTLY in onload
243
- s.onerror = () => {
244
- console.error('Payment SDK: script load failed');
245
- setError(t('failedToLoadPaymentSdk'));
246
- };
247
- const ref = document.getElementsByTagName('script')[0];
248
- if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
249
- else document.head.appendChild(s);
250
- }
251
-
252
- // --- Init: called in s.onload (as Grow docs require) ---
253
- function initSdk(sdk: PaymentClientSdk) {
254
- if (sdkInitDone) return; // Guard against double init
255
-
256
- const global = (window as any)[sdk.globalName!];
257
- if (!global) {
258
- setError(t('failedToLoadPaymentSdk'));
259
- return;
260
- }
261
-
262
- const method = sdk.initMethod || 'init';
263
- const config = {
264
- ...(sdk.initConfig || {}),
265
- events: {
266
- onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
267
- onFailure: (r: unknown) => cbRef.current.onFailure(r),
268
- onError: (r: unknown) => cbRef.current.onError(r),
269
- onTimeout: () => cbRef.current.onTimeout(),
270
- onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
271
- },
272
- };
273
-
274
- console.info(`Payment SDK: calling ${method}()`);
275
- global[method](config);
276
- sdkInitDone = true;
277
- }
278
-
279
- // --- Render: call once, then safety-net retries if wallet doesn't open ---
280
- // Grow SDK sometimes silently swallows renderPaymentOptions when its
281
- // internal resources (mp.min.js etc.) aren't fully loaded yet.
282
- // Strategy: render once, then retry up to 3 times with increasing delays
283
- // (2s, 3s, 4s) if onWalletChange("open") hasn't fired.
284
- let pendingRender: { sdk: PaymentClientSdk; intent: PaymentIntent } | null = null;
285
- let renderAttempts = 0;
286
- const MAX_RENDER_ATTEMPTS = 4;
287
-
288
- function renderPayment(sdk: PaymentClientSdk, intent: PaymentIntent) {
289
- const global = (window as any)[sdk.globalName!];
290
- if (!global || walletOpenRef.current) return;
291
-
292
- const renderMethod = sdk.renderMethod || 'renderPaymentOptions';
293
- const renderArg = sdk.renderArg || intent.clientSecret;
294
- renderAttempts++;
295
-
296
- try {
297
- global[renderMethod](renderArg);
298
- console.info(`Payment SDK: renderPaymentOptions called (attempt ${renderAttempts})`);
299
- } catch (err) {
300
- console.info('Payment SDK: render threw, will retry in 1s');
301
- }
302
-
303
- // Safety net: if wallet doesn't open within a delay, retry
304
- if (renderAttempts < MAX_RENDER_ATTEMPTS) {
305
- const delay = 1000 + renderAttempts * 1000; // 2s, 3s, 4s
306
- const retryId = setTimeout(() => {
307
- if (!walletOpenRef.current) {
308
- console.info(`Payment SDK: wallet not open after ${delay}ms, retrying render...`);
309
- renderPayment(sdk, intent);
310
- }
311
- }, delay);
312
- cleanups.push(() => clearTimeout(retryId));
313
- }
314
- }
315
-
316
- function retryRender() {
317
- if (pendingRender && !walletOpenRef.current) {
318
- renderPayment(pendingRender.sdk, pendingRender.intent);
319
- }
320
- }
321
-
322
- // =============================================
323
- // Execution flow
324
- // =============================================
325
-
326
- // A) Get SDK config from providers (fast, no wallet timer)
327
- const providerPromise = client
328
- .getPaymentProviders()
329
- .then((res) => {
330
- const sdk = res.defaultProvider?.clientSdk;
331
- if (sdk) setPreloadedSdk(sdk);
332
- return sdk || null;
333
- })
334
- .catch(() => null);
335
-
336
- // B) Load + init SDK as early as possible (skip for sandbox)
337
- providerPromise.then((providerSdk) => {
338
- if (providerSdk?.renderType === 'sandbox') return;
339
- if (providerSdk?.renderType === 'sdk-widget' && providerSdk.scriptUrl) {
340
- currentSdk = providerSdk;
341
- loadScript(providerSdk);
342
- }
343
- });
344
-
345
- // C) Create payment intent (starts wallet timer)
346
- // Wait for provider info so we can choose the right success URL:
347
- // iframe providers redirect inside the iframe to /payment-complete (postMessage),
348
- // redirect providers go straight to /order-confirmation.
349
- const intentPromise = providerPromise
350
- .then((providerSdk) => {
351
- const isIframe = providerSdk?.renderType === 'iframe';
352
- const successUrl = isIframe ? iframeSuccessUrl : redirectSuccessUrl;
353
- const failedUrl = isIframe ? iframeFailedUrl : cancelUrl;
354
- return client.createPaymentIntent(checkoutId, {
355
- successUrl,
356
- cancelUrl: failedUrl,
357
- });
358
- })
359
- .then((intent) => {
360
- setPaymentIntent(intent);
361
- return intent;
362
- })
363
- .catch((err) => {
364
- // This is intent CREATION, before any card is entered, so a failure
365
- // here is the merchant's configuration and never the shopper's card.
366
- // The server said "Stripe account is not connected" and the storefront
367
- // printed it verbatim: raw English on a Hebrew store, naming a provider
368
- // to someone who could not install one if they wanted to. Declines come
369
- // from the provider SDK on a different path and keep their own wording,
370
- // which is the part a shopper can actually act on.
371
- console.error('[checkout] could not start payment', err);
372
- setError(t('paymentUnavailable'));
373
- return null;
374
- })
375
- .finally(() => setLoading(false));
376
-
377
- // D) When both ready: resolve final SDK config and render
378
- Promise.all([providerPromise, intentPromise]).then(([providerSdk, intent]) => {
379
- if (!intent) return;
380
-
381
- const sdk = resolveClientSdk(intent, providerSdk);
382
- currentSdk = sdk;
383
-
384
- // Sandbox mode no SDK to load, UI handles it
385
- if (sdk.renderType === 'sandbox') return;
386
-
387
- // The URL to send the customer to is `renderArg`; `clientSecret` is only
388
- // a fallback for providers that duplicate the URL into it. Reading
389
- // clientSecret first silently breaks any provider that puts a real
390
- // identifier there (MAX, Takbull) — the host check rejects the id and the
391
- // customer never reaches the payment page. Mirrors the sdk-widget branch
392
- // above, which already prefers renderArg.
393
- const paymentUrl = sdk.renderArg || intent.clientSecret;
394
-
395
- if (sdk.renderType === 'redirect') {
396
- if (!isAllowedPaymentUrl(paymentUrl)) {
397
- setError(t('paymentRedirectBlocked'));
398
- return;
399
- }
400
- safePaymentRedirect(paymentUrl);
401
- return;
402
- }
403
-
404
- // Iframe mode: listen for postMessage from either:
405
- // (1) the same-origin /payment-complete callback page after a provider
406
- // redirect (legacy hosted-page flow), OR
407
- // (2) a Brainerce-hosted embed page on an allowlisted payment host
408
- // that wraps provider-specific logic (e.g. Cardcom OpenFields).
409
- if (sdk.renderType === 'iframe') {
410
- if (!isAllowedPaymentUrl(paymentUrl)) {
411
- setError(t('paymentRedirectBlocked'));
412
- return;
413
- }
414
- const iframeOrigin = (() => {
415
- try {
416
- return new URL(paymentUrl).origin;
417
- } catch {
418
- return '';
419
- }
420
- })();
421
- const handleMessage = (event: MessageEvent) => {
422
- const isSameOrigin = event.origin === window.location.origin;
423
- const isTrustedIframe = iframeOrigin && event.origin === iframeOrigin;
424
- if (!isSameOrigin && !isTrustedIframe) return;
425
- if (event.data?.type === 'brainerce:resize') {
426
- const h = Number((event.data as { height?: unknown }).height);
427
- if (Number.isFinite(h) && h > 0 && h < 4000) setEmbeddedIframeHeight(h);
428
- return;
429
- }
430
- // Embed page asking for a top-level redirect (e.g. Bit express-pay).
431
- // We re-validate against the allowlist even though the URL comes
432
- // from an already-trusted iframe — defense in depth.
433
- if (event.data?.type === 'brainerce:redirect') {
434
- const url = String((event.data as { url?: unknown }).url || '');
435
- if (url) safePaymentRedirect(url);
436
- return;
437
- }
438
- if (event.data?.type !== 'brainerce:payment-complete') return;
439
-
440
- const params = event.data.data as Record<string, string> | undefined;
441
- if (params?.failed === 'true') {
442
- setError(t('paymentError'));
443
- return;
444
- }
445
-
446
- // Map provider-specific params to normalized format for
447
- // server-side verification (e.g. CardCom lowprofilecode → paymentIntentId)
448
- const lowProfileCode = params?.lowprofilecode || params?.LowProfileCode;
449
- const normalized: Record<string, unknown> = { ...params };
450
- if (lowProfileCode) {
451
- normalized.paymentIntentId = lowProfileCode;
452
- }
453
-
454
- // Trigger server-side verification + order creation
455
- handleSuccess(normalized);
456
- };
457
- window.addEventListener('message', handleMessage);
458
- cleanups.push(() => window.removeEventListener('message', handleMessage));
459
- return;
460
- }
461
-
462
- if (sdk.renderType !== 'sdk-widget' || !sdk.globalName) return;
463
-
464
- // Store for retryRender from onError callback
465
- pendingRender = { sdk, intent };
466
- cbRef.current.retryRender = retryRender;
467
-
468
- // If SDK wasn't loaded from providers, load + init now
469
- if (!sdkInitDone) {
470
- loadScript(sdk);
471
- // Wait for init to complete, then render once
472
- const id = setInterval(() => {
473
- if (sdkInitDone) {
474
- clearInterval(id);
475
- renderPayment(sdk, intent);
476
- }
477
- }, 100);
478
- cleanups.push(() => clearInterval(id));
479
- return;
480
- }
481
-
482
- // Re-init with final config if environment changed
483
- if (sdk.initConfig?.environment && currentSdk) {
484
- const global = (window as any)[sdk.globalName];
485
- if (global) {
486
- const method = sdk.initMethod || 'init';
487
- global[method]({
488
- ...(sdk.initConfig || {}),
489
- events: {
490
- onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
491
- onFailure: (r: unknown) => cbRef.current.onFailure(r),
492
- onError: (r: unknown) => cbRef.current.onError(r),
493
- onTimeout: () => cbRef.current.onTimeout(),
494
- onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
495
- },
496
- });
497
- }
498
- }
499
-
500
- // SDK ready — render once
501
- renderPayment(sdk, intent);
502
- });
503
-
504
- return () => cleanups.forEach((fn) => fn());
505
- }, [checkoutId]);
506
-
507
- // --- UI ---
508
-
509
- // Invalid checkout id — render the error box instead of ever spinning.
510
- // (Checked after the hooks above so hook order is stable across renders.)
511
- if (!isValidCheckoutId(checkoutId)) {
512
- return (
513
- <div className={cn('border-destructive/50 rounded-md border p-4', className)}>
514
- <p className="text-destructive text-sm">{t('paymentError')}</p>
515
- </div>
516
- );
517
- }
518
-
519
- if (loading) {
520
- return (
521
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
522
- <LoadingSpinner size="lg" />
523
- <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
524
- </div>
525
- );
526
- }
527
-
528
- if (error) {
529
- const isNotConfigured =
530
- error.toLowerCase().includes('not configured') ||
531
- error.toLowerCase().includes('no payment') ||
532
- error.toLowerCase().includes('provider');
533
- return (
534
- <div className={cn('py-12 text-center', className)}>
535
- <svg
536
- className="text-muted-foreground mx-auto mb-4 h-12 w-12"
537
- fill="none"
538
- viewBox="0 0 24 24"
539
- stroke="currentColor"
540
- >
541
- <path
542
- strokeLinecap="round"
543
- strokeLinejoin="round"
544
- strokeWidth={1.5}
545
- 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"
546
- />
547
- </svg>
548
- <h3 className="text-foreground mb-2 text-lg font-semibold">
549
- {isNotConfigured ? t('paymentNotConfigured') : t('paymentError')}
550
- </h3>
551
- <p className="text-muted-foreground mx-auto max-w-md text-sm">
552
- {isNotConfigured ? t('paymentNotConfiguredDesc') : error}
553
- </p>
554
- </div>
555
- );
556
- }
557
-
558
- if (!paymentIntent) return null;
559
-
560
- const sdk = resolveClientSdk(paymentIntent, preloadedSdk);
561
-
562
- if (sdk.renderType === 'sandbox') {
563
- const handleCompleteSandbox = async () => {
564
- setLoading(true);
565
- try {
566
- const client = getClient();
567
- await client.completeGuestCheckout(checkoutId);
568
- window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
569
- } catch (err) {
570
- // Sandbox never declines, so there is nothing here a shopper can act on
571
- // either.
572
- console.error('[checkout] sandbox completion failed', err);
573
- setError(t('paymentError'));
574
- setLoading(false);
575
- }
576
- };
577
-
578
- return (
579
- <div className={cn('py-8 text-center', className)}>
580
- <div className="mx-auto max-w-md rounded-lg border border-amber-200 bg-amber-50 p-6">
581
- <svg
582
- className="mx-auto mb-3 h-10 w-10 text-amber-500"
583
- fill="none"
584
- viewBox="0 0 24 24"
585
- stroke="currentColor"
586
- >
587
- <path
588
- strokeLinecap="round"
589
- strokeLinejoin="round"
590
- strokeWidth={1.5}
591
- 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"
592
- />
593
- </svg>
594
- <h3 className="text-foreground mb-1 text-lg font-semibold">{t('sandboxTitle')}</h3>
595
- <p className="text-muted-foreground mb-4 text-sm">{t('sandboxDescription')}</p>
596
- <button
597
- onClick={handleCompleteSandbox}
598
- 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"
599
- >
600
- {t('completeTestOrder')}
601
- </button>
602
- </div>
603
- </div>
604
- );
605
- }
606
-
607
- if (sdk.renderType === 'sdk-widget') {
608
- const containerId =
609
- sdk.containerId || `${paymentIntent.provider || 'payment'}-payment-container`;
610
- return (
611
- <div className={cn('py-4', className)}>
612
- {!sdkReady && (
613
- <div className="flex flex-col items-center justify-center py-8">
614
- <LoadingSpinner size="lg" />
615
- <p className="text-muted-foreground mt-4 text-sm">{t('loadingPaymentOptions')}</p>
616
- </div>
617
- )}
618
- <div id={containerId} />
619
- </div>
620
- );
621
- }
622
-
623
- if (sdk.renderType === 'iframe') {
624
- if (!isAllowedPaymentUrl(paymentIntent.clientSecret)) return null;
625
-
626
- // Detect Brainerce-hosted embed (path-based — works across localhost/
627
- // staging/prod without a domain list) vs. a provider-hosted page. The
628
- // embed page is already brand-styled and compact → render inline in the
629
- // checkout flow. Provider-hosted pages carry their own branding/chrome →
630
- // keep the modal overlay so they don't fight the checkout layout.
631
- const iframeUrlObj = (() => {
632
- try {
633
- return new URL(paymentIntent.clientSecret);
634
- } catch {
635
- return null;
636
- }
637
- })();
638
- const isBrainerceEmbed = iframeUrlObj?.pathname.includes('/embed/') ?? false;
639
-
640
- if (isBrainerceEmbed) {
641
- // Inline: default to a reasonable height until the embed posts its real
642
- // height via `brainerce:resize`. Transition smooths the resize into the
643
- // final measurement.
644
- const hasMeasured = embeddedIframeHeight !== null;
645
- const iframeStyle: CSSProperties = {
646
- height: hasMeasured ? (embeddedIframeHeight as number) : 540,
647
- transition: hasMeasured ? 'height 0.2s ease-out' : undefined,
648
- };
649
- return (
650
- <div className={cn('w-full', className)}>
651
- <iframe
652
- src={paymentIntentUrl}
653
- className="block w-full border-0"
654
- style={iframeStyle}
655
- title={t('payment')}
656
- allow="payment"
657
- />
658
- </div>
659
- );
660
- }
661
-
662
- // Provider-hosted page (e.g. Cardcom LowProfile with full merchant
663
- // branding) — modal overlay keeps it visually contained.
664
- const formattedAmount = formatPrice((Number(paymentIntent.amount) || 0) / 100, {
665
- currency: paymentIntent.currency,
666
- }) as string;
667
- const iframeStyle: CSSProperties = { height: '90vh', minHeight: 700 };
668
- return (
669
- <>
670
- {/* Modal overlay */}
671
- <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 py-6 backdrop-blur-sm">
672
- <div className="bg-background relative mx-4 flex w-full max-w-4xl flex-col overflow-hidden rounded-2xl shadow-2xl">
673
- {/* Header */}
674
- <div className="border-border flex items-center justify-between gap-4 border-b px-5 py-4">
675
- <div className="flex min-w-0 flex-col">
676
- <span className="text-foreground truncate text-sm font-semibold">
677
- {storeInfo?.name}
678
- </span>
679
- <span className="text-muted-foreground text-xs">{t('payment')}</span>
680
- </div>
681
- <div className="flex items-baseline gap-1.5">
682
- <span className="text-foreground text-lg font-bold tabular-nums">
683
- {formattedAmount}
684
- </span>
685
- <span className="text-muted-foreground text-xs uppercase">
686
- {paymentIntent.currency}
687
- </span>
688
- </div>
689
- <button
690
- onClick={() => {
691
- window.location.href = `/checkout?checkout_id=${checkoutId}&canceled=true`;
692
- }}
693
- className="text-muted-foreground hover:bg-secondary hover:text-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors"
694
- aria-label="Close"
695
- >
696
- <svg
697
- width="14"
698
- height="14"
699
- viewBox="0 0 14 14"
700
- fill="none"
701
- stroke="currentColor"
702
- strokeWidth="2"
703
- strokeLinecap="round"
704
- >
705
- <path d="M1 1l12 12M13 1L1 13" />
706
- </svg>
707
- </button>
708
- </div>
709
- {/* Iframe body */}
710
- <iframe
711
- src={paymentIntentUrl}
712
- className="w-full border-0"
713
- style={iframeStyle}
714
- title={t('payment')}
715
- allow="payment"
716
- />
717
- {/* Footer */}
718
- <div className="border-border bg-secondary/30 text-muted-foreground flex items-center justify-center gap-2 border-t px-5 py-3 text-xs">
719
- <svg
720
- width="14"
721
- height="14"
722
- viewBox="0 0 24 24"
723
- fill="none"
724
- stroke="currentColor"
725
- strokeWidth="2"
726
- strokeLinecap="round"
727
- strokeLinejoin="round"
728
- aria-hidden="true"
729
- >
730
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
731
- <path d="m9 12 2 2 4-4" />
732
- </svg>
733
- <span>
734
- {t('securePayment')} · <span className="font-medium">Brainerce</span>
735
- </span>
736
- </div>
737
- </div>
738
- </div>
739
- {/* Placeholder so the checkout layout doesn't collapse */}
740
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
741
- <LoadingSpinner size="lg" />
742
- <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
743
- </div>
744
- </>
745
- );
746
- }
747
-
748
- return (
749
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
750
- <LoadingSpinner size="lg" />
751
- <p className="text-muted-foreground mt-4 text-sm">{t('redirectingToPayment')}</p>
752
- <p className="text-muted-foreground mt-2 text-xs">
753
- {t('redirectingHint')}
754
- <a href={paymentIntentUrl} className="text-primary hover:underline">
755
- {t('clickHere')}
756
- </a>
757
- .
758
- </p>
759
- </div>
760
- );
761
- }
1
+ 'use client';
2
+
3
+ import { useEffect, useState, useRef, useCallback, type CSSProperties } from 'react';
4
+ import type { PaymentIntent, PaymentClientSdk } from 'brainerce';
5
+ import { formatPrice } from 'brainerce';
6
+ import { BrainerceError } from 'brainerce';
7
+ import { getClient } from '@/core/lib/brainerce';
8
+ import { useTranslations } from '@/core/lib/translations';
9
+ import { LoadingSpinner } from '@/ui/shared/loading-spinner';
10
+ import { useStoreInfo } from '@/core/providers/store-provider';
11
+ import { cn } from '@/core/lib/utils';
12
+ import {
13
+ isAllowedPaymentUrl,
14
+ isValidCheckoutId,
15
+ safePaymentRedirect,
16
+ } from '@/core/lib/safe-redirect';
17
+ import { PREFERRED_RENDER_MODE, resolveRenderType } from '@/core/lib/render-mode';
18
+
19
+ /**
20
+ * Backward-compat defaults when backend doesn't return clientSdk.
21
+ */
22
+ const LEGACY_GROW_SDK: PaymentClientSdk = {
23
+ renderType: 'sdk-widget',
24
+ scriptUrl: 'https://cdn.meshulam.co.il/sdk/gs.min.js',
25
+ globalName: 'growPayment',
26
+ initMethod: 'init',
27
+ renderMethod: 'renderPaymentOptions',
28
+ containerId: 'grow-payment-container',
29
+ initConfig: { version: 1, environment: 'DEV' },
30
+ additionalScripts: [
31
+ { url: 'https://meshulam.co.il/_media/js/apple_pay_sdk/sdk.min.js', optional: true },
32
+ ],
33
+ bodyStyles:
34
+ '[id*="Gr0W8-"],[id*="Gr0W8-"] *,[class*="Gr0W8-"],[class*="Gr0W8-"] *{direction:ltr !important;text-align:left}',
35
+ };
36
+
37
+ interface PaymentStepProps {
38
+ checkoutId: string;
39
+ className?: string;
40
+ }
41
+
42
+ function resolveClientSdk(
43
+ intent: PaymentIntent | null,
44
+ preloadedSdk?: PaymentClientSdk | null
45
+ ): PaymentClientSdk {
46
+ // Runtime SDK (returned by the payment app in the intent) wins over the
47
+ // preloaded manifest SDK. This lets a provider return a different renderType
48
+ // per-installation (e.g. Cardcom returning 'embedded-fields' when the
49
+ // merchant opts in, while the manifest default stays 'iframe').
50
+ const fullSdk = [intent?.clientSdk, preloadedSdk].find((s) => s?.renderType);
51
+ const runtimeSdk = intent?.clientSdk;
52
+ if (fullSdk) {
53
+ if (!runtimeSdk || runtimeSdk === fullSdk) return fullSdk;
54
+ return {
55
+ ...fullSdk,
56
+ ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
57
+ ...(runtimeSdk.initConfig
58
+ ? { initConfig: { ...fullSdk.initConfig, ...runtimeSdk.initConfig } }
59
+ : {}),
60
+ };
61
+ }
62
+ const legacy = intent?.provider === 'grow' ? LEGACY_GROW_SDK : null;
63
+ if (legacy && runtimeSdk) {
64
+ return {
65
+ ...legacy,
66
+ ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
67
+ ...(runtimeSdk.initConfig
68
+ ? { initConfig: { ...legacy.initConfig, ...runtimeSdk.initConfig } }
69
+ : {}),
70
+ };
71
+ }
72
+ if (legacy) return legacy;
73
+ return { renderType: 'redirect' };
74
+ }
75
+
76
+ function extractMessage(response: unknown): string {
77
+ if (typeof response === 'string') return response;
78
+ return (response as { message?: string })?.message || '';
79
+ }
80
+
81
+ export function PaymentStep({ checkoutId, className }: PaymentStepProps) {
82
+ const t = useTranslations('checkout');
83
+ const { storeInfo } = useStoreInfo();
84
+
85
+ const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null);
86
+
87
+ // The provider's payment URL. `clientSdk.renderArg` is the URL; `clientSecret`
88
+ // is only a fallback for providers that duplicate it there. Reading
89
+ // clientSecret alone breaks providers that return a real identifier (MAX,
90
+ // Takbull) the iframe/link silently points at an id instead of a page.
91
+ const paymentIntentUrl = paymentIntent?.clientSdk?.renderArg || paymentIntent?.clientSecret || '';
92
+ const [preloadedSdk, setPreloadedSdk] = useState<PaymentClientSdk | null>(null);
93
+ const [loading, setLoading] = useState(true);
94
+ const [error, setError] = useState<string | null>(null);
95
+ const [sdkReady, setSdkReady] = useState(false);
96
+ // Set by the Cardcom OpenFields embed page via `brainerce:resize` postMessage.
97
+ // Presence of this value is how we distinguish our own compact embed page
98
+ // from a provider's hosted page — used to narrow the modal + auto-size the
99
+ // iframe instead of reserving the tall LowProfile footprint.
100
+ const [embeddedIframeHeight, setEmbeddedIframeHeight] = useState<number | null>(null);
101
+ const walletOpenRef = useRef(false);
102
+ const initialized = useRef(false);
103
+
104
+ // Stable refs for SDK event callbacks (avoids stale closures in onload)
105
+ const cbRef = useRef({
106
+ onSuccess: (_r: unknown) => {},
107
+ onFailure: (_r: unknown) => {},
108
+ onError: (_r: unknown) => {},
109
+ onTimeout: () => {},
110
+ onWalletChange: (_s: string) => {},
111
+ retryRender: () => {},
112
+ });
113
+
114
+ const handleSuccess = useCallback(
115
+ async (response: unknown) => {
116
+ console.info('Payment SDK success:', JSON.stringify(response));
117
+ try {
118
+ const client = getClient();
119
+ const resp = response as Record<string, unknown>;
120
+ const data = (resp?.data && typeof resp.data === 'object' ? resp.data : resp) as
121
+ | Record<string, unknown>
122
+ | undefined;
123
+ await client.confirmSdkPayment(checkoutId, data || undefined);
124
+ } catch (err) {
125
+ console.warn('Failed to confirm payment with backend:', err);
126
+ }
127
+ window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
128
+ },
129
+ [checkoutId]
130
+ );
131
+
132
+ cbRef.current = {
133
+ onSuccess: handleSuccess,
134
+ onFailure: (response: unknown) => {
135
+ console.error('Payment SDK failure:', response);
136
+ setError(extractMessage(response) || t('paymentError'));
137
+ },
138
+ onError: (response: unknown) => {
139
+ const TRANSIENT = [
140
+ 'Wallet not initialized',
141
+ "SDK was not loaded as needed and therefore can't run",
142
+ ];
143
+ const msg = extractMessage(response);
144
+ if (TRANSIENT.some((e) => msg.includes(e))) {
145
+ console.info('Payment SDK: transient error, retrying render in 1s:', msg);
146
+ setTimeout(() => cbRef.current.retryRender(), 1000);
147
+ return;
148
+ }
149
+ console.error('Payment SDK error:', response);
150
+ setError(msg || t('paymentError'));
151
+ },
152
+ onTimeout: () => {
153
+ console.warn('Payment SDK: wallet timed out');
154
+ setError(t('paymentTimedOut'));
155
+ },
156
+ onWalletChange: (state: string) => {
157
+ console.info('Payment SDK wallet state:', state);
158
+ if (state === 'open') {
159
+ walletOpenRef.current = true;
160
+ setSdkReady(true);
161
+ }
162
+ if (state === 'close') setSdkReady(false);
163
+ },
164
+ retryRender: () => {},
165
+ };
166
+
167
+ // =========================================================================
168
+ // MAIN EFFECT Follows Grow SDK docs exactly:
169
+ //
170
+ // Step 1: Load gs.min.js (insertBefore, as docs show)
171
+ // Step 2: s.onload → growPayment.init({ environment, version, events })
172
+ // This triggers the SDK to load mp.min.js CSS, HTML, params, services
173
+ // Step 3: createPaymentIntent (starts wallet timer — should be AFTER init)
174
+ // Step 4: growPayment.renderPaymentOptions(authCode)
175
+ //
176
+ // "call createPaymentProcess right before you need to render the wallet"
177
+ // =========================================================================
178
+ useEffect(() => {
179
+ // Defense in depth: the parent already validates checkoutId from URL
180
+ // params, but we re-check here so the component is safe to render in any
181
+ // context. Invalid id → no SDK loading, no API calls (error UI below).
182
+ if (!isValidCheckoutId(checkoutId)) return;
183
+ if (initialized.current) return;
184
+ initialized.current = true;
185
+
186
+ const client = getClient();
187
+ const iframeSuccessUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}`;
188
+ const iframeFailedUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}&failed=true`;
189
+ const redirectSuccessUrl = `${window.location.origin}/order-confirmation?checkout_id=${checkoutId}`;
190
+ const cancelUrl = `${window.location.origin}/checkout?checkout_id=${checkoutId}&canceled=true`;
191
+
192
+ let sdkInitDone = false;
193
+ let currentSdk: PaymentClientSdk | null = null;
194
+ const cleanups: (() => void)[] = [];
195
+
196
+ // --- Load SDK script exactly as Grow docs show ---
197
+ function loadScript(sdk: PaymentClientSdk) {
198
+ if (!sdk.scriptUrl || !sdk.globalName) return;
199
+
200
+ // Inject bodyStyles
201
+ if (sdk.bodyStyles && !document.querySelector('style[data-payment-sdk]')) {
202
+ const style = document.createElement('style');
203
+ style.setAttribute('data-payment-sdk', 'true');
204
+ style.textContent = sdk.bodyStyles;
205
+ document.head.appendChild(style);
206
+ cleanups.push(() => style.remove());
207
+ }
208
+
209
+ // Additional scripts (Apple Pay etc.) — fire and forget
210
+ if (sdk.additionalScripts) {
211
+ for (const extra of sdk.additionalScripts) {
212
+ if (document.querySelector(`script[src="${extra.url}"]`)) continue;
213
+ const s = document.createElement('script');
214
+ s.type = 'text/javascript';
215
+ s.async = true;
216
+ s.src = extra.url;
217
+ const ref = document.getElementsByTagName('script')[0];
218
+ if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
219
+ else document.head.appendChild(s);
220
+ }
221
+ }
222
+
223
+ // Already loaded? Init immediately
224
+ if ((window as any)[sdk.globalName]) {
225
+ initSdk(sdk);
226
+ return;
227
+ }
228
+
229
+ // Already loading (from a previous call)? Wait for it instead of duplicating
230
+ if (document.querySelector(`script[src="${sdk.scriptUrl}"]`)) {
231
+ const waitId = setInterval(() => {
232
+ if ((window as any)[sdk.globalName!]) {
233
+ clearInterval(waitId);
234
+ initSdk(sdk);
235
+ }
236
+ }, 100);
237
+ cleanups.push(() => clearInterval(waitId));
238
+ return;
239
+ }
240
+
241
+ // Load main SDK — insertBefore first <script> as Grow docs show
242
+ const s = document.createElement('script');
243
+ s.type = 'text/javascript';
244
+ s.async = true;
245
+ s.src = sdk.scriptUrl;
246
+ s.onload = () => initSdk(sdk); // init DIRECTLY in onload
247
+ s.onerror = () => {
248
+ console.error('Payment SDK: script load failed');
249
+ setError(t('failedToLoadPaymentSdk'));
250
+ };
251
+ const ref = document.getElementsByTagName('script')[0];
252
+ if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
253
+ else document.head.appendChild(s);
254
+ }
255
+
256
+ // --- Init: called in s.onload (as Grow docs require) ---
257
+ function initSdk(sdk: PaymentClientSdk) {
258
+ if (sdkInitDone) return; // Guard against double init
259
+
260
+ const global = (window as any)[sdk.globalName!];
261
+ if (!global) {
262
+ setError(t('failedToLoadPaymentSdk'));
263
+ return;
264
+ }
265
+
266
+ const method = sdk.initMethod || 'init';
267
+ const config = {
268
+ ...(sdk.initConfig || {}),
269
+ events: {
270
+ onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
271
+ onFailure: (r: unknown) => cbRef.current.onFailure(r),
272
+ onError: (r: unknown) => cbRef.current.onError(r),
273
+ onTimeout: () => cbRef.current.onTimeout(),
274
+ onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
275
+ },
276
+ };
277
+
278
+ console.info(`Payment SDK: calling ${method}()`);
279
+ global[method](config);
280
+ sdkInitDone = true;
281
+ }
282
+
283
+ // --- Render: call once, then safety-net retries if wallet doesn't open ---
284
+ // Grow SDK sometimes silently swallows renderPaymentOptions when its
285
+ // internal resources (mp.min.js etc.) aren't fully loaded yet.
286
+ // Strategy: render once, then retry up to 3 times with increasing delays
287
+ // (2s, 3s, 4s) if onWalletChange("open") hasn't fired.
288
+ let pendingRender: { sdk: PaymentClientSdk; intent: PaymentIntent } | null = null;
289
+ let renderAttempts = 0;
290
+ const MAX_RENDER_ATTEMPTS = 4;
291
+
292
+ function renderPayment(sdk: PaymentClientSdk, intent: PaymentIntent) {
293
+ const global = (window as any)[sdk.globalName!];
294
+ if (!global || walletOpenRef.current) return;
295
+
296
+ const renderMethod = sdk.renderMethod || 'renderPaymentOptions';
297
+ const renderArg = sdk.renderArg || intent.clientSecret;
298
+ renderAttempts++;
299
+
300
+ try {
301
+ global[renderMethod](renderArg);
302
+ console.info(`Payment SDK: renderPaymentOptions called (attempt ${renderAttempts})`);
303
+ } catch (err) {
304
+ console.info('Payment SDK: render threw, will retry in 1s');
305
+ }
306
+
307
+ // Safety net: if wallet doesn't open within a delay, retry
308
+ if (renderAttempts < MAX_RENDER_ATTEMPTS) {
309
+ const delay = 1000 + renderAttempts * 1000; // 2s, 3s, 4s
310
+ const retryId = setTimeout(() => {
311
+ if (!walletOpenRef.current) {
312
+ console.info(`Payment SDK: wallet not open after ${delay}ms, retrying render...`);
313
+ renderPayment(sdk, intent);
314
+ }
315
+ }, delay);
316
+ cleanups.push(() => clearTimeout(retryId));
317
+ }
318
+ }
319
+
320
+ function retryRender() {
321
+ if (pendingRender && !walletOpenRef.current) {
322
+ renderPayment(pendingRender.sdk, pendingRender.intent);
323
+ }
324
+ }
325
+
326
+ // =============================================
327
+ // Execution flow
328
+ // =============================================
329
+
330
+ // A) Get SDK config from providers (fast, no wallet timer)
331
+ const providerPromise = client
332
+ .getPaymentProviders()
333
+ .then((res) => {
334
+ const sdk = res.defaultProvider?.clientSdk;
335
+ if (sdk) setPreloadedSdk(sdk);
336
+ return sdk || null;
337
+ })
338
+ .catch(() => null);
339
+
340
+ // B) Load + init SDK as early as possible (skip for sandbox)
341
+ providerPromise.then((providerSdk) => {
342
+ if (providerSdk?.renderType === 'sandbox') return;
343
+ if (providerSdk?.renderType === 'sdk-widget' && providerSdk.scriptUrl) {
344
+ currentSdk = providerSdk;
345
+ loadScript(providerSdk);
346
+ }
347
+ });
348
+
349
+ // C) Create payment intent (starts wallet timer)
350
+ // Wait for provider info so we can choose the right success URL:
351
+ // iframe providers redirect inside the iframe to /payment-complete (postMessage),
352
+ // redirect providers go straight to /order-confirmation.
353
+ //
354
+ // The mode is PREDICTED with the platform's own resolution rule
355
+ // (resolveRenderType): the provider's default, unless this storefront asks
356
+ // for a mode the provider declares in `displayModes`. The prediction only
357
+ // picks the return URL; the branch below still reads the `renderType` that
358
+ // comes BACK on the intent, never the prediction.
359
+ const intentPromise = providerPromise
360
+ .then((providerSdk) => {
361
+ const expectedRenderType = resolveRenderType(providerSdk, PREFERRED_RENDER_MODE);
362
+ const isIframe = expectedRenderType === 'iframe';
363
+ const successUrl = isIframe ? iframeSuccessUrl : redirectSuccessUrl;
364
+ const failedUrl = isIframe ? iframeFailedUrl : cancelUrl;
365
+ // `preferredRenderType` is only sent when a preference is set, so a
366
+ // storefront on the provider default sends the same body it always
367
+ // has (and an SDK whose option type predates it still compiles).
368
+ return client.createPaymentIntent(checkoutId, {
369
+ successUrl,
370
+ cancelUrl: failedUrl,
371
+ ...(PREFERRED_RENDER_MODE ? { preferredRenderType: PREFERRED_RENDER_MODE } : {}),
372
+ });
373
+ })
374
+ .then((intent) => {
375
+ setPaymentIntent(intent);
376
+ return intent;
377
+ })
378
+ .catch((err) => {
379
+ // This is intent CREATION, before any card is entered, so a failure
380
+ // here is the merchant's configuration and never the shopper's card.
381
+ // The server said "Stripe account is not connected" and the storefront
382
+ // printed it verbatim: raw English on a Hebrew store, naming a provider
383
+ // to someone who could not install one if they wanted to. Declines come
384
+ // from the provider SDK on a different path and keep their own wording,
385
+ // which is the part a shopper can actually act on.
386
+ console.error('[checkout] could not start payment', err);
387
+ setError(t('paymentUnavailable'));
388
+ return null;
389
+ })
390
+ .finally(() => setLoading(false));
391
+
392
+ // D) When both ready: resolve final SDK config and render
393
+ Promise.all([providerPromise, intentPromise]).then(([providerSdk, intent]) => {
394
+ if (!intent) return;
395
+
396
+ const sdk = resolveClientSdk(intent, providerSdk);
397
+ currentSdk = sdk;
398
+
399
+ // Sandbox mode — no SDK to load, UI handles it
400
+ if (sdk.renderType === 'sandbox') return;
401
+
402
+ // The URL to send the customer to is `renderArg`; `clientSecret` is only
403
+ // a fallback for providers that duplicate the URL into it. Reading
404
+ // clientSecret first silently breaks any provider that puts a real
405
+ // identifier there (MAX, Takbull) the host check rejects the id and the
406
+ // customer never reaches the payment page. Mirrors the sdk-widget branch
407
+ // above, which already prefers renderArg.
408
+ const paymentUrl = sdk.renderArg || intent.clientSecret;
409
+
410
+ if (sdk.renderType === 'redirect') {
411
+ if (!isAllowedPaymentUrl(paymentUrl)) {
412
+ setError(t('paymentRedirectBlocked'));
413
+ return;
414
+ }
415
+ safePaymentRedirect(paymentUrl);
416
+ return;
417
+ }
418
+
419
+ // Iframe mode: listen for postMessage from either:
420
+ // (1) the same-origin /payment-complete callback page after a provider
421
+ // redirect (legacy hosted-page flow), OR
422
+ // (2) a Brainerce-hosted embed page on an allowlisted payment host
423
+ // that wraps provider-specific logic (e.g. Cardcom OpenFields).
424
+ if (sdk.renderType === 'iframe') {
425
+ if (!isAllowedPaymentUrl(paymentUrl)) {
426
+ setError(t('paymentRedirectBlocked'));
427
+ return;
428
+ }
429
+ const iframeOrigin = (() => {
430
+ try {
431
+ return new URL(paymentUrl).origin;
432
+ } catch {
433
+ return '';
434
+ }
435
+ })();
436
+ const handleMessage = (event: MessageEvent) => {
437
+ const isSameOrigin = event.origin === window.location.origin;
438
+ const isTrustedIframe = iframeOrigin && event.origin === iframeOrigin;
439
+ if (!isSameOrigin && !isTrustedIframe) return;
440
+ if (event.data?.type === 'brainerce:resize') {
441
+ const h = Number((event.data as { height?: unknown }).height);
442
+ if (Number.isFinite(h) && h > 0 && h < 4000) setEmbeddedIframeHeight(h);
443
+ return;
444
+ }
445
+ // Embed page asking for a top-level redirect (e.g. Bit express-pay).
446
+ // We re-validate against the allowlist even though the URL comes
447
+ // from an already-trusted iframe defense in depth.
448
+ if (event.data?.type === 'brainerce:redirect') {
449
+ const url = String((event.data as { url?: unknown }).url || '');
450
+ if (url) safePaymentRedirect(url);
451
+ return;
452
+ }
453
+ if (event.data?.type !== 'brainerce:payment-complete') return;
454
+
455
+ const params = event.data.data as Record<string, string> | undefined;
456
+ if (params?.failed === 'true') {
457
+ setError(t('paymentError'));
458
+ return;
459
+ }
460
+
461
+ // Map provider-specific params to normalized format for
462
+ // server-side verification (e.g. CardCom lowprofilecode paymentIntentId)
463
+ const lowProfileCode = params?.lowprofilecode || params?.LowProfileCode;
464
+ const normalized: Record<string, unknown> = { ...params };
465
+ if (lowProfileCode) {
466
+ normalized.paymentIntentId = lowProfileCode;
467
+ }
468
+
469
+ // Trigger server-side verification + order creation
470
+ handleSuccess(normalized);
471
+ };
472
+ window.addEventListener('message', handleMessage);
473
+ cleanups.push(() => window.removeEventListener('message', handleMessage));
474
+ return;
475
+ }
476
+
477
+ if (sdk.renderType !== 'sdk-widget' || !sdk.globalName) return;
478
+
479
+ // Store for retryRender from onError callback
480
+ pendingRender = { sdk, intent };
481
+ cbRef.current.retryRender = retryRender;
482
+
483
+ // If SDK wasn't loaded from providers, load + init now
484
+ if (!sdkInitDone) {
485
+ loadScript(sdk);
486
+ // Wait for init to complete, then render once
487
+ const id = setInterval(() => {
488
+ if (sdkInitDone) {
489
+ clearInterval(id);
490
+ renderPayment(sdk, intent);
491
+ }
492
+ }, 100);
493
+ cleanups.push(() => clearInterval(id));
494
+ return;
495
+ }
496
+
497
+ // Re-init with final config if environment changed
498
+ if (sdk.initConfig?.environment && currentSdk) {
499
+ const global = (window as any)[sdk.globalName];
500
+ if (global) {
501
+ const method = sdk.initMethod || 'init';
502
+ global[method]({
503
+ ...(sdk.initConfig || {}),
504
+ events: {
505
+ onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
506
+ onFailure: (r: unknown) => cbRef.current.onFailure(r),
507
+ onError: (r: unknown) => cbRef.current.onError(r),
508
+ onTimeout: () => cbRef.current.onTimeout(),
509
+ onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
510
+ },
511
+ });
512
+ }
513
+ }
514
+
515
+ // SDK ready — render once
516
+ renderPayment(sdk, intent);
517
+ });
518
+
519
+ return () => cleanups.forEach((fn) => fn());
520
+ }, [checkoutId]);
521
+
522
+ // --- UI ---
523
+
524
+ // Invalid checkout id — render the error box instead of ever spinning.
525
+ // (Checked after the hooks above so hook order is stable across renders.)
526
+ if (!isValidCheckoutId(checkoutId)) {
527
+ return (
528
+ <div className={cn('border-destructive/50 rounded-md border p-4', className)}>
529
+ <p className="text-destructive text-sm">{t('paymentError')}</p>
530
+ </div>
531
+ );
532
+ }
533
+
534
+ if (loading) {
535
+ return (
536
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
537
+ <LoadingSpinner size="lg" />
538
+ <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
539
+ </div>
540
+ );
541
+ }
542
+
543
+ if (error) {
544
+ const isNotConfigured =
545
+ error.toLowerCase().includes('not configured') ||
546
+ error.toLowerCase().includes('no payment') ||
547
+ error.toLowerCase().includes('provider');
548
+ return (
549
+ <div className={cn('py-12 text-center', className)}>
550
+ <svg
551
+ className="text-muted-foreground mx-auto mb-4 h-12 w-12"
552
+ fill="none"
553
+ viewBox="0 0 24 24"
554
+ stroke="currentColor"
555
+ >
556
+ <path
557
+ strokeLinecap="round"
558
+ strokeLinejoin="round"
559
+ strokeWidth={1.5}
560
+ 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"
561
+ />
562
+ </svg>
563
+ <h3 className="text-foreground mb-2 text-lg font-semibold">
564
+ {isNotConfigured ? t('paymentNotConfigured') : t('paymentError')}
565
+ </h3>
566
+ <p className="text-muted-foreground mx-auto max-w-md text-sm">
567
+ {isNotConfigured ? t('paymentNotConfiguredDesc') : error}
568
+ </p>
569
+ </div>
570
+ );
571
+ }
572
+
573
+ if (!paymentIntent) return null;
574
+
575
+ const sdk = resolveClientSdk(paymentIntent, preloadedSdk);
576
+
577
+ if (sdk.renderType === 'sandbox') {
578
+ const handleCompleteSandbox = async () => {
579
+ setLoading(true);
580
+ try {
581
+ const client = getClient();
582
+ await client.completeGuestCheckout(checkoutId);
583
+ window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
584
+ } catch (err) {
585
+ // Sandbox never declines, so there is nothing here a shopper can act on
586
+ // either.
587
+ console.error('[checkout] sandbox completion failed', err);
588
+ setError(t('paymentError'));
589
+ setLoading(false);
590
+ }
591
+ };
592
+
593
+ return (
594
+ <div className={cn('py-8 text-center', className)}>
595
+ <div className="mx-auto max-w-md rounded-lg border border-amber-200 bg-amber-50 p-6">
596
+ <svg
597
+ className="mx-auto mb-3 h-10 w-10 text-amber-500"
598
+ fill="none"
599
+ viewBox="0 0 24 24"
600
+ stroke="currentColor"
601
+ >
602
+ <path
603
+ strokeLinecap="round"
604
+ strokeLinejoin="round"
605
+ strokeWidth={1.5}
606
+ 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"
607
+ />
608
+ </svg>
609
+ <h3 className="text-foreground mb-1 text-lg font-semibold">{t('sandboxTitle')}</h3>
610
+ <p className="text-muted-foreground mb-4 text-sm">{t('sandboxDescription')}</p>
611
+ <button
612
+ onClick={handleCompleteSandbox}
613
+ 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"
614
+ >
615
+ {t('completeTestOrder')}
616
+ </button>
617
+ </div>
618
+ </div>
619
+ );
620
+ }
621
+
622
+ if (sdk.renderType === 'sdk-widget') {
623
+ const containerId =
624
+ sdk.containerId || `${paymentIntent.provider || 'payment'}-payment-container`;
625
+ return (
626
+ <div className={cn('py-4', className)}>
627
+ {!sdkReady && (
628
+ <div className="flex flex-col items-center justify-center py-8">
629
+ <LoadingSpinner size="lg" />
630
+ <p className="text-muted-foreground mt-4 text-sm">{t('loadingPaymentOptions')}</p>
631
+ </div>
632
+ )}
633
+ <div id={containerId} />
634
+ </div>
635
+ );
636
+ }
637
+
638
+ if (sdk.renderType === 'iframe') {
639
+ if (!isAllowedPaymentUrl(paymentIntent.clientSecret)) return null;
640
+
641
+ // Detect Brainerce-hosted embed (path-based works across localhost/
642
+ // staging/prod without a domain list) vs. a provider-hosted page. The
643
+ // embed page is already brand-styled and compact → render inline in the
644
+ // checkout flow. Provider-hosted pages carry their own branding/chrome →
645
+ // keep the modal overlay so they don't fight the checkout layout.
646
+ const iframeUrlObj = (() => {
647
+ try {
648
+ return new URL(paymentIntent.clientSecret);
649
+ } catch {
650
+ return null;
651
+ }
652
+ })();
653
+ const isBrainerceEmbed = iframeUrlObj?.pathname.includes('/embed/') ?? false;
654
+
655
+ if (isBrainerceEmbed) {
656
+ // Inline: default to a reasonable height until the embed posts its real
657
+ // height via `brainerce:resize`. Transition smooths the resize into the
658
+ // final measurement.
659
+ const hasMeasured = embeddedIframeHeight !== null;
660
+ const iframeStyle: CSSProperties = {
661
+ height: hasMeasured ? (embeddedIframeHeight as number) : 540,
662
+ transition: hasMeasured ? 'height 0.2s ease-out' : undefined,
663
+ };
664
+ return (
665
+ <div className={cn('w-full', className)}>
666
+ <iframe
667
+ src={paymentIntentUrl}
668
+ className="block w-full border-0"
669
+ style={iframeStyle}
670
+ title={t('payment')}
671
+ allow="payment"
672
+ />
673
+ </div>
674
+ );
675
+ }
676
+
677
+ // Provider-hosted page (e.g. Cardcom LowProfile with full merchant
678
+ // branding) — modal overlay keeps it visually contained.
679
+ const formattedAmount = formatPrice((Number(paymentIntent.amount) || 0) / 100, {
680
+ currency: paymentIntent.currency,
681
+ }) as string;
682
+ const iframeStyle: CSSProperties = { height: '90vh', minHeight: 700 };
683
+ return (
684
+ <>
685
+ {/* Modal overlay */}
686
+ <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 py-6 backdrop-blur-sm">
687
+ <div className="bg-background relative mx-4 flex w-full max-w-4xl flex-col overflow-hidden rounded-2xl shadow-2xl">
688
+ {/* Header */}
689
+ <div className="border-border flex items-center justify-between gap-4 border-b px-5 py-4">
690
+ <div className="flex min-w-0 flex-col">
691
+ <span className="text-foreground truncate text-sm font-semibold">
692
+ {storeInfo?.name}
693
+ </span>
694
+ <span className="text-muted-foreground text-xs">{t('payment')}</span>
695
+ </div>
696
+ <div className="flex items-baseline gap-1.5">
697
+ <span className="text-foreground text-lg font-bold tabular-nums">
698
+ {formattedAmount}
699
+ </span>
700
+ <span className="text-muted-foreground text-xs uppercase">
701
+ {paymentIntent.currency}
702
+ </span>
703
+ </div>
704
+ <button
705
+ onClick={() => {
706
+ window.location.href = `/checkout?checkout_id=${checkoutId}&canceled=true`;
707
+ }}
708
+ className="text-muted-foreground hover:bg-secondary hover:text-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors"
709
+ aria-label="Close"
710
+ >
711
+ <svg
712
+ width="14"
713
+ height="14"
714
+ viewBox="0 0 14 14"
715
+ fill="none"
716
+ stroke="currentColor"
717
+ strokeWidth="2"
718
+ strokeLinecap="round"
719
+ >
720
+ <path d="M1 1l12 12M13 1L1 13" />
721
+ </svg>
722
+ </button>
723
+ </div>
724
+ {/* Iframe body */}
725
+ <iframe
726
+ src={paymentIntentUrl}
727
+ className="w-full border-0"
728
+ style={iframeStyle}
729
+ title={t('payment')}
730
+ allow="payment"
731
+ />
732
+ {/* Footer */}
733
+ <div className="border-border bg-secondary/30 text-muted-foreground flex items-center justify-center gap-2 border-t px-5 py-3 text-xs">
734
+ <svg
735
+ width="14"
736
+ height="14"
737
+ viewBox="0 0 24 24"
738
+ fill="none"
739
+ stroke="currentColor"
740
+ strokeWidth="2"
741
+ strokeLinecap="round"
742
+ strokeLinejoin="round"
743
+ aria-hidden="true"
744
+ >
745
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
746
+ <path d="m9 12 2 2 4-4" />
747
+ </svg>
748
+ <span>
749
+ {t('securePayment')} · <span className="font-medium">Brainerce</span>
750
+ </span>
751
+ </div>
752
+ </div>
753
+ </div>
754
+ {/* Placeholder so the checkout layout doesn't collapse */}
755
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
756
+ <LoadingSpinner size="lg" />
757
+ <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
758
+ </div>
759
+ </>
760
+ );
761
+ }
762
+
763
+ return (
764
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
765
+ <LoadingSpinner size="lg" />
766
+ <p className="text-muted-foreground mt-4 text-sm">{t('redirectingToPayment')}</p>
767
+ <p className="text-muted-foreground mt-2 text-xs">
768
+ {t('redirectingHint')}
769
+ <a href={paymentIntentUrl} className="text-primary hover:underline">
770
+ {t('clickHere')}
771
+ </a>
772
+ .
773
+ </p>
774
+ </div>
775
+ );
776
+ }