@clickmax/checkout-react 0.0.0-stage → 12.5.3
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.
- package/LICENSE +201 -0
- package/README.md +133 -2
- package/dist/index.d.ts +2405 -0
- package/dist/index.js +2822 -0
- package/dist/theme.css +147 -0
- package/package.json +63 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2822 @@
|
|
|
1
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Where and how the checkout calls the payments API. Every call goes through one base URL, so a
|
|
8
|
+
* site can route them through its own origin (a same-domain proxy) instead of a separate host.
|
|
9
|
+
*/ /** A non-2xx answer or a network failure of a checkout API call. */ class CheckoutApiError extends Error {
|
|
10
|
+
/** HTTP status, or `0` when the request never got an answer. */ status;
|
|
11
|
+
/** Machine-readable code from the API body, when it sends one. */ code;
|
|
12
|
+
/** Parsed response body, when it is JSON. */ body;
|
|
13
|
+
constructor(init){
|
|
14
|
+
super(init.message);
|
|
15
|
+
this.name = 'CheckoutApiError';
|
|
16
|
+
this.status = init.status;
|
|
17
|
+
this.code = init.code;
|
|
18
|
+
this.body = init.body;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function joinUrl(baseUrl, path) {
|
|
22
|
+
return `${baseUrl.replace(/\/+$/, '')}${path.startsWith('/') ? path : `/${path}`}`;
|
|
23
|
+
}
|
|
24
|
+
function readError(status, body) {
|
|
25
|
+
const record = body && typeof body === 'object' ? body : undefined;
|
|
26
|
+
const message = typeof record?.message === 'string' && record.message ? record.message : `Checkout request failed with status ${status}`;
|
|
27
|
+
const code = typeof record?.code === 'string' ? record.code : typeof record?.error === 'string' ? record.error : undefined;
|
|
28
|
+
return new CheckoutApiError({
|
|
29
|
+
status,
|
|
30
|
+
message,
|
|
31
|
+
code,
|
|
32
|
+
body
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Orval mutator used by every generated checkout operation. Orval counts this function's
|
|
37
|
+
* parameters to type `options`, so it must keep exactly two.
|
|
38
|
+
*
|
|
39
|
+
* @param url Path and query relative to the base URL, such as `/checkout/offer/public?offer=x`.
|
|
40
|
+
* @param options Method and body from the generated code plus the transport.
|
|
41
|
+
*/ async function http(url, options) {
|
|
42
|
+
const { transport } = options;
|
|
43
|
+
if (!transport) throw new TypeError('Checkout operation called without a transport');
|
|
44
|
+
const headers = new Headers(transport.headers);
|
|
45
|
+
for (const [name, value] of new Headers(options.headers))headers.set(name, value);
|
|
46
|
+
if (!headers.has('accept')) headers.set('accept', 'application/json');
|
|
47
|
+
if (options.body !== undefined && !headers.has('content-type')) {
|
|
48
|
+
headers.set('content-type', 'application/json');
|
|
49
|
+
}
|
|
50
|
+
// Called through a local: browser `fetch` throws "Illegal invocation" when `this` is not `window`.
|
|
51
|
+
const fetchFn = transport.fetch ?? globalThis.fetch;
|
|
52
|
+
let response;
|
|
53
|
+
try {
|
|
54
|
+
response = await fetchFn(joinUrl(transport.baseUrl, url), {
|
|
55
|
+
method: options.method ?? 'GET',
|
|
56
|
+
headers,
|
|
57
|
+
body: options.body,
|
|
58
|
+
credentials: transport.credentials ?? 'same-origin',
|
|
59
|
+
signal: options.signal
|
|
60
|
+
});
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error instanceof DOMException && error.name === 'AbortError') throw error;
|
|
63
|
+
throw new CheckoutApiError({
|
|
64
|
+
status: 0,
|
|
65
|
+
message: error instanceof Error ? error.message : 'Network error'
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const text = await response.text();
|
|
69
|
+
let body = text;
|
|
70
|
+
if (text) {
|
|
71
|
+
try {
|
|
72
|
+
body = JSON.parse(text);
|
|
73
|
+
} catch {
|
|
74
|
+
// Not JSON: keep the raw text so the error still carries it.
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (!response.ok) throw readError(response.status, body);
|
|
78
|
+
return text ? body : undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
const getOfferCheckoutUrl = ()=>{
|
|
83
|
+
return `/checkout/offer`;
|
|
84
|
+
};
|
|
85
|
+
const offerCheckout = async (offerCheckoutBody, options)=>{
|
|
86
|
+
const getHeaders = (h)=>{
|
|
87
|
+
if (!h) return {};
|
|
88
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
89
|
+
if (Symbol.iterator in h) {
|
|
90
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
91
|
+
}
|
|
92
|
+
const headers = {};
|
|
93
|
+
for (const [name, value] of Object.entries(h)){
|
|
94
|
+
if (value !== undefined) headers[name] = value;
|
|
95
|
+
}
|
|
96
|
+
return headers;
|
|
97
|
+
};
|
|
98
|
+
return http(getOfferCheckoutUrl(), {
|
|
99
|
+
...options,
|
|
100
|
+
method: 'POST',
|
|
101
|
+
headers: {
|
|
102
|
+
'Content-Type': 'application/json',
|
|
103
|
+
...getHeaders(options?.headers)
|
|
104
|
+
},
|
|
105
|
+
body: JSON.stringify(offerCheckoutBody)
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
const getGetPublicOfferCheckoutUrl = (params)=>{
|
|
109
|
+
const normalizedParams = new URLSearchParams();
|
|
110
|
+
Object.entries(params || {}).forEach(([key, value])=>{
|
|
111
|
+
if (value !== undefined) {
|
|
112
|
+
normalizedParams.append(key, value === null ? 'null' : String(value));
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
const stringifiedParams = normalizedParams.toString();
|
|
116
|
+
return stringifiedParams.length > 0 ? `/checkout/offer/public?${stringifiedParams}` : `/checkout/offer/public`;
|
|
117
|
+
};
|
|
118
|
+
const getPublicOfferCheckout = async (params, options)=>{
|
|
119
|
+
return http(getGetPublicOfferCheckoutUrl(params), {
|
|
120
|
+
...options,
|
|
121
|
+
method: 'GET'
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
const getGetOfferCheckoutVisitorUrl = (params)=>{
|
|
125
|
+
const normalizedParams = new URLSearchParams();
|
|
126
|
+
Object.entries(params || {}).forEach(([key, value])=>{
|
|
127
|
+
if (value !== undefined) {
|
|
128
|
+
normalizedParams.append(key, value === null ? 'null' : String(value));
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
const stringifiedParams = normalizedParams.toString();
|
|
132
|
+
return stringifiedParams.length > 0 ? `/checkout/offer/visitor?${stringifiedParams}` : `/checkout/offer/visitor`;
|
|
133
|
+
};
|
|
134
|
+
const getOfferCheckoutVisitor = async (params, options)=>{
|
|
135
|
+
return http(getGetOfferCheckoutVisitorUrl(params), {
|
|
136
|
+
...options,
|
|
137
|
+
method: 'GET'
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
const getGetCheckoutCsrfTokenUrl = ()=>{
|
|
141
|
+
return `/checkout/csrf-token`;
|
|
142
|
+
};
|
|
143
|
+
const getCheckoutCsrfToken = async (options)=>{
|
|
144
|
+
return http(getGetCheckoutCsrfTokenUrl(), {
|
|
145
|
+
...options,
|
|
146
|
+
method: 'GET'
|
|
147
|
+
});
|
|
148
|
+
};
|
|
149
|
+
const getGetCheckoutStatusUrl = (id)=>{
|
|
150
|
+
return `/checkout/offer/status/${encodeURIComponent(String(id))}`;
|
|
151
|
+
};
|
|
152
|
+
const getCheckoutStatus = async (id, options)=>{
|
|
153
|
+
return http(getGetCheckoutStatusUrl(id), {
|
|
154
|
+
...options,
|
|
155
|
+
method: 'GET'
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
const getGetCheckoutDetailsUrl = (id)=>{
|
|
159
|
+
return `/checkout/offer/${encodeURIComponent(String(id))}`;
|
|
160
|
+
};
|
|
161
|
+
const getCheckoutDetails = async (id, options)=>{
|
|
162
|
+
return http(getGetCheckoutDetailsUrl(id), {
|
|
163
|
+
...options,
|
|
164
|
+
method: 'GET'
|
|
165
|
+
});
|
|
166
|
+
};
|
|
167
|
+
const getValidateCheckoutCouponUrl = ()=>{
|
|
168
|
+
return `/checkout/coupon/validate`;
|
|
169
|
+
};
|
|
170
|
+
const validateCheckoutCoupon = async (validateCheckoutCouponBody, options)=>{
|
|
171
|
+
const getHeaders = (h)=>{
|
|
172
|
+
if (!h) return {};
|
|
173
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
174
|
+
if (Symbol.iterator in h) {
|
|
175
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
176
|
+
}
|
|
177
|
+
const headers = {};
|
|
178
|
+
for (const [name, value] of Object.entries(h)){
|
|
179
|
+
if (value !== undefined) headers[name] = value;
|
|
180
|
+
}
|
|
181
|
+
return headers;
|
|
182
|
+
};
|
|
183
|
+
return http(getValidateCheckoutCouponUrl(), {
|
|
184
|
+
...options,
|
|
185
|
+
method: 'POST',
|
|
186
|
+
headers: {
|
|
187
|
+
'Content-Type': 'application/json',
|
|
188
|
+
...getHeaders(options?.headers)
|
|
189
|
+
},
|
|
190
|
+
body: JSON.stringify(validateCheckoutCouponBody)
|
|
191
|
+
});
|
|
192
|
+
};
|
|
193
|
+
const getGetCheckoutPricingUrl = ()=>{
|
|
194
|
+
return `/checkout/pricing`;
|
|
195
|
+
};
|
|
196
|
+
const getCheckoutPricing = async (getCheckoutPricingBody, options)=>{
|
|
197
|
+
const getHeaders = (h)=>{
|
|
198
|
+
if (!h) return {};
|
|
199
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
200
|
+
if (Symbol.iterator in h) {
|
|
201
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
202
|
+
}
|
|
203
|
+
const headers = {};
|
|
204
|
+
for (const [name, value] of Object.entries(h)){
|
|
205
|
+
if (value !== undefined) headers[name] = value;
|
|
206
|
+
}
|
|
207
|
+
return headers;
|
|
208
|
+
};
|
|
209
|
+
return http(getGetCheckoutPricingUrl(), {
|
|
210
|
+
...options,
|
|
211
|
+
method: 'POST',
|
|
212
|
+
headers: {
|
|
213
|
+
'Content-Type': 'application/json',
|
|
214
|
+
...getHeaders(options?.headers)
|
|
215
|
+
},
|
|
216
|
+
body: JSON.stringify(getCheckoutPricingBody)
|
|
217
|
+
});
|
|
218
|
+
};
|
|
219
|
+
const getGetOfferFreightQuoteUrl = (offerHash, zipCode)=>{
|
|
220
|
+
return `/checkout/freight/${encodeURIComponent(String(offerHash))}/${encodeURIComponent(String(zipCode))}`;
|
|
221
|
+
};
|
|
222
|
+
const getOfferFreightQuote = async (offerHash, zipCode, options)=>{
|
|
223
|
+
return http(getGetOfferFreightQuoteUrl(offerHash, zipCode), {
|
|
224
|
+
...options,
|
|
225
|
+
method: 'GET'
|
|
226
|
+
});
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
function publicOfferQuery({ bumps, bumpTitle, mode, ...rest }) {
|
|
231
|
+
const query = {
|
|
232
|
+
...rest
|
|
233
|
+
};
|
|
234
|
+
// An empty list declares nothing: the route reads a non-empty list, and a page with no
|
|
235
|
+
// `pageId` already has no bumps.
|
|
236
|
+
if (bumps && bumps.length > 0) {
|
|
237
|
+
// Comma lists, the format the route reads: one stable URL (and cache key) per declaration.
|
|
238
|
+
query.bumps = bumps.map((bump)=>bump.offer).join(',');
|
|
239
|
+
const required = bumps.filter((bump)=>bump.required).map((bump)=>bump.offer);
|
|
240
|
+
if (required.length > 0) query.requiredBumps = required.join(',');
|
|
241
|
+
}
|
|
242
|
+
if (bumpTitle?.trim()) query.bumpTitle = bumpTitle.trim();
|
|
243
|
+
if (mode) query.mode = mode;
|
|
244
|
+
return query;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Creates a {@link CheckoutApi} bound to a transport.
|
|
248
|
+
*
|
|
249
|
+
* @param transport Base URL and fetch settings of every call.
|
|
250
|
+
*/ function createCheckoutApi(transport) {
|
|
251
|
+
if (typeof transport?.baseUrl !== 'string' || transport.baseUrl === '') {
|
|
252
|
+
throw new TypeError('createCheckoutApi: transport.baseUrl is required');
|
|
253
|
+
}
|
|
254
|
+
const call = (options)=>({
|
|
255
|
+
transport,
|
|
256
|
+
signal: options?.signal
|
|
257
|
+
});
|
|
258
|
+
return {
|
|
259
|
+
getPublicOffer: (params, options)=>getPublicOfferCheckout(publicOfferQuery(params), call(options)),
|
|
260
|
+
getVisitor: ({ offer, affiliateHash }, options)=>getOfferCheckoutVisitor(affiliateHash ? {
|
|
261
|
+
offer,
|
|
262
|
+
a: affiliateHash
|
|
263
|
+
} : {
|
|
264
|
+
offer
|
|
265
|
+
}, call(options)),
|
|
266
|
+
getPricing: (body, options)=>getCheckoutPricing(body, call(options)),
|
|
267
|
+
validateCoupon: (body, options)=>validateCheckoutCoupon(body, call(options)),
|
|
268
|
+
getFreightQuote: ({ offerHash, zipCode }, options)=>getOfferFreightQuote(offerHash, zipCode, call(options)),
|
|
269
|
+
getCsrfToken: async (options)=>(await getCheckoutCsrfToken(call(options))).csrfToken,
|
|
270
|
+
purchase: (body, { idempotencyKey, csrfToken }, options)=>offerCheckout(body, {
|
|
271
|
+
...call(options),
|
|
272
|
+
headers: {
|
|
273
|
+
'idempotency-key': idempotencyKey,
|
|
274
|
+
'x-csrf-token': csrfToken
|
|
275
|
+
}
|
|
276
|
+
}),
|
|
277
|
+
getPurchaseStatus: (jobId, options)=>getCheckoutStatus(jobId, call(options)),
|
|
278
|
+
getPurchaseDetails: (transactionId, options)=>getCheckoutDetails(transactionId, call(options))
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
// Parent half of the Elements `postMessage` contract used by the card frame in the payments web
|
|
285
|
+
// app (frame-only helpers left out). Both sides must keep the same `ELEMENTS_PROTOCOL_VERSION` and
|
|
286
|
+
// message shapes; the frame ignores any other version.
|
|
287
|
+
//
|
|
288
|
+
// PCI rule this contract keeps: no message from the frame to the page carries the card number,
|
|
289
|
+
// expiry or CVC. The frame returns validation state and, on `tokenize`, an opaque card id plus the
|
|
290
|
+
// first 6 and last 4 digits, which PCI allows outside the card environment.
|
|
291
|
+
const ELEMENTS_PROTOCOL = 'clickmax-elements';
|
|
292
|
+
const ELEMENTS_PROTOCOL_VERSION = 1;
|
|
293
|
+
const FRAME_TO_PARENT_TYPES = new Set([
|
|
294
|
+
'hello',
|
|
295
|
+
'ready',
|
|
296
|
+
'change',
|
|
297
|
+
'focus',
|
|
298
|
+
'blur',
|
|
299
|
+
'escape',
|
|
300
|
+
'resize',
|
|
301
|
+
'loaderror',
|
|
302
|
+
'tokenize-result',
|
|
303
|
+
'tokenize-error'
|
|
304
|
+
]);
|
|
305
|
+
function envelope(channel, type, payload) {
|
|
306
|
+
return {
|
|
307
|
+
protocol: ELEMENTS_PROTOCOL,
|
|
308
|
+
v: ELEMENTS_PROTOCOL_VERSION,
|
|
309
|
+
channel,
|
|
310
|
+
type,
|
|
311
|
+
payload
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
/** Mensagem do pai para o iframe; `type` escolhe o formato de `payload`. */ function parentMessage(channel, type, payload) {
|
|
315
|
+
return envelope(channel, type, payload);
|
|
316
|
+
}
|
|
317
|
+
function isEnvelope(data, channel) {
|
|
318
|
+
if (!data || typeof data !== 'object') return false;
|
|
319
|
+
const message = data;
|
|
320
|
+
return message.protocol === ELEMENTS_PROTOCOL && message.v === ELEMENTS_PROTOCOL_VERSION && message.channel === channel && typeof message.type === 'string' && typeof message.payload === 'object' && message.payload !== null;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Aceita uma mensagem só se origem, janela de origem, protocolo, versão e canal baterem.
|
|
324
|
+
* `source` importa porque outro iframe da mesma origem `payments.*` na página (ex.: um segundo
|
|
325
|
+
* cartão) não pode falar em nome deste.
|
|
326
|
+
*/ function readFrameMessage(event, expected) {
|
|
327
|
+
if (event.origin !== expected.origin || event.source !== expected.source) return null;
|
|
328
|
+
if (!isEnvelope(event.data, expected.channel)) return null;
|
|
329
|
+
if (!FRAME_TO_PARENT_TYPES.has(event.data.type)) return null;
|
|
330
|
+
return event.data;
|
|
331
|
+
}
|
|
332
|
+
function toBase64Url(value) {
|
|
333
|
+
const bytes = new TextEncoder().encode(value);
|
|
334
|
+
let binary = '';
|
|
335
|
+
for (const byte of bytes)binary += String.fromCharCode(byte);
|
|
336
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* A configuração vai no hash (como no Stripe): não chega ao servidor nem à chave de cache da CDN,
|
|
340
|
+
* então a rota do iframe responde o mesmo HTML para qualquer vendedor.
|
|
341
|
+
*/ function encodeFrameConfig(config) {
|
|
342
|
+
return toBase64Url(JSON.stringify(config));
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
class ClickmaxElementsError extends Error {
|
|
347
|
+
code;
|
|
348
|
+
constructor(code, message){
|
|
349
|
+
super(message);
|
|
350
|
+
this.name = 'ClickmaxElementsError';
|
|
351
|
+
this.code = code;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const DEFAULT_FRAME_PATH = '/elements/card';
|
|
355
|
+
const DEFAULT_TOKENIZE_TIMEOUT_MS = 45000;
|
|
356
|
+
const INITIAL_HEIGHT = 120;
|
|
357
|
+
function randomId() {
|
|
358
|
+
const bytes = new Uint8Array(16);
|
|
359
|
+
crypto.getRandomValues(bytes);
|
|
360
|
+
return Array.from(bytes, (byte)=>byte.toString(16).padStart(2, '0')).join('');
|
|
361
|
+
}
|
|
362
|
+
function createClickmaxElements(options) {
|
|
363
|
+
const paymentsOrigin = new URL(options.paymentsOrigin).origin;
|
|
364
|
+
const framePath = options.framePath ?? DEFAULT_FRAME_PATH;
|
|
365
|
+
return {
|
|
366
|
+
create (elementType, elementOptions = {}) {
|
|
367
|
+
if (elementType !== 'card') throw new Error(`Elemento não suportado: ${elementType}`);
|
|
368
|
+
return createCardElement({
|
|
369
|
+
paymentsOrigin,
|
|
370
|
+
framePath,
|
|
371
|
+
tokenizeTimeoutMs: options.tokenizeTimeoutMs ?? DEFAULT_TOKENIZE_TIMEOUT_MS,
|
|
372
|
+
elementOptions
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
function createCardElement(config) {
|
|
378
|
+
const channel = randomId();
|
|
379
|
+
const handlers = new Map();
|
|
380
|
+
const pending = new Map();
|
|
381
|
+
let currentOptions = {
|
|
382
|
+
...config.elementOptions
|
|
383
|
+
};
|
|
384
|
+
let iframe = null;
|
|
385
|
+
let handshakeDone = false;
|
|
386
|
+
let destroyed = false;
|
|
387
|
+
let lastChange;
|
|
388
|
+
// Comandos chamados antes do handshake (ex.: `focus` logo depois do `mount`) esperam o `hello`.
|
|
389
|
+
let queue = [];
|
|
390
|
+
function emit(event, payload) {
|
|
391
|
+
for (const handler of handlers.get(event) ?? []){
|
|
392
|
+
try {
|
|
393
|
+
;
|
|
394
|
+
handler(payload);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
console.error('[clickmax-elements] handler failed', {
|
|
397
|
+
op: 'emit',
|
|
398
|
+
event,
|
|
399
|
+
channel,
|
|
400
|
+
message: error instanceof Error ? error.message : 'unknown'
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function post(message) {
|
|
406
|
+
if (!iframe?.contentWindow || !handshakeDone) {
|
|
407
|
+
queue.push(message);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
// `targetOrigin` fixo: se o iframe navegar para outra origem, o navegador descarta.
|
|
411
|
+
iframe.contentWindow.postMessage(message, config.paymentsOrigin);
|
|
412
|
+
}
|
|
413
|
+
function rejectAll(code, message) {
|
|
414
|
+
for (const [requestId, request] of pending){
|
|
415
|
+
clearTimeout(request.timer);
|
|
416
|
+
request.reject(new ClickmaxElementsError(code, message));
|
|
417
|
+
pending.delete(requestId);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
function onMessage(event) {
|
|
421
|
+
if (!iframe) return;
|
|
422
|
+
const message = readFrameMessage(event, {
|
|
423
|
+
origin: config.paymentsOrigin,
|
|
424
|
+
source: iframe.contentWindow,
|
|
425
|
+
channel
|
|
426
|
+
});
|
|
427
|
+
if (!message) return;
|
|
428
|
+
handleFrameMessage(message);
|
|
429
|
+
}
|
|
430
|
+
function handleFrameMessage(message) {
|
|
431
|
+
switch(message.type){
|
|
432
|
+
case 'hello':
|
|
433
|
+
{
|
|
434
|
+
handshakeDone = true;
|
|
435
|
+
post(parentMessage(channel, 'init', currentOptions));
|
|
436
|
+
const queued = queue;
|
|
437
|
+
queue = [];
|
|
438
|
+
for (const item of queued)post(item);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
case 'ready':
|
|
442
|
+
if (iframe) iframe.style.opacity = '1';
|
|
443
|
+
emit('ready', message.payload);
|
|
444
|
+
return;
|
|
445
|
+
case 'change':
|
|
446
|
+
lastChange = message.payload;
|
|
447
|
+
emit('change', message.payload);
|
|
448
|
+
return;
|
|
449
|
+
case 'focus':
|
|
450
|
+
case 'blur':
|
|
451
|
+
emit(message.type, message.payload);
|
|
452
|
+
return;
|
|
453
|
+
case 'escape':
|
|
454
|
+
emit('escape', message.payload);
|
|
455
|
+
return;
|
|
456
|
+
case 'loaderror':
|
|
457
|
+
emit('loaderror', message.payload);
|
|
458
|
+
return;
|
|
459
|
+
case 'resize':
|
|
460
|
+
{
|
|
461
|
+
const height = Math.ceil(message.payload.height);
|
|
462
|
+
if (iframe && Number.isFinite(height) && height > 0 && height < 2000) {
|
|
463
|
+
iframe.style.height = `${height}px`;
|
|
464
|
+
}
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
case 'tokenize-result':
|
|
468
|
+
case 'tokenize-error':
|
|
469
|
+
{
|
|
470
|
+
const request = pending.get(message.payload.requestId);
|
|
471
|
+
// Resposta de um pedido que não fizemos (ou que já expirou) é ignorada.
|
|
472
|
+
if (!request) return;
|
|
473
|
+
pending.delete(message.payload.requestId);
|
|
474
|
+
clearTimeout(request.timer);
|
|
475
|
+
if (message.type === 'tokenize-result') request.resolve(message.payload.result);
|
|
476
|
+
else request.reject(new ClickmaxElementsError(message.payload.error.code, message.payload.error.message));
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const element = {
|
|
482
|
+
get state () {
|
|
483
|
+
return lastChange;
|
|
484
|
+
},
|
|
485
|
+
mount (target) {
|
|
486
|
+
if (destroyed) throw new Error('Elemento destruído: crie outro com elements.create().');
|
|
487
|
+
if (iframe) throw new Error('Elemento já montado.');
|
|
488
|
+
const container = typeof target === 'string' ? document.querySelector(target) : target;
|
|
489
|
+
if (!container) throw new Error('Container do elemento não encontrado.');
|
|
490
|
+
const frameUrl = new URL(config.framePath, config.paymentsOrigin);
|
|
491
|
+
frameUrl.hash = encodeFrameConfig({
|
|
492
|
+
v: 1,
|
|
493
|
+
channel,
|
|
494
|
+
parentOrigin: window.location.origin,
|
|
495
|
+
elementType: 'card'
|
|
496
|
+
});
|
|
497
|
+
iframe = document.createElement('iframe');
|
|
498
|
+
iframe.src = frameUrl.toString();
|
|
499
|
+
iframe.title = 'Campos seguros do cartão';
|
|
500
|
+
iframe.name = `clickmax-elements-${channel}`;
|
|
501
|
+
iframe.setAttribute('frameborder', '0');
|
|
502
|
+
iframe.setAttribute('scrolling', 'no');
|
|
503
|
+
iframe.setAttribute('allowtransparency', 'true');
|
|
504
|
+
// Mesmo `allow` do iframe do Stripe: deixa o Payment Request (Apple/Google Pay) possível depois.
|
|
505
|
+
iframe.allow = 'payment *';
|
|
506
|
+
// Nasce invisível e aparece no `ready`, sem piscar fundo branco.
|
|
507
|
+
Object.assign(iframe.style, {
|
|
508
|
+
border: 'none',
|
|
509
|
+
width: '100%',
|
|
510
|
+
height: `${INITIAL_HEIGHT}px`,
|
|
511
|
+
display: 'block',
|
|
512
|
+
overflow: 'hidden',
|
|
513
|
+
opacity: '0',
|
|
514
|
+
transition: 'opacity 120ms ease-out',
|
|
515
|
+
colorScheme: 'normal'
|
|
516
|
+
});
|
|
517
|
+
handshakeDone = false;
|
|
518
|
+
window.addEventListener('message', onMessage);
|
|
519
|
+
container.appendChild(iframe);
|
|
520
|
+
},
|
|
521
|
+
unmount () {
|
|
522
|
+
window.removeEventListener('message', onMessage);
|
|
523
|
+
iframe?.remove();
|
|
524
|
+
iframe = null;
|
|
525
|
+
handshakeDone = false;
|
|
526
|
+
lastChange = undefined;
|
|
527
|
+
rejectAll('destroyed', 'O campo de cartão foi desmontado.');
|
|
528
|
+
},
|
|
529
|
+
destroy () {
|
|
530
|
+
element.unmount();
|
|
531
|
+
destroyed = true;
|
|
532
|
+
handlers.clear();
|
|
533
|
+
queue = [];
|
|
534
|
+
},
|
|
535
|
+
update (options) {
|
|
536
|
+
currentOptions = {
|
|
537
|
+
...currentOptions,
|
|
538
|
+
...options,
|
|
539
|
+
appearance: options.appearance ?? currentOptions.appearance
|
|
540
|
+
};
|
|
541
|
+
post(parentMessage(channel, 'update', options));
|
|
542
|
+
},
|
|
543
|
+
focus () {
|
|
544
|
+
post(parentMessage(channel, 'focus', {}));
|
|
545
|
+
},
|
|
546
|
+
blur () {
|
|
547
|
+
post(parentMessage(channel, 'blur', {}));
|
|
548
|
+
},
|
|
549
|
+
clear () {
|
|
550
|
+
post(parentMessage(channel, 'clear', {}));
|
|
551
|
+
},
|
|
552
|
+
on (event, handler) {
|
|
553
|
+
if (!handlers.has(event)) handlers.set(event, new Set());
|
|
554
|
+
handlers.get(event)?.add(handler);
|
|
555
|
+
return element;
|
|
556
|
+
},
|
|
557
|
+
off (event, handler) {
|
|
558
|
+
if (!handler) handlers.delete(event);
|
|
559
|
+
else handlers.get(event)?.delete(handler);
|
|
560
|
+
return element;
|
|
561
|
+
},
|
|
562
|
+
tokenize (request) {
|
|
563
|
+
if (destroyed || !iframe) {
|
|
564
|
+
return Promise.reject(new ClickmaxElementsError('not_ready', 'Monte o campo de cartão antes de tokenizar.'));
|
|
565
|
+
}
|
|
566
|
+
const requestId = randomId();
|
|
567
|
+
return new Promise((resolve, reject)=>{
|
|
568
|
+
const timer = setTimeout(()=>{
|
|
569
|
+
pending.delete(requestId);
|
|
570
|
+
reject(new ClickmaxElementsError('timeout', 'O cartão demorou para ser processado.'));
|
|
571
|
+
}, config.tokenizeTimeoutMs);
|
|
572
|
+
pending.set(requestId, {
|
|
573
|
+
resolve,
|
|
574
|
+
reject,
|
|
575
|
+
timer
|
|
576
|
+
});
|
|
577
|
+
post(parentMessage(channel, 'tokenize', {
|
|
578
|
+
...request,
|
|
579
|
+
requestId
|
|
580
|
+
}));
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
return element;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Returns the URL only when it is absolute `https:` or `http:`. Image sources, the boleto link and
|
|
591
|
+
* the downsell redirect come from offer data and page config; a `javascript:` or `data:` value
|
|
592
|
+
* there must never reach an `href`, `src` or navigation.
|
|
593
|
+
*/ function safeUrl(value) {
|
|
594
|
+
if (!value) return undefined;
|
|
595
|
+
try {
|
|
596
|
+
const { protocol } = new URL(value);
|
|
597
|
+
return protocol === 'https:' || protocol === 'http:' ? value : undefined;
|
|
598
|
+
} catch {
|
|
599
|
+
return undefined;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/** Positive finite number of milliseconds or seconds, or the fallback. */ function positiveFinite(value, fallback) {
|
|
603
|
+
return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
604
|
+
}
|
|
605
|
+
const FREIGHT_METHODS = new Set([
|
|
606
|
+
'pac',
|
|
607
|
+
'sedex',
|
|
608
|
+
'by_producer'
|
|
609
|
+
]);
|
|
610
|
+
/** Freight quotes type `method` as a string; only the methods the purchase accepts are usable. */ function isFreightMethod(value) {
|
|
611
|
+
return FREIGHT_METHODS.has(value);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Random UUID v4, also where `crypto.randomUUID` is missing (non-secure contexts). */ function randomUuid() {
|
|
615
|
+
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
|
|
616
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
617
|
+
bytes[6] = (bytes[6] ?? 0) & 0x0f | 0x40;
|
|
618
|
+
bytes[8] = (bytes[8] ?? 0) & 0x3f | 0x80;
|
|
619
|
+
const hex = Array.from(bytes, (byte)=>byte.toString(16).padStart(2, '0')).join('');
|
|
620
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Adds the browser `eventID`s of the visitor's session to a pixel. The server builds the
|
|
624
|
+
* conversions API ids with the same formula from the same session id, which is what lets the ad
|
|
625
|
+
* platform drop the duplicate of each event.
|
|
626
|
+
*
|
|
627
|
+
* @param pixel Pixel from the public offer, which has no ids because it is cached for everyone.
|
|
628
|
+
* @param sourceId Session id from the visitor route.
|
|
629
|
+
*/ function withPixelEventIds(pixel, sourceId) {
|
|
630
|
+
const id = (event)=>`${event}-${sourceId}-${pixel.serviceId}`;
|
|
631
|
+
return {
|
|
632
|
+
...pixel,
|
|
633
|
+
eventIds: {
|
|
634
|
+
initiateCheckout: id('initiateCheckout'),
|
|
635
|
+
addToCart: id('addToCart'),
|
|
636
|
+
addPaymentInfo: id('addPaymentInfo')
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
const PT_BR = {
|
|
642
|
+
required: 'Campo obrigatório',
|
|
643
|
+
fullName: 'Informe nome e sobrenome',
|
|
644
|
+
email: 'E-mail inválido',
|
|
645
|
+
emailMismatch: 'Os e-mails não são iguais',
|
|
646
|
+
phone: 'Telefone inválido',
|
|
647
|
+
document: 'CPF ou CNPJ inválido',
|
|
648
|
+
zipCode: 'CEP inválido',
|
|
649
|
+
state: 'Use a sigla do estado',
|
|
650
|
+
csrfUnavailable: 'Não foi possível iniciar a compra. Tente de novo.',
|
|
651
|
+
recaptchaUnavailable: 'Não foi possível verificar a compra. Recarregue a página.',
|
|
652
|
+
cardNotReady: 'Os campos do cartão ainda estão carregando.',
|
|
653
|
+
cardIncomplete: 'Confira os dados do cartão.',
|
|
654
|
+
methodUnavailable: 'Forma de pagamento indisponível para esta compra.',
|
|
655
|
+
purchaseFailed: 'Não foi possível concluir a compra.',
|
|
656
|
+
purchaseTimeout: 'A compra está demorando. Confira seu e-mail antes de tentar de novo.',
|
|
657
|
+
pixExpired: 'O código pix expirou. Gere outro.',
|
|
658
|
+
includedInOrder: 'Incluído no seu pedido',
|
|
659
|
+
specialOffer: 'Oferta especial',
|
|
660
|
+
specialOffers: 'Ofertas especiais'
|
|
661
|
+
};
|
|
662
|
+
const EN = {
|
|
663
|
+
required: 'Required',
|
|
664
|
+
fullName: 'Enter your first and last name',
|
|
665
|
+
email: 'Invalid email',
|
|
666
|
+
emailMismatch: 'Emails do not match',
|
|
667
|
+
phone: 'Invalid phone',
|
|
668
|
+
document: 'Invalid document',
|
|
669
|
+
zipCode: 'Invalid postal code',
|
|
670
|
+
state: 'Use the state code',
|
|
671
|
+
csrfUnavailable: 'Could not start the purchase. Try again.',
|
|
672
|
+
recaptchaUnavailable: 'Could not verify the purchase. Reload the page.',
|
|
673
|
+
cardNotReady: 'The card fields are still loading.',
|
|
674
|
+
cardIncomplete: 'Check your card details.',
|
|
675
|
+
methodUnavailable: 'Payment method not available for this purchase.',
|
|
676
|
+
purchaseFailed: 'Could not complete the purchase.',
|
|
677
|
+
purchaseTimeout: 'The purchase is taking long. Check your email before trying again.',
|
|
678
|
+
pixExpired: 'The pix code expired. Generate a new one.',
|
|
679
|
+
includedInOrder: 'Included in your order',
|
|
680
|
+
specialOffer: 'Special offer',
|
|
681
|
+
specialOffers: 'Special offers'
|
|
682
|
+
};
|
|
683
|
+
const ES = {
|
|
684
|
+
required: 'Campo obligatorio',
|
|
685
|
+
fullName: 'Ingresa nombre y apellido',
|
|
686
|
+
email: 'Correo inválido',
|
|
687
|
+
emailMismatch: 'Los correos no coinciden',
|
|
688
|
+
phone: 'Teléfono inválido',
|
|
689
|
+
document: 'Documento inválido',
|
|
690
|
+
zipCode: 'Código postal inválido',
|
|
691
|
+
state: 'Usa la sigla del estado',
|
|
692
|
+
csrfUnavailable: 'No fue posible iniciar la compra. Inténtalo de nuevo.',
|
|
693
|
+
recaptchaUnavailable: 'No fue posible verificar la compra. Recarga la página.',
|
|
694
|
+
cardNotReady: 'Los campos de la tarjeta aún están cargando.',
|
|
695
|
+
cardIncomplete: 'Revisa los datos de la tarjeta.',
|
|
696
|
+
methodUnavailable: 'Forma de pago no disponible para esta compra.',
|
|
697
|
+
purchaseFailed: 'No fue posible completar la compra.',
|
|
698
|
+
purchaseTimeout: 'La compra está tardando. Revisa tu correo antes de intentar de nuevo.',
|
|
699
|
+
pixExpired: 'El código pix expiró. Genera otro.',
|
|
700
|
+
includedInOrder: 'Incluido en tu pedido',
|
|
701
|
+
specialOffer: 'Oferta especial',
|
|
702
|
+
specialOffers: 'Ofertas especiales'
|
|
703
|
+
};
|
|
704
|
+
const BY_LOCALE = {
|
|
705
|
+
'pt-BR': PT_BR,
|
|
706
|
+
en: EN,
|
|
707
|
+
es: ES
|
|
708
|
+
};
|
|
709
|
+
function resolveMessages(locale, overrides) {
|
|
710
|
+
return {
|
|
711
|
+
...BY_LOCALE[locale],
|
|
712
|
+
...overrides
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
const LANGUAGE = {
|
|
716
|
+
'pt-BR': 'pt',
|
|
717
|
+
en: 'en',
|
|
718
|
+
es: 'es'
|
|
719
|
+
};
|
|
720
|
+
/** Language code the purchase API takes for the buyer's emails. */ function purchaseLanguage(locale) {
|
|
721
|
+
return LANGUAGE[locale];
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Formats an amount in cents. The currency is the offer's (always BRL today); only the separators
|
|
725
|
+
* follow the locale, so the same price reads the same on the server and in the browser.
|
|
726
|
+
*
|
|
727
|
+
* @param cents Integer amount in cents, as every checkout price comes from the API.
|
|
728
|
+
* @param locale Number formatting locale.
|
|
729
|
+
*/ function formatMoney(cents, locale = 'pt-BR') {
|
|
730
|
+
return new Intl.NumberFormat(locale, {
|
|
731
|
+
style: 'currency',
|
|
732
|
+
currency: 'BRL'
|
|
733
|
+
}).format(cents / 100);
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Digits only. */ function onlyDigits(value) {
|
|
737
|
+
return value.replace(/\D/g, '');
|
|
738
|
+
}
|
|
739
|
+
function isValidCpf(digits) {
|
|
740
|
+
if (digits.length !== 11 || /^(\d)\1{10}$/.test(digits)) return false;
|
|
741
|
+
for (const length of [
|
|
742
|
+
9,
|
|
743
|
+
10
|
|
744
|
+
]){
|
|
745
|
+
let sum = 0;
|
|
746
|
+
for(let i = 0; i < length; i++)sum += Number(digits[i]) * (length + 1 - i);
|
|
747
|
+
let check = sum * 10 % 11;
|
|
748
|
+
if (check === 10) check = 0;
|
|
749
|
+
if (check !== Number(digits[length])) return false;
|
|
750
|
+
}
|
|
751
|
+
return true;
|
|
752
|
+
}
|
|
753
|
+
function isValidCnpj(digits) {
|
|
754
|
+
if (digits.length !== 14 || /^(\d)\1{13}$/.test(digits)) return false;
|
|
755
|
+
for (const length of [
|
|
756
|
+
12,
|
|
757
|
+
13
|
|
758
|
+
]){
|
|
759
|
+
let factor = length - 7;
|
|
760
|
+
let sum = 0;
|
|
761
|
+
for(let i = 0; i < length; i++){
|
|
762
|
+
sum += Number(digits[i]) * factor--;
|
|
763
|
+
if (factor < 2) factor = 9;
|
|
764
|
+
}
|
|
765
|
+
const check = 11 - sum % 11;
|
|
766
|
+
if ((check > 9 ? 0 : check) !== Number(digits[length])) return false;
|
|
767
|
+
}
|
|
768
|
+
return true;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Validates a Brazilian CPF (11 digits) or CNPJ (14 digits), with or without punctuation.
|
|
772
|
+
*
|
|
773
|
+
* @param value Document as typed.
|
|
774
|
+
*/ function isValidDocument(value) {
|
|
775
|
+
const digits = onlyDigits(value);
|
|
776
|
+
return digits.length === 11 ? isValidCpf(digits) : isValidCnpj(digits);
|
|
777
|
+
}
|
|
778
|
+
// First and last name, letters (accents included) separated by single spaces.
|
|
779
|
+
const FULL_NAME = /^[A-Za-zÀ-ÖØ-öø-ÿ]+(?: [A-Za-zÀ-ÖØ-öø-ÿ]+)+\s*$/;
|
|
780
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
|
781
|
+
/**
|
|
782
|
+
* Splits a phone into the parts the payments API expects. Without a leading `+`, the number is
|
|
783
|
+
* read as Brazilian. Brazilian numbers take the first two national digits as the area code; other
|
|
784
|
+
* countries keep the whole national number and send the country code only.
|
|
785
|
+
*
|
|
786
|
+
* Returns `undefined` when the number is too short to be real.
|
|
787
|
+
*
|
|
788
|
+
* @param value Phone as typed, such as `+55 (11) 91234-5678` or `11912345678`.
|
|
789
|
+
* @param defaultCountryCode Country code assumed without `+`. Defaults to `55`.
|
|
790
|
+
*/ function parseTelephone(value, defaultCountryCode = '55') {
|
|
791
|
+
const trimmed = value.trim();
|
|
792
|
+
let digits = onlyDigits(trimmed);
|
|
793
|
+
let countryCode = defaultCountryCode;
|
|
794
|
+
if (trimmed.startsWith('+')) {
|
|
795
|
+
// Brazilian numbers are the common case; other country codes are 1 to 3 digits, and without a
|
|
796
|
+
// numbering plan table the longest unambiguous split is the first 1-3 digits the buyer typed
|
|
797
|
+
// before a space or a separator.
|
|
798
|
+
const explicit = /^\+\s*(\d{1,3})(?=[\s().-]|$)/.exec(trimmed)?.[1];
|
|
799
|
+
countryCode = explicit ?? (digits.startsWith('55') ? '55' : digits.slice(0, 2));
|
|
800
|
+
digits = digits.slice(countryCode.length);
|
|
801
|
+
} else if (digits.length > 11 && digits.startsWith(defaultCountryCode)) {
|
|
802
|
+
digits = digits.slice(defaultCountryCode.length);
|
|
803
|
+
}
|
|
804
|
+
if (countryCode === '55') {
|
|
805
|
+
if (digits.length < 10 || digits.length > 11) return undefined;
|
|
806
|
+
return {
|
|
807
|
+
countryCode,
|
|
808
|
+
areaCode: digits.slice(0, 2),
|
|
809
|
+
number: digits.slice(2)
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
if (digits.length < 5) return undefined;
|
|
813
|
+
return {
|
|
814
|
+
countryCode,
|
|
815
|
+
areaCode: '',
|
|
816
|
+
number: digits
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Validates personal data with the same rules as the hosted checkout.
|
|
821
|
+
*
|
|
822
|
+
* @param values Typed values.
|
|
823
|
+
* @param options `isForeign` makes the document optional and skips the CPF/CNPJ check.
|
|
824
|
+
*/ function validatePersonalData(values, options) {
|
|
825
|
+
const { messages } = options;
|
|
826
|
+
const errors = {};
|
|
827
|
+
if (!values.name.trim()) errors.name = messages.required;
|
|
828
|
+
else if (!FULL_NAME.test(values.name.trim())) errors.name = messages.fullName;
|
|
829
|
+
if (!values.email.trim()) errors.email = messages.required;
|
|
830
|
+
else if (!EMAIL.test(values.email.trim())) errors.email = messages.email;
|
|
831
|
+
if (options.requireEmailConfirmation && values.confirmEmail.trim().toLowerCase() !== values.email.trim().toLowerCase()) {
|
|
832
|
+
errors.confirmEmail = messages.emailMismatch;
|
|
833
|
+
}
|
|
834
|
+
if (!values.phone.trim()) errors.phone = messages.required;
|
|
835
|
+
else if (!parseTelephone(values.phone)) errors.phone = messages.phone;
|
|
836
|
+
if (!options.isForeign) {
|
|
837
|
+
if (!values.document.trim()) errors.document = messages.required;
|
|
838
|
+
else if (!isValidDocument(values.document)) errors.document = messages.document;
|
|
839
|
+
}
|
|
840
|
+
return errors;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Validates an address. Brazilian addresses need a full CEP, a two-letter state and a
|
|
844
|
+
* neighborhood; foreign ones only a postal code, street, number and city.
|
|
845
|
+
*/ function validateAddress(values, messages) {
|
|
846
|
+
const errors = {};
|
|
847
|
+
const isBrazil = (values.country || 'BR').toUpperCase() === 'BR';
|
|
848
|
+
const zip = isBrazil ? onlyDigits(values.zipCode) : values.zipCode.trim();
|
|
849
|
+
if (!zip) errors.zipCode = messages.required;
|
|
850
|
+
else if (isBrazil ? zip.length !== 8 : zip.length > 12) errors.zipCode = messages.zipCode;
|
|
851
|
+
for (const field of [
|
|
852
|
+
'street',
|
|
853
|
+
'number',
|
|
854
|
+
'city'
|
|
855
|
+
]){
|
|
856
|
+
if (!values[field].trim()) errors[field] = messages.required;
|
|
857
|
+
}
|
|
858
|
+
if (isBrazil) {
|
|
859
|
+
if (!values.neighborhood.trim()) errors.neighborhood = messages.required;
|
|
860
|
+
if (values.state.trim().length !== 2) errors.state = messages.state;
|
|
861
|
+
}
|
|
862
|
+
return errors;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
const JOB_POLL_INTERVAL_MS = 1500;
|
|
870
|
+
const JOB_DEADLINE_MS = 60000;
|
|
871
|
+
const delay = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms));
|
|
872
|
+
function buildBuyer(state) {
|
|
873
|
+
if (!state.personalDataActive) return undefined;
|
|
874
|
+
const { personalData, address } = state;
|
|
875
|
+
const telephone = parseTelephone(personalData.phone) ?? state.oneClick?.telephone;
|
|
876
|
+
if (!telephone) return undefined;
|
|
877
|
+
const document = onlyDigits(personalData.document);
|
|
878
|
+
return {
|
|
879
|
+
name: personalData.name.trim(),
|
|
880
|
+
email: personalData.email.trim().toLowerCase(),
|
|
881
|
+
document: state.isForeign && !document ? undefined : document || undefined,
|
|
882
|
+
telephone,
|
|
883
|
+
address: address ? {
|
|
884
|
+
zipCode: address.zipCode.trim() || undefined,
|
|
885
|
+
street: address.street.trim() || undefined,
|
|
886
|
+
number: address.number.trim() || undefined,
|
|
887
|
+
complement: address.complement.trim() || undefined,
|
|
888
|
+
neighborhood: address.neighborhood.trim() || undefined,
|
|
889
|
+
city: address.city.trim() || undefined,
|
|
890
|
+
state: address.state.trim().toUpperCase() || undefined,
|
|
891
|
+
country: (address.country || 'BR').toUpperCase()
|
|
892
|
+
} : undefined
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
function pageUrl(location) {
|
|
896
|
+
if (location.pageUrl) return location.pageUrl;
|
|
897
|
+
return typeof window === 'undefined' ? '' : window.location.href;
|
|
898
|
+
}
|
|
899
|
+
async function paymentFields(state, method) {
|
|
900
|
+
if (method === 'pix') return {
|
|
901
|
+
ok: true,
|
|
902
|
+
fields: {
|
|
903
|
+
type: 'pix'
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
if (method === 'boleto') return {
|
|
907
|
+
ok: true,
|
|
908
|
+
fields: {
|
|
909
|
+
type: 'boleto'
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
// A returning buyer's saved card is charged by the API from the session cookie: nothing to send.
|
|
913
|
+
if (state.useSavedCard) return {
|
|
914
|
+
ok: true,
|
|
915
|
+
fields: {
|
|
916
|
+
type: 'credit',
|
|
917
|
+
installments: state.installment
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
const { card } = state;
|
|
921
|
+
if (!card) return {
|
|
922
|
+
ok: false,
|
|
923
|
+
message: state.messages.cardNotReady
|
|
924
|
+
};
|
|
925
|
+
if (!card.state?.complete) {
|
|
926
|
+
card.focus();
|
|
927
|
+
return {
|
|
928
|
+
ok: false,
|
|
929
|
+
message: state.messages.cardIncomplete
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
const name = state.personalData.name.trim() || state.oneClick?.name || '';
|
|
933
|
+
const result = await card.tokenize({
|
|
934
|
+
billing: {
|
|
935
|
+
holderName: state.cardHolderName.trim() || name,
|
|
936
|
+
name,
|
|
937
|
+
email: state.personalData.email.trim() || state.oneClick?.email || '',
|
|
938
|
+
document: onlyDigits(state.personalData.document) || state.oneClick?.document || undefined,
|
|
939
|
+
isForeign: state.isForeign
|
|
940
|
+
},
|
|
941
|
+
offerCode: state.offer.externalId ?? undefined
|
|
942
|
+
});
|
|
943
|
+
return {
|
|
944
|
+
ok: true,
|
|
945
|
+
fields: {
|
|
946
|
+
type: 'credit',
|
|
947
|
+
installments: state.installment,
|
|
948
|
+
cards: {
|
|
949
|
+
[result.gateway]: result.card
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
async function waitForJob(state, jobId) {
|
|
955
|
+
const deadline = Date.now() + JOB_DEADLINE_MS;
|
|
956
|
+
while(Date.now() < deadline){
|
|
957
|
+
await delay(JOB_POLL_INTERVAL_MS);
|
|
958
|
+
const status = await state.api.getPurchaseStatus(jobId);
|
|
959
|
+
if (status.result) return status.result;
|
|
960
|
+
if (status.error) {
|
|
961
|
+
throw new CheckoutApiError({
|
|
962
|
+
status: 422,
|
|
963
|
+
message: status.message,
|
|
964
|
+
code: status.error
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
throw new CheckoutApiError({
|
|
969
|
+
status: 0,
|
|
970
|
+
message: state.messages.purchaseTimeout,
|
|
971
|
+
code: 'timeout'
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
/** Polls a pending pix until it is paid. Stops when the submission moves on (reset, new attempt). */ async function watchPix(state, transactionId, totalAmount) {
|
|
975
|
+
const stillPending = ()=>{
|
|
976
|
+
const current = state.getSubmission();
|
|
977
|
+
return current.status === 'pix_pending' && current.transactionId === transactionId;
|
|
978
|
+
};
|
|
979
|
+
while(true){
|
|
980
|
+
await delay(state.pixPollIntervalMs);
|
|
981
|
+
if (!stillPending()) return;
|
|
982
|
+
try {
|
|
983
|
+
const details = await state.api.getPurchaseDetails(transactionId);
|
|
984
|
+
if (details.status !== 'paid') continue;
|
|
985
|
+
if (!stillPending()) return;
|
|
986
|
+
const purchase = {
|
|
987
|
+
transactionId,
|
|
988
|
+
totalAmount,
|
|
989
|
+
method: 'pix',
|
|
990
|
+
isUpsell: state.offer.isOTO
|
|
991
|
+
};
|
|
992
|
+
state.setSubmission((value)=>({
|
|
993
|
+
...value,
|
|
994
|
+
status: 'approved'
|
|
995
|
+
}));
|
|
996
|
+
state.callbacks.onApproved?.(purchase);
|
|
997
|
+
if (purchase.isUpsell) state.callbacks.onUpsellAccepted?.(purchase);
|
|
998
|
+
return;
|
|
999
|
+
} catch {
|
|
1000
|
+
// A failed check is retried on the next tick; the pix stays payable.
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
/** Runs one purchase attempt. Internal: components call it through `useCheckout().submit`. */ async function submitPurchase(state, options = {}) {
|
|
1005
|
+
const running = state.getSubmission().status;
|
|
1006
|
+
if (running === 'submitting' || running === 'processing') return {
|
|
1007
|
+
status: 'busy'
|
|
1008
|
+
};
|
|
1009
|
+
const method = options.method ?? state.method;
|
|
1010
|
+
const attempt = ++state.attempts.current;
|
|
1011
|
+
const commit = (update)=>{
|
|
1012
|
+
if (state.attempts.current === attempt) state.setSubmission(update);
|
|
1013
|
+
};
|
|
1014
|
+
const fail = (message)=>{
|
|
1015
|
+
commit(()=>({
|
|
1016
|
+
status: 'error',
|
|
1017
|
+
error: message,
|
|
1018
|
+
errorCode: undefined,
|
|
1019
|
+
pix: undefined,
|
|
1020
|
+
boleto: undefined,
|
|
1021
|
+
transactionId: undefined
|
|
1022
|
+
}));
|
|
1023
|
+
return {
|
|
1024
|
+
status: 'error',
|
|
1025
|
+
message
|
|
1026
|
+
};
|
|
1027
|
+
};
|
|
1028
|
+
if (!method || !state.methods.includes(method)) return fail(state.messages.methodUnavailable);
|
|
1029
|
+
if (!state.validate()) return {
|
|
1030
|
+
status: 'invalid'
|
|
1031
|
+
};
|
|
1032
|
+
commit(()=>({
|
|
1033
|
+
status: 'submitting',
|
|
1034
|
+
error: undefined,
|
|
1035
|
+
errorCode: undefined,
|
|
1036
|
+
pix: undefined,
|
|
1037
|
+
boleto: undefined,
|
|
1038
|
+
transactionId: undefined
|
|
1039
|
+
}));
|
|
1040
|
+
try {
|
|
1041
|
+
const payment = await paymentFields(state, method);
|
|
1042
|
+
if (!payment.ok) return fail(payment.message);
|
|
1043
|
+
const [recaptcha, csrfToken] = await Promise.all([
|
|
1044
|
+
state.getRecaptchaToken().catch(()=>{
|
|
1045
|
+
throw new CheckoutApiError({
|
|
1046
|
+
status: 0,
|
|
1047
|
+
message: state.messages.recaptchaUnavailable
|
|
1048
|
+
});
|
|
1049
|
+
}),
|
|
1050
|
+
state.api.getCsrfToken().catch(()=>{
|
|
1051
|
+
throw new CheckoutApiError({
|
|
1052
|
+
status: 0,
|
|
1053
|
+
message: state.messages.csrfUnavailable
|
|
1054
|
+
});
|
|
1055
|
+
})
|
|
1056
|
+
]);
|
|
1057
|
+
const { tracking } = state.location;
|
|
1058
|
+
const body = {
|
|
1059
|
+
...payment.fields,
|
|
1060
|
+
offer: state.offer.hash,
|
|
1061
|
+
orderBumpIds: state.orderBumpIds,
|
|
1062
|
+
affiliateHash: state.affiliateHash,
|
|
1063
|
+
linkCheckout: pageUrl(state.location),
|
|
1064
|
+
pageId: state.location.pageId,
|
|
1065
|
+
recaptcha,
|
|
1066
|
+
couponCode: state.couponCode,
|
|
1067
|
+
freightMethod: state.freightMethod,
|
|
1068
|
+
// Saved one-click data without a document belongs to a foreign buyer.
|
|
1069
|
+
isForeign: state.isForeign || !state.personalDataActive && !!state.oneClick && !state.oneClick.document,
|
|
1070
|
+
language: purchaseLanguage(state.locale),
|
|
1071
|
+
buyer: buildBuyer(state),
|
|
1072
|
+
...tracking
|
|
1073
|
+
};
|
|
1074
|
+
state.idempotency.key ??= randomUuid();
|
|
1075
|
+
let response = await state.api.purchase(body, {
|
|
1076
|
+
idempotencyKey: state.idempotency.key,
|
|
1077
|
+
csrfToken
|
|
1078
|
+
});
|
|
1079
|
+
if ('jobId' in response) {
|
|
1080
|
+
commit((value)=>({
|
|
1081
|
+
...value,
|
|
1082
|
+
status: 'processing'
|
|
1083
|
+
}));
|
|
1084
|
+
response = await waitForJob(state, response.jobId);
|
|
1085
|
+
}
|
|
1086
|
+
state.idempotency.key = undefined;
|
|
1087
|
+
if ('jobId' in response) throw new Error('unreachable');
|
|
1088
|
+
if (response.type === 'pix') {
|
|
1089
|
+
const pix = {
|
|
1090
|
+
transactionId: response.id,
|
|
1091
|
+
code: response.code,
|
|
1092
|
+
qrcodeUrl: response.qrcodeUrl,
|
|
1093
|
+
expiresAt: response.expirationDateTime ? new Date(response.expirationDateTime) : undefined,
|
|
1094
|
+
totalAmount: response.totalAmount
|
|
1095
|
+
};
|
|
1096
|
+
commit(()=>({
|
|
1097
|
+
status: 'pix_pending',
|
|
1098
|
+
error: undefined,
|
|
1099
|
+
errorCode: undefined,
|
|
1100
|
+
pix,
|
|
1101
|
+
boleto: undefined,
|
|
1102
|
+
transactionId: response.id
|
|
1103
|
+
}));
|
|
1104
|
+
state.callbacks.onPixGenerated?.(pix);
|
|
1105
|
+
void watchPix(state, response.id, response.totalAmount);
|
|
1106
|
+
return {
|
|
1107
|
+
status: 'pix_pending',
|
|
1108
|
+
transactionId: response.id
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
if (response.type === 'boleto') {
|
|
1112
|
+
const boleto = {
|
|
1113
|
+
transactionId: response.id,
|
|
1114
|
+
boletoUrl: response.boletoUrl,
|
|
1115
|
+
barcode: response.barcode,
|
|
1116
|
+
totalAmount: response.totalAmount
|
|
1117
|
+
};
|
|
1118
|
+
commit(()=>({
|
|
1119
|
+
status: 'boleto_issued',
|
|
1120
|
+
error: undefined,
|
|
1121
|
+
errorCode: undefined,
|
|
1122
|
+
pix: undefined,
|
|
1123
|
+
boleto,
|
|
1124
|
+
transactionId: response.id
|
|
1125
|
+
}));
|
|
1126
|
+
state.callbacks.onBoletoGenerated?.(boleto);
|
|
1127
|
+
return {
|
|
1128
|
+
status: 'boleto_issued',
|
|
1129
|
+
transactionId: response.id
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
const purchase = {
|
|
1133
|
+
transactionId: response.id,
|
|
1134
|
+
totalAmount: response.totalAmount,
|
|
1135
|
+
method: response.type,
|
|
1136
|
+
isUpsell: state.offer.isOTO
|
|
1137
|
+
};
|
|
1138
|
+
commit(()=>({
|
|
1139
|
+
status: 'approved',
|
|
1140
|
+
error: undefined,
|
|
1141
|
+
errorCode: undefined,
|
|
1142
|
+
pix: undefined,
|
|
1143
|
+
boleto: undefined,
|
|
1144
|
+
transactionId: response.id
|
|
1145
|
+
}));
|
|
1146
|
+
state.callbacks.onApproved?.(purchase);
|
|
1147
|
+
if (purchase.isUpsell) state.callbacks.onUpsellAccepted?.(purchase);
|
|
1148
|
+
return {
|
|
1149
|
+
status: 'approved',
|
|
1150
|
+
purchase
|
|
1151
|
+
};
|
|
1152
|
+
} catch (error) {
|
|
1153
|
+
const apiError = error instanceof CheckoutApiError ? error : new CheckoutApiError({
|
|
1154
|
+
status: 0,
|
|
1155
|
+
message: error instanceof Error ? error.message : state.messages.purchaseFailed,
|
|
1156
|
+
code: error?.code
|
|
1157
|
+
});
|
|
1158
|
+
// No answer (network, timeout) or a server error leaves the purchase in doubt: keep the key so
|
|
1159
|
+
// a retry is deduplicated by the API instead of charging twice. A definitive refusal (4xx)
|
|
1160
|
+
// starts the next attempt with a new key.
|
|
1161
|
+
if (apiError.status !== 0 && apiError.status < 500) state.idempotency.key = undefined;
|
|
1162
|
+
const message = apiError.message || state.messages.purchaseFailed;
|
|
1163
|
+
commit(()=>({
|
|
1164
|
+
status: 'declined',
|
|
1165
|
+
error: message,
|
|
1166
|
+
errorCode: apiError.code,
|
|
1167
|
+
pix: undefined,
|
|
1168
|
+
boleto: undefined,
|
|
1169
|
+
transactionId: undefined
|
|
1170
|
+
}));
|
|
1171
|
+
state.callbacks.onDeclined?.({
|
|
1172
|
+
method,
|
|
1173
|
+
status: apiError.status,
|
|
1174
|
+
code: apiError.code,
|
|
1175
|
+
message
|
|
1176
|
+
});
|
|
1177
|
+
return {
|
|
1178
|
+
status: 'declined',
|
|
1179
|
+
message,
|
|
1180
|
+
code: apiError.code
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
/** Base URL used when the provider gets no `transport`: the same-domain proxy of a site. */ const DEFAULT_PAYMENTS_BASE_URL = '/__clickmax/payments';
|
|
1195
|
+
const CheckoutContext = /*#__PURE__*/ createContext(null);
|
|
1196
|
+
/** Reads the checkout. Throws outside `CheckoutProvider`. */ function useCheckout() {
|
|
1197
|
+
const value = useContext(CheckoutContext);
|
|
1198
|
+
if (!value) throw new Error('useCheckout must be used inside <CheckoutProvider>');
|
|
1199
|
+
return value;
|
|
1200
|
+
}
|
|
1201
|
+
const EMPTY_ADDRESS = {
|
|
1202
|
+
zipCode: '',
|
|
1203
|
+
street: '',
|
|
1204
|
+
number: '',
|
|
1205
|
+
complement: '',
|
|
1206
|
+
neighborhood: '',
|
|
1207
|
+
city: '',
|
|
1208
|
+
state: '',
|
|
1209
|
+
country: 'BR'
|
|
1210
|
+
};
|
|
1211
|
+
const IDLE_SUBMISSION = {
|
|
1212
|
+
status: 'idle',
|
|
1213
|
+
error: undefined,
|
|
1214
|
+
errorCode: undefined,
|
|
1215
|
+
pix: undefined,
|
|
1216
|
+
boleto: undefined,
|
|
1217
|
+
transactionId: undefined
|
|
1218
|
+
};
|
|
1219
|
+
function offerPrice(offer) {
|
|
1220
|
+
return offer.newPrice ?? offer.originalPrice;
|
|
1221
|
+
}
|
|
1222
|
+
function bumpPrice(bump) {
|
|
1223
|
+
return bump.newPrice ?? bump.originalPrice;
|
|
1224
|
+
}
|
|
1225
|
+
/**
|
|
1226
|
+
* Methods the offer accepts, intersected with what every selected bump accepts. Used only until
|
|
1227
|
+
* the server pricing answers with `availableMethods`.
|
|
1228
|
+
*/ function staticMethods(offer, selectedIds) {
|
|
1229
|
+
const bumps = offer.orderBumps.filter((bump)=>selectedIds.includes(bump.id));
|
|
1230
|
+
return [
|
|
1231
|
+
'credit',
|
|
1232
|
+
'pix',
|
|
1233
|
+
'boleto'
|
|
1234
|
+
].filter((method)=>offer.methods[method].active && bumps.every((bump)=>bump.paymentMethods[method]));
|
|
1235
|
+
}
|
|
1236
|
+
function staticInstallments(offer) {
|
|
1237
|
+
return offer.methods.credit.installments.map(({ installment, value })=>({
|
|
1238
|
+
installment,
|
|
1239
|
+
value,
|
|
1240
|
+
total: installment * value
|
|
1241
|
+
}));
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Root of the checkout. Renders nothing itself; every component and hook reads from it.
|
|
1245
|
+
*
|
|
1246
|
+
* SSR: the first render uses only `offer` (and `initialPricing`), so the server HTML and the
|
|
1247
|
+
* first client render match. After hydration the provider loads the visitor (one-click data,
|
|
1248
|
+
* session id, affiliate status), the server pricing and an initial coupon, and only the parts that
|
|
1249
|
+
* depend on them re-render.
|
|
1250
|
+
*/ function CheckoutProvider(props) {
|
|
1251
|
+
const { offer, transport, paymentsOrigin, location: locationProp, locale = 'pt-BR', messages: messageOverrides, initialPricing, requireEmailConfirmation = false, children } = props;
|
|
1252
|
+
const location = locationProp ?? {};
|
|
1253
|
+
const baseUrl = transport?.baseUrl ?? DEFAULT_PAYMENTS_BASE_URL;
|
|
1254
|
+
const api = useMemo(()=>createCheckoutApi({
|
|
1255
|
+
...transport,
|
|
1256
|
+
baseUrl
|
|
1257
|
+
}), // A new object literal on every host render must not rebuild the client.
|
|
1258
|
+
[
|
|
1259
|
+
baseUrl,
|
|
1260
|
+
transport?.fetch,
|
|
1261
|
+
transport?.credentials,
|
|
1262
|
+
transport?.headers
|
|
1263
|
+
]);
|
|
1264
|
+
const messages = useMemo(()=>resolveMessages(locale, messageOverrides), [
|
|
1265
|
+
locale,
|
|
1266
|
+
messageOverrides
|
|
1267
|
+
]);
|
|
1268
|
+
// Callbacks change identity on every host render; reading them through a ref keeps effects and
|
|
1269
|
+
// `submit` stable.
|
|
1270
|
+
const propsRef = useRef(props);
|
|
1271
|
+
propsRef.current = props;
|
|
1272
|
+
const callbacks = useMemo(()=>({
|
|
1273
|
+
onApproved: (purchase)=>propsRef.current.onApproved?.(purchase),
|
|
1274
|
+
onDeclined: (purchase)=>propsRef.current.onDeclined?.(purchase),
|
|
1275
|
+
onPixGenerated: (pix)=>propsRef.current.onPixGenerated?.(pix),
|
|
1276
|
+
onBoletoGenerated: (boleto)=>propsRef.current.onBoletoGenerated?.(boleto),
|
|
1277
|
+
onUpsellAccepted: (purchase)=>propsRef.current.onUpsellAccepted?.(purchase),
|
|
1278
|
+
onUpsellDeclined: (event)=>propsRef.current.onUpsellDeclined?.(event)
|
|
1279
|
+
}), []);
|
|
1280
|
+
const [isHydrated, setHydrated] = useState(false);
|
|
1281
|
+
useEffect(()=>setHydrated(true), []);
|
|
1282
|
+
// region Visitor
|
|
1283
|
+
const [visitor, setVisitor] = useState({
|
|
1284
|
+
status: 'idle',
|
|
1285
|
+
data: undefined
|
|
1286
|
+
});
|
|
1287
|
+
useEffect(()=>{
|
|
1288
|
+
const controller = new AbortController();
|
|
1289
|
+
setVisitor({
|
|
1290
|
+
status: 'loading',
|
|
1291
|
+
data: undefined
|
|
1292
|
+
});
|
|
1293
|
+
api.getVisitor({
|
|
1294
|
+
offer: offer.hash,
|
|
1295
|
+
affiliateHash: location.affiliateHash
|
|
1296
|
+
}, {
|
|
1297
|
+
signal: controller.signal
|
|
1298
|
+
}).then((data)=>setVisitor({
|
|
1299
|
+
status: 'success',
|
|
1300
|
+
data
|
|
1301
|
+
})).catch((error)=>{
|
|
1302
|
+
if (controller.signal.aborted) return;
|
|
1303
|
+
// The checkout still works without the visitor: no one-click, no pixel ids.
|
|
1304
|
+
console.error('[clickmax-checkout] visitor request failed', {
|
|
1305
|
+
op: 'getVisitor',
|
|
1306
|
+
offer: offer.hash,
|
|
1307
|
+
status: error instanceof CheckoutApiError ? error.status : undefined
|
|
1308
|
+
});
|
|
1309
|
+
setVisitor({
|
|
1310
|
+
status: 'error',
|
|
1311
|
+
data: undefined
|
|
1312
|
+
});
|
|
1313
|
+
});
|
|
1314
|
+
return ()=>controller.abort();
|
|
1315
|
+
}, [
|
|
1316
|
+
api,
|
|
1317
|
+
offer.hash,
|
|
1318
|
+
location.affiliateHash
|
|
1319
|
+
]);
|
|
1320
|
+
const affiliateHash = visitor.data?.isAffiliationSuspended ? undefined : location.affiliateHash;
|
|
1321
|
+
const pixels = useMemo(()=>{
|
|
1322
|
+
const sourceId = visitor.data?.sourceId;
|
|
1323
|
+
return sourceId ? offer.pixels.map((pixel)=>withPixelEventIds(pixel, sourceId)) : offer.pixels;
|
|
1324
|
+
}, [
|
|
1325
|
+
offer.pixels,
|
|
1326
|
+
visitor.data?.sourceId
|
|
1327
|
+
]);
|
|
1328
|
+
// endregion
|
|
1329
|
+
// region One-click and personal data
|
|
1330
|
+
const oneClickData = visitor.data?.oneClickBuy;
|
|
1331
|
+
const [oneClickEditing, setOneClickEditing] = useState(false);
|
|
1332
|
+
const [personalValues, setPersonalValues] = useState(()=>({
|
|
1333
|
+
name: location.prefill?.name ?? '',
|
|
1334
|
+
email: location.prefill?.email ?? '',
|
|
1335
|
+
confirmEmail: location.prefill?.confirmEmail ?? '',
|
|
1336
|
+
phone: location.prefill?.phone ?? '',
|
|
1337
|
+
document: location.prefill?.document ?? ''
|
|
1338
|
+
}));
|
|
1339
|
+
const [personalErrors, setPersonalErrors] = useState({});
|
|
1340
|
+
const [addressValues, setAddressValues] = useState(EMPTY_ADDRESS);
|
|
1341
|
+
const [addressErrors, setAddressErrors] = useState({});
|
|
1342
|
+
// Editing saved data starts from it instead of empty fields.
|
|
1343
|
+
useEffect(()=>{
|
|
1344
|
+
if (!oneClickEditing || !oneClickData) return;
|
|
1345
|
+
const { telephone, address } = oneClickData;
|
|
1346
|
+
setPersonalValues((current)=>({
|
|
1347
|
+
name: current.name || oneClickData.name,
|
|
1348
|
+
email: current.email || oneClickData.email,
|
|
1349
|
+
confirmEmail: current.confirmEmail || oneClickData.email,
|
|
1350
|
+
phone: current.phone || `+${telephone.countryCode} ${telephone.areaCode}${telephone.number}`,
|
|
1351
|
+
document: current.document || (oneClickData.document ?? '')
|
|
1352
|
+
}));
|
|
1353
|
+
setAddressValues((current)=>current.zipCode ? current : {
|
|
1354
|
+
zipCode: address.zipCode ?? '',
|
|
1355
|
+
street: address.street ?? '',
|
|
1356
|
+
number: address.number ?? '',
|
|
1357
|
+
complement: address.complement ?? '',
|
|
1358
|
+
neighborhood: address.neighborhood ?? '',
|
|
1359
|
+
city: address.city ?? '',
|
|
1360
|
+
state: address.state ?? '',
|
|
1361
|
+
country: address.country ?? 'BR'
|
|
1362
|
+
});
|
|
1363
|
+
}, [
|
|
1364
|
+
oneClickEditing,
|
|
1365
|
+
oneClickData
|
|
1366
|
+
]);
|
|
1367
|
+
const personalDataActive = !oneClickData || oneClickEditing;
|
|
1368
|
+
const isForeign = locale !== 'pt-BR';
|
|
1369
|
+
const addressRequired = (offer.requiredAddress || offer.isPhysical) && personalDataActive;
|
|
1370
|
+
const validatePersonal = useCallback(()=>{
|
|
1371
|
+
if (!personalDataActive) return true;
|
|
1372
|
+
const errors = validatePersonalData(personalValues, {
|
|
1373
|
+
isForeign,
|
|
1374
|
+
requireEmailConfirmation,
|
|
1375
|
+
messages
|
|
1376
|
+
});
|
|
1377
|
+
setPersonalErrors(errors);
|
|
1378
|
+
return Object.keys(errors).length === 0;
|
|
1379
|
+
}, [
|
|
1380
|
+
personalDataActive,
|
|
1381
|
+
personalValues,
|
|
1382
|
+
isForeign,
|
|
1383
|
+
requireEmailConfirmation,
|
|
1384
|
+
messages
|
|
1385
|
+
]);
|
|
1386
|
+
const validateAddressFields = useCallback(()=>{
|
|
1387
|
+
if (!addressRequired) return true;
|
|
1388
|
+
const errors = validateAddress(addressValues, messages);
|
|
1389
|
+
setAddressErrors(errors);
|
|
1390
|
+
return Object.keys(errors).length === 0;
|
|
1391
|
+
}, [
|
|
1392
|
+
addressRequired,
|
|
1393
|
+
addressValues,
|
|
1394
|
+
messages
|
|
1395
|
+
]);
|
|
1396
|
+
// endregion
|
|
1397
|
+
// region Order bumps
|
|
1398
|
+
const requiredBumpIds = useMemo(()=>offer.configs?.orderBump.required.filter((id)=>offer.orderBumps.some((b)=>b.id === id)) ?? [], [
|
|
1399
|
+
offer.configs,
|
|
1400
|
+
offer.orderBumps
|
|
1401
|
+
]);
|
|
1402
|
+
const [optionalBumpIds, setOptionalBumpIds] = useState([]);
|
|
1403
|
+
const selectedBumpIds = useMemo(()=>[
|
|
1404
|
+
...requiredBumpIds,
|
|
1405
|
+
...optionalBumpIds.filter((id)=>!requiredBumpIds.includes(id))
|
|
1406
|
+
], [
|
|
1407
|
+
requiredBumpIds,
|
|
1408
|
+
optionalBumpIds
|
|
1409
|
+
]);
|
|
1410
|
+
const toggleBump = useCallback((id, selected)=>{
|
|
1411
|
+
if (requiredBumpIds.includes(id)) return;
|
|
1412
|
+
setOptionalBumpIds((current)=>{
|
|
1413
|
+
const isSelected = current.includes(id);
|
|
1414
|
+
const next = selected ?? !isSelected;
|
|
1415
|
+
if (next === isSelected) return current;
|
|
1416
|
+
return next ? [
|
|
1417
|
+
...current,
|
|
1418
|
+
id
|
|
1419
|
+
] : current.filter((value)=>value !== id);
|
|
1420
|
+
});
|
|
1421
|
+
}, [
|
|
1422
|
+
requiredBumpIds
|
|
1423
|
+
]);
|
|
1424
|
+
// endregion
|
|
1425
|
+
// region Coupon and pricing
|
|
1426
|
+
const [couponCode, setCouponCode] = useState(undefined);
|
|
1427
|
+
const [couponStatus, setCouponStatus] = useState('idle');
|
|
1428
|
+
const [couponResult, setCouponResult] = useState(undefined);
|
|
1429
|
+
const couponRequest = useRef(0);
|
|
1430
|
+
const buyerEmail = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(personalValues.email.trim()) ? personalValues.email.trim().toLowerCase() : oneClickData?.email;
|
|
1431
|
+
const applyCoupon = useCallback(async (code)=>{
|
|
1432
|
+
const normalized = code.trim().toUpperCase();
|
|
1433
|
+
if (!normalized) return false;
|
|
1434
|
+
const request = ++couponRequest.current;
|
|
1435
|
+
setCouponStatus('validating');
|
|
1436
|
+
try {
|
|
1437
|
+
const result = await api.validateCoupon({
|
|
1438
|
+
code: normalized,
|
|
1439
|
+
offerHash: offer.hash,
|
|
1440
|
+
buyerEmail
|
|
1441
|
+
});
|
|
1442
|
+
// Only the latest request may write: a slow answer must not undo a newer one.
|
|
1443
|
+
if (request !== couponRequest.current) return result.valid;
|
|
1444
|
+
setCouponResult(result);
|
|
1445
|
+
setCouponStatus(result.valid ? 'valid' : 'invalid');
|
|
1446
|
+
setCouponCode(result.valid ? normalized : undefined);
|
|
1447
|
+
return result.valid;
|
|
1448
|
+
} catch {
|
|
1449
|
+
if (request === couponRequest.current) {
|
|
1450
|
+
setCouponStatus('invalid');
|
|
1451
|
+
setCouponCode(undefined);
|
|
1452
|
+
}
|
|
1453
|
+
return false;
|
|
1454
|
+
}
|
|
1455
|
+
}, [
|
|
1456
|
+
api,
|
|
1457
|
+
offer.hash,
|
|
1458
|
+
buyerEmail
|
|
1459
|
+
]);
|
|
1460
|
+
const removeCoupon = useCallback(()=>{
|
|
1461
|
+
couponRequest.current++;
|
|
1462
|
+
setCouponCode(undefined);
|
|
1463
|
+
setCouponResult(undefined);
|
|
1464
|
+
setCouponStatus('idle');
|
|
1465
|
+
}, []);
|
|
1466
|
+
// A coupon from the link is applied once, after hydration (it is per visit, not per page).
|
|
1467
|
+
const initialCoupon = location.couponCode;
|
|
1468
|
+
const appliedInitialCoupon = useRef(false);
|
|
1469
|
+
useEffect(()=>{
|
|
1470
|
+
if (appliedInitialCoupon.current || !initialCoupon || !offer.showCoupon) return;
|
|
1471
|
+
appliedInitialCoupon.current = true;
|
|
1472
|
+
void applyCoupon(initialCoupon);
|
|
1473
|
+
}, [
|
|
1474
|
+
initialCoupon,
|
|
1475
|
+
offer.showCoupon,
|
|
1476
|
+
applyCoupon
|
|
1477
|
+
]);
|
|
1478
|
+
const [pricing, setPricing] = useState({
|
|
1479
|
+
status: initialPricing ? 'success' : 'idle',
|
|
1480
|
+
data: initialPricing
|
|
1481
|
+
});
|
|
1482
|
+
// Required bumps go too: the server only prices what it is sent, and the total (and the
|
|
1483
|
+
// methods the order allows) must include them.
|
|
1484
|
+
const pricingKey = JSON.stringify([
|
|
1485
|
+
selectedBumpIds,
|
|
1486
|
+
couponCode,
|
|
1487
|
+
couponCode ? buyerEmail : ''
|
|
1488
|
+
]);
|
|
1489
|
+
useEffect(()=>{
|
|
1490
|
+
const controller = new AbortController();
|
|
1491
|
+
const [orderBumpIds, code, email] = JSON.parse(pricingKey);
|
|
1492
|
+
// Short debounce: toggling bumps or typing the email fires one request, not one per change.
|
|
1493
|
+
const timer = setTimeout(()=>{
|
|
1494
|
+
setPricing((current)=>({
|
|
1495
|
+
...current,
|
|
1496
|
+
status: 'loading'
|
|
1497
|
+
}));
|
|
1498
|
+
api.getPricing({
|
|
1499
|
+
offerHash: offer.hash,
|
|
1500
|
+
orderBumpIds,
|
|
1501
|
+
previewOrderBumpIds: offer.orderBumps.map((bump)=>bump.id),
|
|
1502
|
+
couponCode: code || undefined,
|
|
1503
|
+
buyerEmail: email || undefined
|
|
1504
|
+
}, {
|
|
1505
|
+
signal: controller.signal
|
|
1506
|
+
}).then((data)=>{
|
|
1507
|
+
setPricing({
|
|
1508
|
+
status: 'success',
|
|
1509
|
+
data
|
|
1510
|
+
});
|
|
1511
|
+
if (data.coupon && code) {
|
|
1512
|
+
setCouponResult(data.coupon);
|
|
1513
|
+
setCouponStatus(data.coupon.valid ? 'valid' : 'invalid');
|
|
1514
|
+
}
|
|
1515
|
+
}).catch(()=>{
|
|
1516
|
+
if (!controller.signal.aborted) setPricing((current)=>({
|
|
1517
|
+
...current,
|
|
1518
|
+
status: 'error'
|
|
1519
|
+
}));
|
|
1520
|
+
});
|
|
1521
|
+
}, 200);
|
|
1522
|
+
return ()=>{
|
|
1523
|
+
clearTimeout(timer);
|
|
1524
|
+
controller.abort();
|
|
1525
|
+
};
|
|
1526
|
+
}, [
|
|
1527
|
+
api,
|
|
1528
|
+
offer.hash,
|
|
1529
|
+
offer.orderBumps,
|
|
1530
|
+
pricingKey
|
|
1531
|
+
]);
|
|
1532
|
+
// endregion
|
|
1533
|
+
// region Freight
|
|
1534
|
+
const freightEnabled = offer.isPhysical;
|
|
1535
|
+
const zipDigits = onlyDigits(addressValues.zipCode);
|
|
1536
|
+
const [freight, setFreight] = useState({
|
|
1537
|
+
status: 'idle',
|
|
1538
|
+
quote: undefined
|
|
1539
|
+
});
|
|
1540
|
+
const [freightMethod, setFreightMethod] = useState(undefined);
|
|
1541
|
+
useEffect(()=>{
|
|
1542
|
+
if (!freightEnabled || zipDigits.length !== 8) return;
|
|
1543
|
+
const controller = new AbortController();
|
|
1544
|
+
const timer = setTimeout(()=>{
|
|
1545
|
+
setFreight((current)=>({
|
|
1546
|
+
...current,
|
|
1547
|
+
status: 'loading'
|
|
1548
|
+
}));
|
|
1549
|
+
api.getFreightQuote({
|
|
1550
|
+
offerHash: offer.hash,
|
|
1551
|
+
zipCode: zipDigits
|
|
1552
|
+
}, {
|
|
1553
|
+
signal: controller.signal
|
|
1554
|
+
}).then((quote)=>{
|
|
1555
|
+
setFreight({
|
|
1556
|
+
status: 'success',
|
|
1557
|
+
quote
|
|
1558
|
+
});
|
|
1559
|
+
const usable = quote.freights.map((option)=>option.method).filter(isFreightMethod);
|
|
1560
|
+
setFreightMethod((current)=>current && usable.includes(current) ? current : usable[0]);
|
|
1561
|
+
}).catch(()=>{
|
|
1562
|
+
if (!controller.signal.aborted) setFreight({
|
|
1563
|
+
status: 'error',
|
|
1564
|
+
quote: undefined
|
|
1565
|
+
});
|
|
1566
|
+
});
|
|
1567
|
+
}, 300);
|
|
1568
|
+
return ()=>{
|
|
1569
|
+
clearTimeout(timer);
|
|
1570
|
+
controller.abort();
|
|
1571
|
+
};
|
|
1572
|
+
}, [
|
|
1573
|
+
api,
|
|
1574
|
+
freightEnabled,
|
|
1575
|
+
offer.hash,
|
|
1576
|
+
zipDigits
|
|
1577
|
+
]);
|
|
1578
|
+
const freightValue = freight.quote?.freights.find((option)=>option.method === freightMethod)?.value ?? 0;
|
|
1579
|
+
// endregion
|
|
1580
|
+
// region Payment
|
|
1581
|
+
const methods = useMemo(()=>{
|
|
1582
|
+
const available = pricing.data?.availableMethods;
|
|
1583
|
+
if (!available) return staticMethods(offer, selectedBumpIds);
|
|
1584
|
+
return [
|
|
1585
|
+
'credit',
|
|
1586
|
+
'pix',
|
|
1587
|
+
'boleto'
|
|
1588
|
+
].filter((method)=>available[method]);
|
|
1589
|
+
}, [
|
|
1590
|
+
pricing.data?.availableMethods,
|
|
1591
|
+
offer,
|
|
1592
|
+
selectedBumpIds
|
|
1593
|
+
]);
|
|
1594
|
+
const [chosenMethod, setChosenMethod] = useState(undefined);
|
|
1595
|
+
const preferredMethod = oneClickData?.lastPaymentMethod;
|
|
1596
|
+
const method = chosenMethod && methods.includes(chosenMethod) ? chosenMethod : preferredMethod && methods.includes(preferredMethod) ? preferredMethod : methods[0];
|
|
1597
|
+
const installments = useMemo(()=>pricing.data?.installments ?? staticInstallments(offer), [
|
|
1598
|
+
pricing.data?.installments,
|
|
1599
|
+
offer
|
|
1600
|
+
]);
|
|
1601
|
+
const [chosenInstallment, setChosenInstallment] = useState(undefined);
|
|
1602
|
+
const defaultInstallment = oneClickData?.lastInstallment ?? offer.defaultInstallment;
|
|
1603
|
+
const installment = [
|
|
1604
|
+
chosenInstallment,
|
|
1605
|
+
defaultInstallment,
|
|
1606
|
+
1
|
|
1607
|
+
].find((value)=>value !== undefined && installments.some((option)=>option.installment === value)) ?? installments[0]?.installment ?? 1;
|
|
1608
|
+
const savedCard = oneClickData?.card;
|
|
1609
|
+
const [useSavedCardChoice, setUseSavedCard] = useState(true);
|
|
1610
|
+
const useSavedCard = Boolean(savedCard) && useSavedCardChoice;
|
|
1611
|
+
const [cardHolderName, setCardHolderName] = useState('');
|
|
1612
|
+
const [card, registerCard] = useState(undefined);
|
|
1613
|
+
// endregion
|
|
1614
|
+
// region Summary
|
|
1615
|
+
const summary = useMemo(()=>{
|
|
1616
|
+
const data = pricing.data;
|
|
1617
|
+
if (data) {
|
|
1618
|
+
return {
|
|
1619
|
+
subtotal: data.subtotal,
|
|
1620
|
+
offerDiscount: data.offerDiscount,
|
|
1621
|
+
couponDiscount: data.couponDiscount,
|
|
1622
|
+
platformFee: data.platformFixedFee,
|
|
1623
|
+
freight: freightValue,
|
|
1624
|
+
total: data.total + data.platformFixedFee + freightValue,
|
|
1625
|
+
isEstimate: false
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
const items = [
|
|
1629
|
+
{
|
|
1630
|
+
original: offer.originalPrice,
|
|
1631
|
+
price: offerPrice(offer)
|
|
1632
|
+
},
|
|
1633
|
+
...offer.orderBumps.filter((bump)=>selectedBumpIds.includes(bump.id)).map((bump)=>({
|
|
1634
|
+
original: bump.originalPrice,
|
|
1635
|
+
price: bumpPrice(bump)
|
|
1636
|
+
}))
|
|
1637
|
+
];
|
|
1638
|
+
const subtotal = items.reduce((sum, item)=>sum + item.original, 0);
|
|
1639
|
+
const total = items.reduce((sum, item)=>sum + item.price, 0);
|
|
1640
|
+
return {
|
|
1641
|
+
subtotal,
|
|
1642
|
+
offerDiscount: subtotal - total,
|
|
1643
|
+
couponDiscount: 0,
|
|
1644
|
+
platformFee: 0,
|
|
1645
|
+
freight: freightValue,
|
|
1646
|
+
total: total + freightValue,
|
|
1647
|
+
isEstimate: true
|
|
1648
|
+
};
|
|
1649
|
+
}, [
|
|
1650
|
+
pricing.data,
|
|
1651
|
+
offer,
|
|
1652
|
+
selectedBumpIds,
|
|
1653
|
+
freightValue
|
|
1654
|
+
]);
|
|
1655
|
+
const bumpItems = useMemo(()=>{
|
|
1656
|
+
const priced = new Map(pricing.data?.items.filter((item)=>item.type === 'orderBump').map((item)=>[
|
|
1657
|
+
item.id,
|
|
1658
|
+
item.effectivePrice
|
|
1659
|
+
]));
|
|
1660
|
+
return offer.orderBumps// A recurring bump cannot ride on a recurring offer (one subscription per purchase).
|
|
1661
|
+
.filter((bump)=>!(offer.isRecurrent && bump.isRecurrent)).map((bump)=>({
|
|
1662
|
+
id: bump.id,
|
|
1663
|
+
name: bump.name,
|
|
1664
|
+
description: bump.description,
|
|
1665
|
+
imageUrl: bump.thumbnailImage,
|
|
1666
|
+
originalPrice: bump.originalPrice,
|
|
1667
|
+
price: priced.get(bump.id) ?? bumpPrice(bump),
|
|
1668
|
+
isRecurrent: bump.isRecurrent,
|
|
1669
|
+
recurrenceFrequency: bump.recurrenceFrequency,
|
|
1670
|
+
selected: selectedBumpIds.includes(bump.id),
|
|
1671
|
+
required: requiredBumpIds.includes(bump.id),
|
|
1672
|
+
disabled: method ? !bump.paymentMethods[method] : false
|
|
1673
|
+
}));
|
|
1674
|
+
}, [
|
|
1675
|
+
offer,
|
|
1676
|
+
pricing.data?.items,
|
|
1677
|
+
selectedBumpIds,
|
|
1678
|
+
requiredBumpIds,
|
|
1679
|
+
method
|
|
1680
|
+
]);
|
|
1681
|
+
const requiredBumps = useMemo(()=>bumpItems.filter((bump)=>bump.required), [
|
|
1682
|
+
bumpItems
|
|
1683
|
+
]);
|
|
1684
|
+
const optionalBumps = useMemo(()=>bumpItems.filter((bump)=>!bump.required), [
|
|
1685
|
+
bumpItems
|
|
1686
|
+
]);
|
|
1687
|
+
// Empty title falls back to the translated default: older pages have no title.
|
|
1688
|
+
const bumpTitle = offer.configs?.orderBump.title?.trim() || (optionalBumps.length > 1 ? messages.specialOffers : messages.specialOffer);
|
|
1689
|
+
// endregion
|
|
1690
|
+
// region Submit
|
|
1691
|
+
const [submission, setSubmissionState] = useState(IDLE_SUBMISSION);
|
|
1692
|
+
// Mirrors `submission` synchronously so a running purchase (pix polling) can tell whether the
|
|
1693
|
+
// buyer reset or started another attempt in the meantime.
|
|
1694
|
+
const submissionRef = useRef(IDLE_SUBMISSION);
|
|
1695
|
+
const setSubmission = useCallback((update)=>{
|
|
1696
|
+
submissionRef.current = update(submissionRef.current);
|
|
1697
|
+
setSubmissionState(submissionRef.current);
|
|
1698
|
+
}, []);
|
|
1699
|
+
const idempotency = useRef({
|
|
1700
|
+
key: undefined
|
|
1701
|
+
}).current;
|
|
1702
|
+
const attempts = useRef({
|
|
1703
|
+
current: 0
|
|
1704
|
+
}).current;
|
|
1705
|
+
const stateRef = useRef(null);
|
|
1706
|
+
stateRef.current = {
|
|
1707
|
+
api,
|
|
1708
|
+
offer,
|
|
1709
|
+
location,
|
|
1710
|
+
locale,
|
|
1711
|
+
messages,
|
|
1712
|
+
callbacks,
|
|
1713
|
+
getRecaptchaToken: ()=>propsRef.current.getRecaptchaToken?.() ?? Promise.resolve(''),
|
|
1714
|
+
pixPollIntervalMs: positiveFinite(props.pixPollIntervalMs, 5000),
|
|
1715
|
+
affiliateHash,
|
|
1716
|
+
oneClick: oneClickData,
|
|
1717
|
+
personalDataActive,
|
|
1718
|
+
personalData: personalValues,
|
|
1719
|
+
address: addressRequired ? addressValues : undefined,
|
|
1720
|
+
validate: ()=>{
|
|
1721
|
+
const personalOk = validatePersonal();
|
|
1722
|
+
const addressOk = validateAddressFields();
|
|
1723
|
+
return personalOk && addressOk;
|
|
1724
|
+
},
|
|
1725
|
+
isForeign,
|
|
1726
|
+
orderBumpIds: selectedBumpIds,
|
|
1727
|
+
couponCode,
|
|
1728
|
+
freightMethod: freightEnabled ? freightMethod : undefined,
|
|
1729
|
+
method,
|
|
1730
|
+
methods,
|
|
1731
|
+
installment,
|
|
1732
|
+
useSavedCard,
|
|
1733
|
+
cardHolderName,
|
|
1734
|
+
card,
|
|
1735
|
+
setSubmission,
|
|
1736
|
+
getSubmission: ()=>submissionRef.current,
|
|
1737
|
+
idempotency,
|
|
1738
|
+
attempts
|
|
1739
|
+
};
|
|
1740
|
+
const submit = useCallback(async (options)=>{
|
|
1741
|
+
const state = stateRef.current;
|
|
1742
|
+
if (!state) throw new Error('Checkout is not ready');
|
|
1743
|
+
return submitPurchase(state, options);
|
|
1744
|
+
}, []);
|
|
1745
|
+
const reset = useCallback(()=>{
|
|
1746
|
+
attempts.current++;
|
|
1747
|
+
setSubmission(()=>IDLE_SUBMISSION);
|
|
1748
|
+
}, [
|
|
1749
|
+
attempts,
|
|
1750
|
+
setSubmission
|
|
1751
|
+
]);
|
|
1752
|
+
// endregion
|
|
1753
|
+
const value = {
|
|
1754
|
+
offer,
|
|
1755
|
+
api,
|
|
1756
|
+
locale,
|
|
1757
|
+
messages,
|
|
1758
|
+
location,
|
|
1759
|
+
paymentsOrigin,
|
|
1760
|
+
isHydrated,
|
|
1761
|
+
visitor,
|
|
1762
|
+
affiliateHash,
|
|
1763
|
+
pixels,
|
|
1764
|
+
oneClick: {
|
|
1765
|
+
data: oneClickData,
|
|
1766
|
+
editing: oneClickEditing,
|
|
1767
|
+
setEditing: setOneClickEditing
|
|
1768
|
+
},
|
|
1769
|
+
personalData: {
|
|
1770
|
+
values: personalValues,
|
|
1771
|
+
errors: personalErrors,
|
|
1772
|
+
setValue: (field, next)=>{
|
|
1773
|
+
setPersonalValues((current)=>({
|
|
1774
|
+
...current,
|
|
1775
|
+
[field]: next
|
|
1776
|
+
}));
|
|
1777
|
+
setPersonalErrors((current)=>({
|
|
1778
|
+
...current,
|
|
1779
|
+
[field]: undefined
|
|
1780
|
+
}));
|
|
1781
|
+
},
|
|
1782
|
+
validate: validatePersonal,
|
|
1783
|
+
isActive: personalDataActive
|
|
1784
|
+
},
|
|
1785
|
+
address: {
|
|
1786
|
+
values: addressValues,
|
|
1787
|
+
errors: addressErrors,
|
|
1788
|
+
setValue: (field, next)=>{
|
|
1789
|
+
setAddressValues((current)=>({
|
|
1790
|
+
...current,
|
|
1791
|
+
[field]: next
|
|
1792
|
+
}));
|
|
1793
|
+
setAddressErrors((current)=>({
|
|
1794
|
+
...current,
|
|
1795
|
+
[field]: undefined
|
|
1796
|
+
}));
|
|
1797
|
+
},
|
|
1798
|
+
validate: validateAddressFields,
|
|
1799
|
+
required: addressRequired
|
|
1800
|
+
},
|
|
1801
|
+
bumps: {
|
|
1802
|
+
items: bumpItems,
|
|
1803
|
+
required: requiredBumps,
|
|
1804
|
+
optional: optionalBumps,
|
|
1805
|
+
title: bumpTitle,
|
|
1806
|
+
selectedIds: selectedBumpIds,
|
|
1807
|
+
toggle: toggleBump
|
|
1808
|
+
},
|
|
1809
|
+
pricing,
|
|
1810
|
+
summary,
|
|
1811
|
+
coupon: {
|
|
1812
|
+
code: couponCode,
|
|
1813
|
+
status: couponStatus,
|
|
1814
|
+
result: couponResult,
|
|
1815
|
+
apply: applyCoupon,
|
|
1816
|
+
remove: removeCoupon
|
|
1817
|
+
},
|
|
1818
|
+
freight: {
|
|
1819
|
+
enabled: freightEnabled,
|
|
1820
|
+
status: freight.status,
|
|
1821
|
+
quote: freight.quote,
|
|
1822
|
+
method: freightMethod,
|
|
1823
|
+
select: setFreightMethod
|
|
1824
|
+
},
|
|
1825
|
+
payment: {
|
|
1826
|
+
methods,
|
|
1827
|
+
method,
|
|
1828
|
+
setMethod: setChosenMethod,
|
|
1829
|
+
installments,
|
|
1830
|
+
installment,
|
|
1831
|
+
setInstallment: setChosenInstallment,
|
|
1832
|
+
savedCard,
|
|
1833
|
+
useSavedCard,
|
|
1834
|
+
setUseSavedCard,
|
|
1835
|
+
cardHolderName,
|
|
1836
|
+
setCardHolderName,
|
|
1837
|
+
card,
|
|
1838
|
+
registerCard
|
|
1839
|
+
},
|
|
1840
|
+
submission,
|
|
1841
|
+
submit,
|
|
1842
|
+
reset,
|
|
1843
|
+
callbacks
|
|
1844
|
+
};
|
|
1845
|
+
return /*#__PURE__*/ jsx(CheckoutContext.Provider, {
|
|
1846
|
+
value: value,
|
|
1847
|
+
children: children
|
|
1848
|
+
});
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
|
|
1852
|
+
|
|
1853
|
+
|
|
1854
|
+
|
|
1855
|
+
// `useLayoutEffect` warns during SSR; the card only mounts in the browser anyway.
|
|
1856
|
+
const useClientLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
|
|
1857
|
+
const ELEMENTS_LOCALE = {
|
|
1858
|
+
'pt-BR': 'pt-BR',
|
|
1859
|
+
en: 'en',
|
|
1860
|
+
es: 'es'
|
|
1861
|
+
};
|
|
1862
|
+
/**
|
|
1863
|
+
* Card number, expiry and CVC in a secure frame served by Clickmax. The page never sees the card:
|
|
1864
|
+
* the frame tokenizes it and the purchase sends only the token. Mounts in the browser only; the
|
|
1865
|
+
* server renders an empty container.
|
|
1866
|
+
*
|
|
1867
|
+
* Needs `paymentsOrigin` on `CheckoutProvider`. Renders nothing for a returning buyer paying
|
|
1868
|
+
* with the saved card (see `savedCard`).
|
|
1869
|
+
*/ function CardFields(props) {
|
|
1870
|
+
const { paymentsOrigin, payment, locale } = useCheckout();
|
|
1871
|
+
const containerRef = useRef(null);
|
|
1872
|
+
const cardRef = useRef(null);
|
|
1873
|
+
const propsRef = useRef(props);
|
|
1874
|
+
propsRef.current = props;
|
|
1875
|
+
const showFrame = !payment.useSavedCard;
|
|
1876
|
+
const { registerCard } = payment;
|
|
1877
|
+
// Created once per mount, like react-stripe-js: later prop changes go through `update`.
|
|
1878
|
+
useClientLayoutEffect(()=>{
|
|
1879
|
+
if (!showFrame || !containerRef.current) return;
|
|
1880
|
+
if (!paymentsOrigin) {
|
|
1881
|
+
console.error('[clickmax-checkout] CardFields needs paymentsOrigin on CheckoutProvider', {
|
|
1882
|
+
op: 'mountCard'
|
|
1883
|
+
});
|
|
1884
|
+
return;
|
|
1885
|
+
}
|
|
1886
|
+
const card = createClickmaxElements({
|
|
1887
|
+
paymentsOrigin
|
|
1888
|
+
}).create('card', {
|
|
1889
|
+
appearance: propsRef.current.appearance,
|
|
1890
|
+
locale: ELEMENTS_LOCALE[locale],
|
|
1891
|
+
disabled: propsRef.current.disabled
|
|
1892
|
+
});
|
|
1893
|
+
card.on('ready', ()=>propsRef.current.onReady?.()).on('change', (event)=>propsRef.current.onChange?.(event)).on('focus', (event)=>propsRef.current.onFocus?.(event)).on('blur', (event)=>propsRef.current.onBlur?.(event)).on('loaderror', (event)=>propsRef.current.onLoadError?.(event));
|
|
1894
|
+
card.mount(containerRef.current);
|
|
1895
|
+
cardRef.current = card;
|
|
1896
|
+
registerCard(card);
|
|
1897
|
+
return ()=>{
|
|
1898
|
+
registerCard(undefined);
|
|
1899
|
+
cardRef.current = null;
|
|
1900
|
+
card.destroy();
|
|
1901
|
+
};
|
|
1902
|
+
}, [
|
|
1903
|
+
showFrame,
|
|
1904
|
+
paymentsOrigin,
|
|
1905
|
+
registerCard
|
|
1906
|
+
]);
|
|
1907
|
+
const appearanceKey = JSON.stringify(props.appearance ?? null);
|
|
1908
|
+
useEffect(()=>{
|
|
1909
|
+
const appearance = JSON.parse(appearanceKey);
|
|
1910
|
+
cardRef.current?.update({
|
|
1911
|
+
appearance: appearance ?? undefined,
|
|
1912
|
+
locale: ELEMENTS_LOCALE[locale],
|
|
1913
|
+
disabled: props.disabled
|
|
1914
|
+
});
|
|
1915
|
+
}, [
|
|
1916
|
+
appearanceKey,
|
|
1917
|
+
locale,
|
|
1918
|
+
props.disabled
|
|
1919
|
+
]);
|
|
1920
|
+
if (!showFrame && payment.savedCard) {
|
|
1921
|
+
return props.savedCard ? props.savedCard({
|
|
1922
|
+
...payment.savedCard,
|
|
1923
|
+
useAnother: ()=>payment.setUseSavedCard(false)
|
|
1924
|
+
}) : null;
|
|
1925
|
+
}
|
|
1926
|
+
return /*#__PURE__*/ jsx("div", {
|
|
1927
|
+
ref: containerRef,
|
|
1928
|
+
className: props.className,
|
|
1929
|
+
"data-cx-checkout": "card-fields"
|
|
1930
|
+
});
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
|
|
1934
|
+
|
|
1935
|
+
|
|
1936
|
+
|
|
1937
|
+
|
|
1938
|
+
|
|
1939
|
+
|
|
1940
|
+
|
|
1941
|
+
/** Formats cents with the checkout locale. */ function useFormatMoney() {
|
|
1942
|
+
const { locale } = useCheckout();
|
|
1943
|
+
return useCallback((cents)=>formatMoney(cents, locale), [
|
|
1944
|
+
locale
|
|
1945
|
+
]);
|
|
1946
|
+
}
|
|
1947
|
+
/** Main item and price of the offer. */ function useOfferItem() {
|
|
1948
|
+
const { offer, pricing, payment } = useCheckout();
|
|
1949
|
+
const format = useFormatMoney();
|
|
1950
|
+
const main = pricing.data?.items.find((item)=>item.type === 'main');
|
|
1951
|
+
const price = main?.effectivePrice ?? offer.newPrice ?? offer.originalPrice;
|
|
1952
|
+
const originalPrice = main?.originalPrice ?? offer.originalPrice;
|
|
1953
|
+
const last = payment.installments.at(-1);
|
|
1954
|
+
return {
|
|
1955
|
+
name: offer.checkoutTitle || offer.name,
|
|
1956
|
+
description: offer.showDescription ? offer.description : undefined,
|
|
1957
|
+
imageUrl: offer.thumbnailImage || undefined,
|
|
1958
|
+
price,
|
|
1959
|
+
originalPrice,
|
|
1960
|
+
hasDiscount: price < originalPrice,
|
|
1961
|
+
formattedPrice: format(price),
|
|
1962
|
+
formattedOriginalPrice: format(originalPrice),
|
|
1963
|
+
isRecurrent: offer.isRecurrent,
|
|
1964
|
+
maxInstallment: last ? {
|
|
1965
|
+
installment: last.installment,
|
|
1966
|
+
value: last.value,
|
|
1967
|
+
formattedValue: format(last.value)
|
|
1968
|
+
} : undefined
|
|
1969
|
+
};
|
|
1970
|
+
}
|
|
1971
|
+
/** Order bumps and their selection. */ function useOrderBumps() {
|
|
1972
|
+
return useCheckout().bumps;
|
|
1973
|
+
}
|
|
1974
|
+
/** Personal data fields plus the saved one-click data of a returning buyer. */ function usePersonalData() {
|
|
1975
|
+
const { personalData, oneClick } = useCheckout();
|
|
1976
|
+
return {
|
|
1977
|
+
...personalData,
|
|
1978
|
+
oneClick
|
|
1979
|
+
};
|
|
1980
|
+
}
|
|
1981
|
+
/** Address fields. `required` is `false` for offers that do not ask for an address. */ function useAddress() {
|
|
1982
|
+
return useCheckout().address;
|
|
1983
|
+
}
|
|
1984
|
+
/** Freight quote of physical offers, loaded when the zip code is complete. */ function useFreight() {
|
|
1985
|
+
return useCheckout().freight;
|
|
1986
|
+
}
|
|
1987
|
+
/** Payment method, installments and card state. */ function usePayment() {
|
|
1988
|
+
return useCheckout().payment;
|
|
1989
|
+
}
|
|
1990
|
+
/** Coupon applied to the purchase. Validation and discount come from the server. */ function useCoupon() {
|
|
1991
|
+
const { coupon, offer } = useCheckout();
|
|
1992
|
+
return {
|
|
1993
|
+
...coupon,
|
|
1994
|
+
enabled: offer.showCoupon
|
|
1995
|
+
};
|
|
1996
|
+
}
|
|
1997
|
+
/** Totals of the current selection, with formatted values. */ function useSummary() {
|
|
1998
|
+
const { summary } = useCheckout();
|
|
1999
|
+
const format = useFormatMoney();
|
|
2000
|
+
return {
|
|
2001
|
+
...summary,
|
|
2002
|
+
formatted: {
|
|
2003
|
+
subtotal: format(summary.subtotal),
|
|
2004
|
+
offerDiscount: format(summary.offerDiscount),
|
|
2005
|
+
couponDiscount: format(summary.couponDiscount),
|
|
2006
|
+
platformFee: format(summary.platformFee),
|
|
2007
|
+
freight: format(summary.freight),
|
|
2008
|
+
total: format(summary.total)
|
|
2009
|
+
}
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
/** Purchase state and the function that submits it. */ function useSubmit() {
|
|
2013
|
+
const { submit, reset, submission } = useCheckout();
|
|
2014
|
+
return {
|
|
2015
|
+
submit,
|
|
2016
|
+
reset,
|
|
2017
|
+
submission,
|
|
2018
|
+
isSubmitting: submission.status === 'submitting' || submission.status === 'processing'
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
/**
|
|
2022
|
+
* Seconds left until a deadline, updated every second after hydration. Before hydration it
|
|
2023
|
+
* returns the value of `fallbackSeconds`, so server and client render the same text.
|
|
2024
|
+
*/ function useSecondsUntil(deadline, fallbackSeconds) {
|
|
2025
|
+
const { isHydrated } = useCheckout();
|
|
2026
|
+
const [now, setNow] = useState(undefined);
|
|
2027
|
+
useEffect(()=>{
|
|
2028
|
+
if (!isHydrated || deadline === undefined) return;
|
|
2029
|
+
setNow(Date.now());
|
|
2030
|
+
const timer = setInterval(()=>setNow(Date.now()), 1000);
|
|
2031
|
+
return ()=>clearInterval(timer);
|
|
2032
|
+
}, [
|
|
2033
|
+
isHydrated,
|
|
2034
|
+
deadline
|
|
2035
|
+
]);
|
|
2036
|
+
if (deadline === undefined || now === undefined) return fallbackSeconds;
|
|
2037
|
+
return Math.max(0, Math.ceil((deadline - now) / 1000));
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* Countdown that starts at `seconds` when the page hydrates. The server renders `seconds`, so the
|
|
2041
|
+
* prerendered HTML and the first client render match.
|
|
2042
|
+
*
|
|
2043
|
+
* @param requestedSeconds Length of the countdown. Defaults to 10 minutes.
|
|
2044
|
+
*/ function useCountdown(requestedSeconds) {
|
|
2045
|
+
const seconds = Math.round(positiveFinite(requestedSeconds, 600));
|
|
2046
|
+
const { offer, isHydrated } = useCheckout();
|
|
2047
|
+
const [deadline, setDeadline] = useState(undefined);
|
|
2048
|
+
useEffect(()=>{
|
|
2049
|
+
if (isHydrated) setDeadline(Date.now() + seconds * 1000);
|
|
2050
|
+
}, [
|
|
2051
|
+
isHydrated,
|
|
2052
|
+
seconds
|
|
2053
|
+
]);
|
|
2054
|
+
const left = useSecondsUntil(deadline, seconds);
|
|
2055
|
+
return {
|
|
2056
|
+
secondsLeft: left,
|
|
2057
|
+
minutes: String(Math.floor(left / 60)).padStart(2, '0'),
|
|
2058
|
+
seconds: String(left % 60).padStart(2, '0'),
|
|
2059
|
+
expired: left === 0,
|
|
2060
|
+
enabled: offer.showTimer
|
|
2061
|
+
};
|
|
2062
|
+
}
|
|
2063
|
+
/** The pix waiting for payment, if any, with its countdown and a copy helper. */ function usePix() {
|
|
2064
|
+
const { submission, submit, reset } = useCheckout();
|
|
2065
|
+
const pix = submission.status === 'pix_pending' ? submission.pix : undefined;
|
|
2066
|
+
const left = useSecondsUntil(pix?.expiresAt?.getTime(), Number.POSITIVE_INFINITY);
|
|
2067
|
+
const copy = useCallback(async ()=>{
|
|
2068
|
+
if (!pix || typeof navigator === 'undefined' || !navigator.clipboard) return false;
|
|
2069
|
+
try {
|
|
2070
|
+
await navigator.clipboard.writeText(pix.code);
|
|
2071
|
+
return true;
|
|
2072
|
+
} catch {
|
|
2073
|
+
return false;
|
|
2074
|
+
}
|
|
2075
|
+
}, [
|
|
2076
|
+
pix
|
|
2077
|
+
]);
|
|
2078
|
+
const regenerate = useCallback(()=>{
|
|
2079
|
+
reset();
|
|
2080
|
+
return submit({
|
|
2081
|
+
method: 'pix'
|
|
2082
|
+
});
|
|
2083
|
+
}, [
|
|
2084
|
+
reset,
|
|
2085
|
+
submit
|
|
2086
|
+
]);
|
|
2087
|
+
return {
|
|
2088
|
+
pix,
|
|
2089
|
+
secondsLeft: pix?.expiresAt && Number.isFinite(left) ? left : undefined,
|
|
2090
|
+
expired: Boolean(pix?.expiresAt) && left === 0,
|
|
2091
|
+
copy,
|
|
2092
|
+
regenerate
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
/** The boleto issued for the purchase, if any. */ function useBoleto() {
|
|
2096
|
+
const { submission } = useCheckout();
|
|
2097
|
+
return {
|
|
2098
|
+
boleto: submission.status === 'boleto_issued' ? submission.boleto : undefined
|
|
2099
|
+
};
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* One-time offer (upsell or downsell) actions. Accepting submits the offer like any purchase; a
|
|
2103
|
+
* returning buyer with saved data and card buys with one click.
|
|
2104
|
+
*/ function useUpsell() {
|
|
2105
|
+
const { offer, oneClick, payment, submit, location, callbacks } = useCheckout();
|
|
2106
|
+
const decline = useCallback(()=>{
|
|
2107
|
+
const downsellUrl = location.downsellUrl || offer.configs?.buttons.downsell.url || undefined;
|
|
2108
|
+
callbacks.onUpsellDeclined?.({
|
|
2109
|
+
downsellUrl
|
|
2110
|
+
});
|
|
2111
|
+
return downsellUrl;
|
|
2112
|
+
}, [
|
|
2113
|
+
location.downsellUrl,
|
|
2114
|
+
offer.configs,
|
|
2115
|
+
callbacks
|
|
2116
|
+
]);
|
|
2117
|
+
return {
|
|
2118
|
+
isOneTimeOffer: offer.isOTO,
|
|
2119
|
+
canBuyWithOneClick: Boolean(oneClick.data && payment.savedCard),
|
|
2120
|
+
accept: submit,
|
|
2121
|
+
decline
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
|
|
2126
|
+
|
|
2127
|
+
|
|
2128
|
+
|
|
2129
|
+
|
|
2130
|
+
/** Name, image and price of the offer. Renders on the server from the public offer data. */ function OfferItem({ className, children }) {
|
|
2131
|
+
const item = useOfferItem();
|
|
2132
|
+
if (children) return children(item);
|
|
2133
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2134
|
+
className: className,
|
|
2135
|
+
"data-cx-checkout": "offer-item",
|
|
2136
|
+
children: [
|
|
2137
|
+
safeUrl(item.imageUrl) ? /*#__PURE__*/ jsx("img", {
|
|
2138
|
+
src: safeUrl(item.imageUrl),
|
|
2139
|
+
alt: "",
|
|
2140
|
+
"data-cx-checkout": "offer-image"
|
|
2141
|
+
}) : null,
|
|
2142
|
+
/*#__PURE__*/ jsx("div", {
|
|
2143
|
+
"data-cx-checkout": "offer-name",
|
|
2144
|
+
children: item.name
|
|
2145
|
+
}),
|
|
2146
|
+
item.description ? /*#__PURE__*/ jsx("p", {
|
|
2147
|
+
"data-cx-checkout": "offer-description",
|
|
2148
|
+
children: item.description
|
|
2149
|
+
}) : null,
|
|
2150
|
+
/*#__PURE__*/ jsx(Price, {})
|
|
2151
|
+
]
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
/** Price of the offer, with the original price struck through when there is a discount. */ function Price({ className, children }) {
|
|
2155
|
+
const item = useOfferItem();
|
|
2156
|
+
if (children) return children(item);
|
|
2157
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2158
|
+
className: className,
|
|
2159
|
+
"data-cx-checkout": "price",
|
|
2160
|
+
children: [
|
|
2161
|
+
item.hasDiscount ? /*#__PURE__*/ jsx("s", {
|
|
2162
|
+
"data-cx-checkout": "price-original",
|
|
2163
|
+
children: item.formattedOriginalPrice
|
|
2164
|
+
}) : null,
|
|
2165
|
+
/*#__PURE__*/ jsx("strong", {
|
|
2166
|
+
"data-cx-checkout": "price-current",
|
|
2167
|
+
children: item.formattedPrice
|
|
2168
|
+
}),
|
|
2169
|
+
item.maxInstallment && item.maxInstallment.installment > 1 ? /*#__PURE__*/ jsxs("span", {
|
|
2170
|
+
"data-cx-checkout": "price-installments",
|
|
2171
|
+
children: [
|
|
2172
|
+
item.maxInstallment.installment,
|
|
2173
|
+
"x ",
|
|
2174
|
+
item.maxInstallment.formattedValue
|
|
2175
|
+
]
|
|
2176
|
+
}) : null
|
|
2177
|
+
]
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Order bumps of the offer. Required bumps are listed under "Included in your order", with no
|
|
2182
|
+
* checkbox, and are already in the total. The optional ones follow under the seller's title (or
|
|
2183
|
+
* the translated default), each with a checkbox; that block is hidden when every bump is
|
|
2184
|
+
* required. With `children`, each bump is rendered by it instead.
|
|
2185
|
+
*/ function OrderBumps({ className, children }) {
|
|
2186
|
+
const { required, optional, title, toggle } = useOrderBumps();
|
|
2187
|
+
const { includedInOrder } = useCheckout().messages;
|
|
2188
|
+
const format = useFormatMoney();
|
|
2189
|
+
if (required.length === 0 && optional.length === 0) return null;
|
|
2190
|
+
const toState = (bump)=>({
|
|
2191
|
+
...bump,
|
|
2192
|
+
formattedPrice: format(bump.price),
|
|
2193
|
+
formattedOriginalPrice: format(bump.originalPrice),
|
|
2194
|
+
toggle: (selected)=>toggle(bump.id, selected)
|
|
2195
|
+
});
|
|
2196
|
+
if (children) {
|
|
2197
|
+
return /*#__PURE__*/ jsx("div", {
|
|
2198
|
+
className: className,
|
|
2199
|
+
"data-cx-checkout": "order-bumps",
|
|
2200
|
+
children: [
|
|
2201
|
+
...required,
|
|
2202
|
+
...optional
|
|
2203
|
+
].map((bump)=>/*#__PURE__*/ jsx("div", {
|
|
2204
|
+
children: children(toState(bump))
|
|
2205
|
+
}, bump.id))
|
|
2206
|
+
});
|
|
2207
|
+
}
|
|
2208
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2209
|
+
className: className,
|
|
2210
|
+
"data-cx-checkout": "order-bumps",
|
|
2211
|
+
children: [
|
|
2212
|
+
required.length > 0 ? /*#__PURE__*/ jsxs("section", {
|
|
2213
|
+
"data-cx-checkout": "order-bumps-required",
|
|
2214
|
+
children: [
|
|
2215
|
+
/*#__PURE__*/ jsx("h3", {
|
|
2216
|
+
"data-cx-checkout": "order-bumps-title",
|
|
2217
|
+
children: includedInOrder
|
|
2218
|
+
}),
|
|
2219
|
+
required.map(toState).map((bump)=>/*#__PURE__*/ jsx("div", {
|
|
2220
|
+
"data-cx-checkout": "order-bump",
|
|
2221
|
+
"data-required": "true",
|
|
2222
|
+
children: /*#__PURE__*/ jsx(OrderBumpContent, {
|
|
2223
|
+
bump: bump
|
|
2224
|
+
})
|
|
2225
|
+
}, bump.id))
|
|
2226
|
+
]
|
|
2227
|
+
}) : null,
|
|
2228
|
+
optional.length > 0 ? /*#__PURE__*/ jsxs("section", {
|
|
2229
|
+
"data-cx-checkout": "order-bumps-optional",
|
|
2230
|
+
children: [
|
|
2231
|
+
/*#__PURE__*/ jsx("h3", {
|
|
2232
|
+
"data-cx-checkout": "order-bumps-title",
|
|
2233
|
+
children: title
|
|
2234
|
+
}),
|
|
2235
|
+
optional.map(toState).map((bump)=>/*#__PURE__*/ jsxs("label", {
|
|
2236
|
+
"data-cx-checkout": "order-bump",
|
|
2237
|
+
"data-selected": bump.selected,
|
|
2238
|
+
children: [
|
|
2239
|
+
/*#__PURE__*/ jsx("input", {
|
|
2240
|
+
type: "checkbox",
|
|
2241
|
+
checked: bump.selected,
|
|
2242
|
+
disabled: bump.disabled,
|
|
2243
|
+
onChange: (event)=>bump.toggle(event.target.checked)
|
|
2244
|
+
}),
|
|
2245
|
+
/*#__PURE__*/ jsx(OrderBumpContent, {
|
|
2246
|
+
bump: bump
|
|
2247
|
+
})
|
|
2248
|
+
]
|
|
2249
|
+
}, bump.id))
|
|
2250
|
+
]
|
|
2251
|
+
}) : null
|
|
2252
|
+
]
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
function OrderBumpContent({ bump }) {
|
|
2256
|
+
return /*#__PURE__*/ jsxs(Fragment, {
|
|
2257
|
+
children: [
|
|
2258
|
+
safeUrl(bump.imageUrl) ? /*#__PURE__*/ jsx("img", {
|
|
2259
|
+
src: safeUrl(bump.imageUrl),
|
|
2260
|
+
alt: ""
|
|
2261
|
+
}) : null,
|
|
2262
|
+
/*#__PURE__*/ jsx("span", {
|
|
2263
|
+
"data-cx-checkout": "order-bump-name",
|
|
2264
|
+
children: bump.name
|
|
2265
|
+
}),
|
|
2266
|
+
bump.description ? /*#__PURE__*/ jsx("span", {
|
|
2267
|
+
"data-cx-checkout": "order-bump-description",
|
|
2268
|
+
children: bump.description
|
|
2269
|
+
}) : null,
|
|
2270
|
+
/*#__PURE__*/ jsx("span", {
|
|
2271
|
+
"data-cx-checkout": "order-bump-price",
|
|
2272
|
+
children: bump.formattedPrice
|
|
2273
|
+
})
|
|
2274
|
+
]
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
function useFieldFactory(values, errors, setValue, meta) {
|
|
2278
|
+
const baseId = useId();
|
|
2279
|
+
const result = {};
|
|
2280
|
+
for (const key of Object.keys(meta)){
|
|
2281
|
+
const name = String(key);
|
|
2282
|
+
const id = `${baseId}-${name}`;
|
|
2283
|
+
const error = errors[key];
|
|
2284
|
+
result[key] = {
|
|
2285
|
+
error,
|
|
2286
|
+
props: {
|
|
2287
|
+
id,
|
|
2288
|
+
name,
|
|
2289
|
+
value: String(values[key] ?? ''),
|
|
2290
|
+
onChange: (event)=>setValue(key, event.target.value),
|
|
2291
|
+
'aria-invalid': Boolean(error),
|
|
2292
|
+
'aria-describedby': error ? `${id}-error` : undefined,
|
|
2293
|
+
autoComplete: meta[key].autoComplete,
|
|
2294
|
+
inputMode: meta[key].inputMode
|
|
2295
|
+
}
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
return result;
|
|
2299
|
+
}
|
|
2300
|
+
const PERSONAL_META = {
|
|
2301
|
+
name: {
|
|
2302
|
+
autoComplete: 'name'
|
|
2303
|
+
},
|
|
2304
|
+
email: {
|
|
2305
|
+
autoComplete: 'email',
|
|
2306
|
+
inputMode: 'email'
|
|
2307
|
+
},
|
|
2308
|
+
confirmEmail: {
|
|
2309
|
+
autoComplete: 'email',
|
|
2310
|
+
inputMode: 'email'
|
|
2311
|
+
},
|
|
2312
|
+
phone: {
|
|
2313
|
+
autoComplete: 'tel',
|
|
2314
|
+
inputMode: 'tel'
|
|
2315
|
+
},
|
|
2316
|
+
document: {
|
|
2317
|
+
autoComplete: 'off',
|
|
2318
|
+
inputMode: 'numeric'
|
|
2319
|
+
}
|
|
2320
|
+
};
|
|
2321
|
+
const PERSONAL_LABELS = {
|
|
2322
|
+
name: 'Nome completo',
|
|
2323
|
+
email: 'E-mail',
|
|
2324
|
+
confirmEmail: 'Confirme o e-mail',
|
|
2325
|
+
phone: 'Telefone',
|
|
2326
|
+
document: 'CPF ou CNPJ'
|
|
2327
|
+
};
|
|
2328
|
+
function DefaultField({ label, field }) {
|
|
2329
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2330
|
+
"data-cx-checkout": "field",
|
|
2331
|
+
"data-invalid": Boolean(field.error),
|
|
2332
|
+
children: [
|
|
2333
|
+
/*#__PURE__*/ jsx("label", {
|
|
2334
|
+
htmlFor: field.props.id,
|
|
2335
|
+
children: label
|
|
2336
|
+
}),
|
|
2337
|
+
/*#__PURE__*/ jsx("input", {
|
|
2338
|
+
...field.props
|
|
2339
|
+
}),
|
|
2340
|
+
field.error ? /*#__PURE__*/ jsx("span", {
|
|
2341
|
+
id: `${field.props.id}-error`,
|
|
2342
|
+
role: "alert",
|
|
2343
|
+
"data-cx-checkout": "field-error",
|
|
2344
|
+
children: field.error
|
|
2345
|
+
}) : null
|
|
2346
|
+
]
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
/** Name, email, phone and document of the buyer. */ function PersonalDataFields({ className, labels, children }) {
|
|
2350
|
+
const { values, errors, setValue, isActive, oneClick } = usePersonalData();
|
|
2351
|
+
const fields = useFieldFactory(values, errors, setValue, PERSONAL_META);
|
|
2352
|
+
const state = {
|
|
2353
|
+
fields,
|
|
2354
|
+
oneClick: !isActive && oneClick.data ? {
|
|
2355
|
+
name: oneClick.data.name,
|
|
2356
|
+
email: oneClick.data.email,
|
|
2357
|
+
edit: ()=>oneClick.setEditing(true)
|
|
2358
|
+
} : undefined
|
|
2359
|
+
};
|
|
2360
|
+
if (children) return children(state);
|
|
2361
|
+
const text = {
|
|
2362
|
+
...PERSONAL_LABELS,
|
|
2363
|
+
...labels
|
|
2364
|
+
};
|
|
2365
|
+
if (state.oneClick) {
|
|
2366
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2367
|
+
className: className,
|
|
2368
|
+
"data-cx-checkout": "personal-data",
|
|
2369
|
+
"data-one-click": "true",
|
|
2370
|
+
children: [
|
|
2371
|
+
/*#__PURE__*/ jsx("span", {
|
|
2372
|
+
children: state.oneClick.name
|
|
2373
|
+
}),
|
|
2374
|
+
/*#__PURE__*/ jsx("span", {
|
|
2375
|
+
children: state.oneClick.email
|
|
2376
|
+
}),
|
|
2377
|
+
/*#__PURE__*/ jsx("button", {
|
|
2378
|
+
type: "button",
|
|
2379
|
+
onClick: state.oneClick.edit,
|
|
2380
|
+
children: "Editar"
|
|
2381
|
+
})
|
|
2382
|
+
]
|
|
2383
|
+
});
|
|
2384
|
+
}
|
|
2385
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2386
|
+
className: className,
|
|
2387
|
+
"data-cx-checkout": "personal-data",
|
|
2388
|
+
children: [
|
|
2389
|
+
/*#__PURE__*/ jsx(DefaultField, {
|
|
2390
|
+
label: text.name,
|
|
2391
|
+
field: fields.name
|
|
2392
|
+
}),
|
|
2393
|
+
/*#__PURE__*/ jsx(DefaultField, {
|
|
2394
|
+
label: text.email,
|
|
2395
|
+
field: fields.email
|
|
2396
|
+
}),
|
|
2397
|
+
/*#__PURE__*/ jsx(DefaultField, {
|
|
2398
|
+
label: text.phone,
|
|
2399
|
+
field: fields.phone
|
|
2400
|
+
}),
|
|
2401
|
+
/*#__PURE__*/ jsx(DefaultField, {
|
|
2402
|
+
label: text.document,
|
|
2403
|
+
field: fields.document
|
|
2404
|
+
})
|
|
2405
|
+
]
|
|
2406
|
+
});
|
|
2407
|
+
}
|
|
2408
|
+
const ADDRESS_META = {
|
|
2409
|
+
zipCode: {
|
|
2410
|
+
autoComplete: 'postal-code',
|
|
2411
|
+
inputMode: 'numeric'
|
|
2412
|
+
},
|
|
2413
|
+
street: {
|
|
2414
|
+
autoComplete: 'address-line1'
|
|
2415
|
+
},
|
|
2416
|
+
number: {
|
|
2417
|
+
autoComplete: 'off'
|
|
2418
|
+
},
|
|
2419
|
+
complement: {
|
|
2420
|
+
autoComplete: 'address-line2'
|
|
2421
|
+
},
|
|
2422
|
+
neighborhood: {
|
|
2423
|
+
autoComplete: 'address-level3'
|
|
2424
|
+
},
|
|
2425
|
+
city: {
|
|
2426
|
+
autoComplete: 'address-level2'
|
|
2427
|
+
},
|
|
2428
|
+
state: {
|
|
2429
|
+
autoComplete: 'address-level1'
|
|
2430
|
+
},
|
|
2431
|
+
country: {
|
|
2432
|
+
autoComplete: 'country'
|
|
2433
|
+
}
|
|
2434
|
+
};
|
|
2435
|
+
const ADDRESS_LABELS = {
|
|
2436
|
+
zipCode: 'CEP',
|
|
2437
|
+
street: 'Rua',
|
|
2438
|
+
number: 'Número',
|
|
2439
|
+
complement: 'Complemento',
|
|
2440
|
+
neighborhood: 'Bairro',
|
|
2441
|
+
city: 'Cidade',
|
|
2442
|
+
state: 'Estado',
|
|
2443
|
+
country: 'País'
|
|
2444
|
+
};
|
|
2445
|
+
/**
|
|
2446
|
+
* Address of the buyer. Renders nothing when the offer does not ask for one (and while a
|
|
2447
|
+
* returning buyer buys with saved data). Physical offers quote freight from the zip code.
|
|
2448
|
+
*/ function AddressFields({ className, labels, children }) {
|
|
2449
|
+
const { values, errors, setValue, required } = useAddress();
|
|
2450
|
+
const fields = useFieldFactory(values, errors, setValue, ADDRESS_META);
|
|
2451
|
+
if (children) return children({
|
|
2452
|
+
fields,
|
|
2453
|
+
required
|
|
2454
|
+
});
|
|
2455
|
+
if (!required) return null;
|
|
2456
|
+
const text = {
|
|
2457
|
+
...ADDRESS_LABELS,
|
|
2458
|
+
...labels
|
|
2459
|
+
};
|
|
2460
|
+
return /*#__PURE__*/ jsx("div", {
|
|
2461
|
+
className: className,
|
|
2462
|
+
"data-cx-checkout": "address",
|
|
2463
|
+
children: [
|
|
2464
|
+
'zipCode',
|
|
2465
|
+
'street',
|
|
2466
|
+
'number',
|
|
2467
|
+
'complement',
|
|
2468
|
+
'neighborhood',
|
|
2469
|
+
'city',
|
|
2470
|
+
'state'
|
|
2471
|
+
].map((key)=>/*#__PURE__*/ jsx(DefaultField, {
|
|
2472
|
+
label: text[key],
|
|
2473
|
+
field: fields[key]
|
|
2474
|
+
}, key))
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
/** Freight options of a physical offer, once the zip code is known. */ function FreightOptions({ className, children }) {
|
|
2478
|
+
const freight = useFreight();
|
|
2479
|
+
const format = useFormatMoney();
|
|
2480
|
+
if (children) return children({
|
|
2481
|
+
...freight,
|
|
2482
|
+
formatMoney: format
|
|
2483
|
+
});
|
|
2484
|
+
if (!freight.enabled || !freight.quote) return null;
|
|
2485
|
+
return /*#__PURE__*/ jsx("fieldset", {
|
|
2486
|
+
className: className,
|
|
2487
|
+
"data-cx-checkout": "freight",
|
|
2488
|
+
children: freight.quote.freights.map((option)=>{
|
|
2489
|
+
const { method } = option;
|
|
2490
|
+
if (!isFreightMethod(method)) return null;
|
|
2491
|
+
return /*#__PURE__*/ jsxs("label", {
|
|
2492
|
+
children: [
|
|
2493
|
+
/*#__PURE__*/ jsx("input", {
|
|
2494
|
+
type: "radio",
|
|
2495
|
+
name: "cx-freight",
|
|
2496
|
+
checked: freight.method === option.method,
|
|
2497
|
+
onChange: ()=>freight.select(method)
|
|
2498
|
+
}),
|
|
2499
|
+
option.method,
|
|
2500
|
+
" ",
|
|
2501
|
+
format(option.value),
|
|
2502
|
+
option.days ? ` (${option.days}d)` : null
|
|
2503
|
+
]
|
|
2504
|
+
}, option.method);
|
|
2505
|
+
})
|
|
2506
|
+
});
|
|
2507
|
+
}
|
|
2508
|
+
// endregion
|
|
2509
|
+
// region Payment
|
|
2510
|
+
const METHOD_LABELS = {
|
|
2511
|
+
credit: 'Cartão de crédito',
|
|
2512
|
+
pix: 'Pix',
|
|
2513
|
+
boleto: 'Boleto'
|
|
2514
|
+
};
|
|
2515
|
+
/** Payment methods available for the current selection (decided by the server). */ function PaymentMethods({ className, labels, children }) {
|
|
2516
|
+
const { methods, method, setMethod } = usePayment();
|
|
2517
|
+
if (children) return children({
|
|
2518
|
+
methods,
|
|
2519
|
+
method,
|
|
2520
|
+
select: setMethod
|
|
2521
|
+
});
|
|
2522
|
+
const text = {
|
|
2523
|
+
...METHOD_LABELS,
|
|
2524
|
+
...labels
|
|
2525
|
+
};
|
|
2526
|
+
return /*#__PURE__*/ jsx("div", {
|
|
2527
|
+
className: className,
|
|
2528
|
+
role: "radiogroup",
|
|
2529
|
+
"data-cx-checkout": "payment-methods",
|
|
2530
|
+
children: methods.map((value)=>/*#__PURE__*/ jsxs("label", {
|
|
2531
|
+
"data-selected": value === method,
|
|
2532
|
+
children: [
|
|
2533
|
+
/*#__PURE__*/ jsx("input", {
|
|
2534
|
+
type: "radio",
|
|
2535
|
+
name: "cx-payment-method",
|
|
2536
|
+
checked: value === method,
|
|
2537
|
+
onChange: ()=>setMethod(value)
|
|
2538
|
+
}),
|
|
2539
|
+
text[value]
|
|
2540
|
+
]
|
|
2541
|
+
}, value))
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2544
|
+
/** Installment options of a card purchase, computed by the server. */ function Installments({ className, children }) {
|
|
2545
|
+
const { installments, installment, setInstallment, method } = usePayment();
|
|
2546
|
+
const format = useFormatMoney();
|
|
2547
|
+
const options = installments.map((option)=>({
|
|
2548
|
+
...option,
|
|
2549
|
+
label: `${option.installment}x ${format(option.value)}`
|
|
2550
|
+
}));
|
|
2551
|
+
if (children) return children({
|
|
2552
|
+
options,
|
|
2553
|
+
installment,
|
|
2554
|
+
select: setInstallment
|
|
2555
|
+
});
|
|
2556
|
+
if (method !== 'credit' || options.length === 0) return null;
|
|
2557
|
+
return /*#__PURE__*/ jsx("select", {
|
|
2558
|
+
className: className,
|
|
2559
|
+
"data-cx-checkout": "installments",
|
|
2560
|
+
value: installment,
|
|
2561
|
+
onChange: (event)=>setInstallment(Number(event.target.value)),
|
|
2562
|
+
children: options.map((option)=>/*#__PURE__*/ jsx("option", {
|
|
2563
|
+
value: option.installment,
|
|
2564
|
+
children: option.label
|
|
2565
|
+
}, option.installment))
|
|
2566
|
+
});
|
|
2567
|
+
}
|
|
2568
|
+
/** QR code and copy-and-paste code of a pending pix, with its countdown. */ function PixPayment({ className, children }) {
|
|
2569
|
+
const pix = usePix();
|
|
2570
|
+
const [copied, setCopied] = useState(false);
|
|
2571
|
+
if (children) return children(pix);
|
|
2572
|
+
if (!pix.pix) return null;
|
|
2573
|
+
const minutes = pix.secondsLeft === undefined ? undefined : Math.floor(pix.secondsLeft / 60);
|
|
2574
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2575
|
+
className: className,
|
|
2576
|
+
"data-cx-checkout": "pix",
|
|
2577
|
+
"data-expired": pix.expired,
|
|
2578
|
+
children: [
|
|
2579
|
+
/*#__PURE__*/ jsx("img", {
|
|
2580
|
+
src: safeUrl(pix.pix.qrcodeUrl),
|
|
2581
|
+
alt: "QR code pix",
|
|
2582
|
+
"data-cx-checkout": "pix-qrcode"
|
|
2583
|
+
}),
|
|
2584
|
+
/*#__PURE__*/ jsx("input", {
|
|
2585
|
+
readOnly: true,
|
|
2586
|
+
value: pix.pix.code,
|
|
2587
|
+
"data-cx-checkout": "pix-code"
|
|
2588
|
+
}),
|
|
2589
|
+
/*#__PURE__*/ jsx("button", {
|
|
2590
|
+
type: "button",
|
|
2591
|
+
onClick: async ()=>setCopied(await pix.copy()),
|
|
2592
|
+
"data-cx-checkout": "pix-copy",
|
|
2593
|
+
children: copied ? 'Copiado' : 'Copiar código'
|
|
2594
|
+
}),
|
|
2595
|
+
pix.secondsLeft !== undefined && minutes !== undefined ? /*#__PURE__*/ jsxs("span", {
|
|
2596
|
+
"data-cx-checkout": "pix-countdown",
|
|
2597
|
+
children: [
|
|
2598
|
+
String(minutes).padStart(2, '0'),
|
|
2599
|
+
":",
|
|
2600
|
+
String(pix.secondsLeft % 60).padStart(2, '0')
|
|
2601
|
+
]
|
|
2602
|
+
}) : null,
|
|
2603
|
+
pix.expired ? /*#__PURE__*/ jsx("button", {
|
|
2604
|
+
type: "button",
|
|
2605
|
+
onClick: ()=>void pix.regenerate(),
|
|
2606
|
+
"data-cx-checkout": "pix-regenerate",
|
|
2607
|
+
children: "Gerar novo c\xf3digo"
|
|
2608
|
+
}) : null
|
|
2609
|
+
]
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
/** Link and barcode of an issued boleto. */ function BoletoPayment({ className, children }) {
|
|
2613
|
+
const state = useBoleto();
|
|
2614
|
+
if (children) return children(state);
|
|
2615
|
+
if (!state.boleto) return null;
|
|
2616
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2617
|
+
className: className,
|
|
2618
|
+
"data-cx-checkout": "boleto",
|
|
2619
|
+
children: [
|
|
2620
|
+
/*#__PURE__*/ jsx("input", {
|
|
2621
|
+
readOnly: true,
|
|
2622
|
+
value: state.boleto.barcode,
|
|
2623
|
+
"data-cx-checkout": "boleto-barcode"
|
|
2624
|
+
}),
|
|
2625
|
+
/*#__PURE__*/ jsx("a", {
|
|
2626
|
+
href: safeUrl(state.boleto.boletoUrl),
|
|
2627
|
+
target: "_blank",
|
|
2628
|
+
rel: "noreferrer",
|
|
2629
|
+
children: "Abrir boleto"
|
|
2630
|
+
})
|
|
2631
|
+
]
|
|
2632
|
+
});
|
|
2633
|
+
}
|
|
2634
|
+
/** Subtotal, discounts, fees, freight and total of the current selection. */ function OrderSummary({ className, children }) {
|
|
2635
|
+
const summary = useSummary();
|
|
2636
|
+
if (children) return children(summary);
|
|
2637
|
+
const rows = [
|
|
2638
|
+
[
|
|
2639
|
+
'Subtotal',
|
|
2640
|
+
summary.formatted.subtotal,
|
|
2641
|
+
true
|
|
2642
|
+
],
|
|
2643
|
+
[
|
|
2644
|
+
'Desconto',
|
|
2645
|
+
`- ${summary.formatted.offerDiscount}`,
|
|
2646
|
+
summary.offerDiscount > 0
|
|
2647
|
+
],
|
|
2648
|
+
[
|
|
2649
|
+
'Cupom',
|
|
2650
|
+
`- ${summary.formatted.couponDiscount}`,
|
|
2651
|
+
summary.couponDiscount > 0
|
|
2652
|
+
],
|
|
2653
|
+
[
|
|
2654
|
+
'Taxa',
|
|
2655
|
+
summary.formatted.platformFee,
|
|
2656
|
+
summary.platformFee > 0
|
|
2657
|
+
],
|
|
2658
|
+
[
|
|
2659
|
+
'Frete',
|
|
2660
|
+
summary.formatted.freight,
|
|
2661
|
+
summary.freight > 0
|
|
2662
|
+
]
|
|
2663
|
+
];
|
|
2664
|
+
return /*#__PURE__*/ jsxs("dl", {
|
|
2665
|
+
className: className,
|
|
2666
|
+
"data-cx-checkout": "summary",
|
|
2667
|
+
"data-estimate": summary.isEstimate,
|
|
2668
|
+
children: [
|
|
2669
|
+
rows.filter(([, , show])=>show).map(([label, value])=>/*#__PURE__*/ jsxs("div", {
|
|
2670
|
+
children: [
|
|
2671
|
+
/*#__PURE__*/ jsx("dt", {
|
|
2672
|
+
children: label
|
|
2673
|
+
}),
|
|
2674
|
+
/*#__PURE__*/ jsx("dd", {
|
|
2675
|
+
children: value
|
|
2676
|
+
})
|
|
2677
|
+
]
|
|
2678
|
+
}, label)),
|
|
2679
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2680
|
+
"data-cx-checkout": "summary-total",
|
|
2681
|
+
children: [
|
|
2682
|
+
/*#__PURE__*/ jsx("dt", {
|
|
2683
|
+
children: "Total"
|
|
2684
|
+
}),
|
|
2685
|
+
/*#__PURE__*/ jsx("dd", {
|
|
2686
|
+
children: summary.formatted.total
|
|
2687
|
+
})
|
|
2688
|
+
]
|
|
2689
|
+
})
|
|
2690
|
+
]
|
|
2691
|
+
});
|
|
2692
|
+
}
|
|
2693
|
+
/** Coupon input. Renders nothing when the offer does not accept coupons. */ function CouponField({ className, children }) {
|
|
2694
|
+
const coupon = useCoupon();
|
|
2695
|
+
const [draft, setDraft] = useState('');
|
|
2696
|
+
if (children) return children(coupon);
|
|
2697
|
+
if (!coupon.enabled) return null;
|
|
2698
|
+
if (coupon.code) {
|
|
2699
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2700
|
+
className: className,
|
|
2701
|
+
"data-cx-checkout": "coupon",
|
|
2702
|
+
"data-status": coupon.status,
|
|
2703
|
+
children: [
|
|
2704
|
+
/*#__PURE__*/ jsx("span", {
|
|
2705
|
+
children: coupon.code
|
|
2706
|
+
}),
|
|
2707
|
+
/*#__PURE__*/ jsx("button", {
|
|
2708
|
+
type: "button",
|
|
2709
|
+
onClick: coupon.remove,
|
|
2710
|
+
children: "Remover"
|
|
2711
|
+
})
|
|
2712
|
+
]
|
|
2713
|
+
});
|
|
2714
|
+
}
|
|
2715
|
+
const onSubmit = (event)=>{
|
|
2716
|
+
event.preventDefault();
|
|
2717
|
+
void coupon.apply(draft);
|
|
2718
|
+
};
|
|
2719
|
+
return /*#__PURE__*/ jsxs("form", {
|
|
2720
|
+
className: className,
|
|
2721
|
+
onSubmit: onSubmit,
|
|
2722
|
+
"data-cx-checkout": "coupon",
|
|
2723
|
+
"data-status": coupon.status,
|
|
2724
|
+
children: [
|
|
2725
|
+
/*#__PURE__*/ jsx("input", {
|
|
2726
|
+
value: draft,
|
|
2727
|
+
onChange: (event)=>setDraft(event.target.value),
|
|
2728
|
+
"aria-label": "Cupom"
|
|
2729
|
+
}),
|
|
2730
|
+
/*#__PURE__*/ jsx("button", {
|
|
2731
|
+
type: "submit",
|
|
2732
|
+
disabled: coupon.status === 'validating',
|
|
2733
|
+
children: "Aplicar"
|
|
2734
|
+
})
|
|
2735
|
+
]
|
|
2736
|
+
});
|
|
2737
|
+
}
|
|
2738
|
+
/** Urgency countdown. Shown only when the offer enables the timer, unless `force`. */ function CountdownTimer({ seconds, force, className, children }) {
|
|
2739
|
+
const countdown = useCountdown(seconds);
|
|
2740
|
+
if (!countdown.enabled && !force) return null;
|
|
2741
|
+
if (children) return children(countdown);
|
|
2742
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
2743
|
+
className: className,
|
|
2744
|
+
"data-cx-checkout": "timer",
|
|
2745
|
+
"data-expired": countdown.expired,
|
|
2746
|
+
children: [
|
|
2747
|
+
countdown.minutes,
|
|
2748
|
+
":",
|
|
2749
|
+
countdown.seconds
|
|
2750
|
+
]
|
|
2751
|
+
});
|
|
2752
|
+
}
|
|
2753
|
+
/** Submits the purchase with the selected method. */ function SubmitButton({ className, label = 'Finalizar compra', children }) {
|
|
2754
|
+
const state = useSubmit();
|
|
2755
|
+
if (children) return children(state);
|
|
2756
|
+
return /*#__PURE__*/ jsx("button", {
|
|
2757
|
+
type: "button",
|
|
2758
|
+
className: className,
|
|
2759
|
+
"data-cx-checkout": "submit",
|
|
2760
|
+
disabled: state.isSubmitting,
|
|
2761
|
+
"aria-busy": state.isSubmitting,
|
|
2762
|
+
onClick: ()=>void state.submit(),
|
|
2763
|
+
children: label
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2766
|
+
/** Message of a declined or failed purchase. Renders nothing otherwise. */ function CheckoutError({ className, children }) {
|
|
2767
|
+
const { submission } = useSubmit();
|
|
2768
|
+
if (!submission.error) return null;
|
|
2769
|
+
const state = {
|
|
2770
|
+
message: submission.error,
|
|
2771
|
+
code: submission.errorCode
|
|
2772
|
+
};
|
|
2773
|
+
if (children) return children(state);
|
|
2774
|
+
return /*#__PURE__*/ jsx("p", {
|
|
2775
|
+
className: className,
|
|
2776
|
+
role: "alert",
|
|
2777
|
+
"data-cx-checkout": "error",
|
|
2778
|
+
children: state.message
|
|
2779
|
+
});
|
|
2780
|
+
}
|
|
2781
|
+
/** Buys the one-time offer. A returning buyer with a saved card buys with one click. */ function UpsellAcceptButton({ className, label = 'Sim, quero aproveitar', children }) {
|
|
2782
|
+
const upsell = useUpsell();
|
|
2783
|
+
const { isSubmitting } = useSubmit();
|
|
2784
|
+
if (children) return children({
|
|
2785
|
+
...upsell,
|
|
2786
|
+
isSubmitting
|
|
2787
|
+
});
|
|
2788
|
+
return /*#__PURE__*/ jsx("button", {
|
|
2789
|
+
type: "button",
|
|
2790
|
+
className: className,
|
|
2791
|
+
"data-cx-checkout": "upsell-accept",
|
|
2792
|
+
disabled: isSubmitting,
|
|
2793
|
+
"aria-busy": isSubmitting,
|
|
2794
|
+
onClick: ()=>void upsell.accept(),
|
|
2795
|
+
children: label
|
|
2796
|
+
});
|
|
2797
|
+
}
|
|
2798
|
+
/** Declines the one-time offer. */ function UpsellDeclineButton({ className, label = 'Não, obrigado', navigate = true, children }) {
|
|
2799
|
+
const upsell = useUpsell();
|
|
2800
|
+
if (children) return children(upsell);
|
|
2801
|
+
return /*#__PURE__*/ jsx("button", {
|
|
2802
|
+
type: "button",
|
|
2803
|
+
className: className,
|
|
2804
|
+
"data-cx-checkout": "upsell-decline",
|
|
2805
|
+
onClick: ()=>{
|
|
2806
|
+
const url = safeUrl(upsell.decline());
|
|
2807
|
+
if (navigate && url && typeof window !== 'undefined') window.location.assign(url);
|
|
2808
|
+
},
|
|
2809
|
+
children: label
|
|
2810
|
+
});
|
|
2811
|
+
} // endregion
|
|
2812
|
+
|
|
2813
|
+
|
|
2814
|
+
|
|
2815
|
+
|
|
2816
|
+
|
|
2817
|
+
|
|
2818
|
+
|
|
2819
|
+
|
|
2820
|
+
|
|
2821
|
+
|
|
2822
|
+
export { AddressFields, BoletoPayment, CardFields, CheckoutApiError, CheckoutError, CheckoutProvider, ClickmaxElementsError, CountdownTimer, CouponField, DEFAULT_PAYMENTS_BASE_URL, FreightOptions, Installments, OfferItem, OrderBumps, OrderSummary, PaymentMethods, PersonalDataFields, PixPayment, Price, SubmitButton, UpsellAcceptButton, UpsellDeclineButton, createCheckoutApi, formatMoney, isValidDocument, parseTelephone, useAddress, useBoleto, useCheckout, useCountdown, useCoupon, useFormatMoney, useFreight, useOfferItem, useOrderBumps, usePayment, usePersonalData, usePix, useSubmit, useSummary, useUpsell };
|