@clickmax/checkout-react 12.5.16 → 12.5.18
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/README.md +64 -1
- package/dist/index.d.ts +591 -3
- package/dist/index.js +1767 -55
- package/dist/theme.css +56 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -79,6 +79,38 @@ function readError(status, body) {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
|
|
82
|
+
const getGetCheckoutSocialProofUrl = (params)=>{
|
|
83
|
+
const normalizedParams = new URLSearchParams();
|
|
84
|
+
Object.entries(params || {}).forEach(([key, value])=>{
|
|
85
|
+
if (value !== undefined) {
|
|
86
|
+
normalizedParams.append(key, value === null ? 'null' : String(value));
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
const stringifiedParams = normalizedParams.toString();
|
|
90
|
+
return stringifiedParams.length > 0 ? `/checkout/offer/social-proof?${stringifiedParams}` : `/checkout/offer/social-proof`;
|
|
91
|
+
};
|
|
92
|
+
const getCheckoutSocialProof = async (params, options)=>{
|
|
93
|
+
return http(getGetCheckoutSocialProofUrl(params), {
|
|
94
|
+
...options,
|
|
95
|
+
method: 'GET'
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
const getGetCheckoutRecentActivityUrl = (params)=>{
|
|
99
|
+
const normalizedParams = new URLSearchParams();
|
|
100
|
+
Object.entries(params || {}).forEach(([key, value])=>{
|
|
101
|
+
if (value !== undefined) {
|
|
102
|
+
normalizedParams.append(key, value === null ? 'null' : String(value));
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
const stringifiedParams = normalizedParams.toString();
|
|
106
|
+
return stringifiedParams.length > 0 ? `/checkout/offer/recent-activity?${stringifiedParams}` : `/checkout/offer/recent-activity`;
|
|
107
|
+
};
|
|
108
|
+
const getCheckoutRecentActivity = async (params, options)=>{
|
|
109
|
+
return http(getGetCheckoutRecentActivityUrl(params), {
|
|
110
|
+
...options,
|
|
111
|
+
method: 'GET'
|
|
112
|
+
});
|
|
113
|
+
};
|
|
82
114
|
const getOfferCheckoutUrl = ()=>{
|
|
83
115
|
return `/checkout/offer`;
|
|
84
116
|
};
|
|
@@ -164,6 +196,84 @@ const getCheckoutDetails = async (id, options)=>{
|
|
|
164
196
|
method: 'GET'
|
|
165
197
|
});
|
|
166
198
|
};
|
|
199
|
+
const getTrackCheckoutLeadsUrl = ()=>{
|
|
200
|
+
return `/checkout/offer/track`;
|
|
201
|
+
};
|
|
202
|
+
const trackCheckoutLeads = async (trackCheckoutLeadsBody, options)=>{
|
|
203
|
+
const getHeaders = (h)=>{
|
|
204
|
+
if (!h) return {};
|
|
205
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
206
|
+
if (Symbol.iterator in h) {
|
|
207
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
208
|
+
}
|
|
209
|
+
const headers = {};
|
|
210
|
+
for (const [name, value] of Object.entries(h)){
|
|
211
|
+
if (value !== undefined) headers[name] = value;
|
|
212
|
+
}
|
|
213
|
+
return headers;
|
|
214
|
+
};
|
|
215
|
+
return http(getTrackCheckoutLeadsUrl(), {
|
|
216
|
+
...options,
|
|
217
|
+
method: 'POST',
|
|
218
|
+
headers: {
|
|
219
|
+
'Content-Type': 'application/json',
|
|
220
|
+
...getHeaders(options?.headers)
|
|
221
|
+
},
|
|
222
|
+
body: JSON.stringify(trackCheckoutLeadsBody)
|
|
223
|
+
});
|
|
224
|
+
};
|
|
225
|
+
const getTrackCheckoutInteractionUrl = ()=>{
|
|
226
|
+
return `/checkout/offer/track-interaction`;
|
|
227
|
+
};
|
|
228
|
+
const trackCheckoutInteraction = async (trackCheckoutInteractionBody, options)=>{
|
|
229
|
+
const getHeaders = (h)=>{
|
|
230
|
+
if (!h) return {};
|
|
231
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
232
|
+
if (Symbol.iterator in h) {
|
|
233
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
234
|
+
}
|
|
235
|
+
const headers = {};
|
|
236
|
+
for (const [name, value] of Object.entries(h)){
|
|
237
|
+
if (value !== undefined) headers[name] = value;
|
|
238
|
+
}
|
|
239
|
+
return headers;
|
|
240
|
+
};
|
|
241
|
+
return http(getTrackCheckoutInteractionUrl(), {
|
|
242
|
+
...options,
|
|
243
|
+
method: 'POST',
|
|
244
|
+
headers: {
|
|
245
|
+
'Content-Type': 'application/json',
|
|
246
|
+
...getHeaders(options?.headers)
|
|
247
|
+
},
|
|
248
|
+
body: JSON.stringify(trackCheckoutInteractionBody)
|
|
249
|
+
});
|
|
250
|
+
};
|
|
251
|
+
const getDispatchCheckoutPixelEventUrl = ()=>{
|
|
252
|
+
return `/checkout/pixels/dispatch`;
|
|
253
|
+
};
|
|
254
|
+
const dispatchCheckoutPixelEvent = async (dispatchCheckoutPixelEventBody, options)=>{
|
|
255
|
+
const getHeaders = (h)=>{
|
|
256
|
+
if (!h) return {};
|
|
257
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
258
|
+
if (Symbol.iterator in h) {
|
|
259
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
260
|
+
}
|
|
261
|
+
const headers = {};
|
|
262
|
+
for (const [name, value] of Object.entries(h)){
|
|
263
|
+
if (value !== undefined) headers[name] = value;
|
|
264
|
+
}
|
|
265
|
+
return headers;
|
|
266
|
+
};
|
|
267
|
+
return http(getDispatchCheckoutPixelEventUrl(), {
|
|
268
|
+
...options,
|
|
269
|
+
method: 'POST',
|
|
270
|
+
headers: {
|
|
271
|
+
'Content-Type': 'application/json',
|
|
272
|
+
...getHeaders(options?.headers)
|
|
273
|
+
},
|
|
274
|
+
body: JSON.stringify(dispatchCheckoutPixelEventBody)
|
|
275
|
+
});
|
|
276
|
+
};
|
|
167
277
|
const getValidateCheckoutCouponUrl = ()=>{
|
|
168
278
|
return `/checkout/coupon/validate`;
|
|
169
279
|
};
|
|
@@ -190,6 +300,58 @@ const validateCheckoutCoupon = async (validateCheckoutCouponBody, options)=>{
|
|
|
190
300
|
body: JSON.stringify(validateCheckoutCouponBody)
|
|
191
301
|
});
|
|
192
302
|
};
|
|
303
|
+
const getCheckCheckoutOfferEligibilityUrl = ()=>{
|
|
304
|
+
return `/checkout/offer/eligibility`;
|
|
305
|
+
};
|
|
306
|
+
const checkCheckoutOfferEligibility = async (checkCheckoutOfferEligibilityBody, options)=>{
|
|
307
|
+
const getHeaders = (h)=>{
|
|
308
|
+
if (!h) return {};
|
|
309
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
310
|
+
if (Symbol.iterator in h) {
|
|
311
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
312
|
+
}
|
|
313
|
+
const headers = {};
|
|
314
|
+
for (const [name, value] of Object.entries(h)){
|
|
315
|
+
if (value !== undefined) headers[name] = value;
|
|
316
|
+
}
|
|
317
|
+
return headers;
|
|
318
|
+
};
|
|
319
|
+
return http(getCheckCheckoutOfferEligibilityUrl(), {
|
|
320
|
+
...options,
|
|
321
|
+
method: 'POST',
|
|
322
|
+
headers: {
|
|
323
|
+
'Content-Type': 'application/json',
|
|
324
|
+
...getHeaders(options?.headers)
|
|
325
|
+
},
|
|
326
|
+
body: JSON.stringify(checkCheckoutOfferEligibilityBody)
|
|
327
|
+
});
|
|
328
|
+
};
|
|
329
|
+
const getFindCheckoutAutoCouponUrl = ()=>{
|
|
330
|
+
return `/checkout/coupon/auto`;
|
|
331
|
+
};
|
|
332
|
+
const findCheckoutAutoCoupon = async (findCheckoutAutoCouponBody, options)=>{
|
|
333
|
+
const getHeaders = (h)=>{
|
|
334
|
+
if (!h) return {};
|
|
335
|
+
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
|
336
|
+
if (Symbol.iterator in h) {
|
|
337
|
+
return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
|
|
338
|
+
}
|
|
339
|
+
const headers = {};
|
|
340
|
+
for (const [name, value] of Object.entries(h)){
|
|
341
|
+
if (value !== undefined) headers[name] = value;
|
|
342
|
+
}
|
|
343
|
+
return headers;
|
|
344
|
+
};
|
|
345
|
+
return http(getFindCheckoutAutoCouponUrl(), {
|
|
346
|
+
...options,
|
|
347
|
+
method: 'POST',
|
|
348
|
+
headers: {
|
|
349
|
+
'Content-Type': 'application/json',
|
|
350
|
+
...getHeaders(options?.headers)
|
|
351
|
+
},
|
|
352
|
+
body: JSON.stringify(findCheckoutAutoCouponBody)
|
|
353
|
+
});
|
|
354
|
+
};
|
|
193
355
|
const getGetCheckoutPricingUrl = ()=>{
|
|
194
356
|
return `/checkout/pricing`;
|
|
195
357
|
};
|
|
@@ -275,7 +437,18 @@ function publicOfferQuery({ bumps, bumpTitle, mode, ...rest }) {
|
|
|
275
437
|
}
|
|
276
438
|
}),
|
|
277
439
|
getPurchaseStatus: (jobId, options)=>getCheckoutStatus(jobId, call(options)),
|
|
278
|
-
getPurchaseDetails: (transactionId, options)=>getCheckoutDetails(transactionId, call(options))
|
|
440
|
+
getPurchaseDetails: (transactionId, options)=>getCheckoutDetails(transactionId, call(options)),
|
|
441
|
+
getSocialProof: (params, options)=>getCheckoutSocialProof(params, call(options)),
|
|
442
|
+
getRecentActivity: (params, options)=>getCheckoutRecentActivity(params, call(options)),
|
|
443
|
+
findAutoCoupon: async (body, options)=>(await findCheckoutAutoCoupon(body, call(options))).coupon,
|
|
444
|
+
checkEligibility: (body, options)=>checkCheckoutOfferEligibility(body, call(options)),
|
|
445
|
+
trackLead: async (body, options)=>{
|
|
446
|
+
await trackCheckoutLeads(body, call(options));
|
|
447
|
+
},
|
|
448
|
+
trackInteraction: async (body, options)=>{
|
|
449
|
+
await trackCheckoutInteraction(body, call(options));
|
|
450
|
+
},
|
|
451
|
+
dispatchPixelEvent: (body, options)=>dispatchCheckoutPixelEvent(body, call(options))
|
|
279
452
|
};
|
|
280
453
|
}
|
|
281
454
|
|
|
@@ -656,9 +829,43 @@ const PT_BR = {
|
|
|
656
829
|
purchaseTimeout: 'A compra está demorando. Confira seu e-mail antes de tentar de novo.',
|
|
657
830
|
pixExpired: 'O código pix expirou. Gere outro.',
|
|
658
831
|
offerBuyerNotEligible: 'Esta oferta não está disponível para este e-mail.',
|
|
832
|
+
checkoutUnavailableTitle: 'Produto temporariamente indisponível',
|
|
833
|
+
checkoutUnavailable: 'Este produto não está disponível para compra no momento. Para mais informações, entre em contato com o suporte do vendedor',
|
|
834
|
+
offerPendingApproval: 'O checkout estará liberado para vendas assim que o produto for aprovado pela moderação.',
|
|
835
|
+
trialUnavailable: 'Este e-mail já usou o período de teste deste produto. A primeira cobrança será feita hoje.',
|
|
836
|
+
affiliateAccountNotice: 'Ao comprar, você ganha uma conta Clickmax gratuita para indicar este produto e ganhar comissão.',
|
|
659
837
|
includedInOrder: 'Incluído no seu pedido',
|
|
660
838
|
specialOffer: 'Oferta especial',
|
|
661
|
-
specialOffers: 'Ofertas especiais'
|
|
839
|
+
specialOffers: 'Ofertas especiais',
|
|
840
|
+
perMonth: '/mês',
|
|
841
|
+
perYear: '/ano',
|
|
842
|
+
perQuarter: '/trimestre',
|
|
843
|
+
perSemester: '/semestre',
|
|
844
|
+
freeTrial: 'Grátis por {days} dias.',
|
|
845
|
+
postTrialPrice: 'Após este período, o valor da sua assinatura será de {price}.',
|
|
846
|
+
postTrialInstallments: 'Após este período, sua assinatura será cobrada em {installments}x de {value} ({price}).',
|
|
847
|
+
chargeLimit: 'Assinatura com {count} cobranças, contando a de hoje. Depois ela encerra sozinha.',
|
|
848
|
+
chargeLimitSingle: 'Cobrança única: a assinatura não renova.',
|
|
849
|
+
bumpTrialHighlight: '{free} por {days} dias',
|
|
850
|
+
bumpTrialAfter: 'Depois, {price}',
|
|
851
|
+
socialProofRegion: 'Atividade na oferta',
|
|
852
|
+
socialProofClose: 'Fechar avisos',
|
|
853
|
+
socialProofExtraItem: 'um item extra',
|
|
854
|
+
socialProofViewsOne: '**1 visualização** {window}',
|
|
855
|
+
socialProofViewsOther: '**{n} visualizações** {window}',
|
|
856
|
+
socialProofPurchasesOne: '**1 pessoa** comprou {window}',
|
|
857
|
+
socialProofPurchasesOther: '**{n} pessoas** compraram {window}',
|
|
858
|
+
socialProofOrderBumpOne: '**1 pessoa** também levou {item} {window}',
|
|
859
|
+
socialProofOrderBumpOther: '**{n} pessoas** também levaram {item} {window}',
|
|
860
|
+
socialProofWindow10m: 'nos últimos 10 min',
|
|
861
|
+
socialProofWindow1h: 'na última hora',
|
|
862
|
+
socialProofWindow12h: 'nas últimas 12h',
|
|
863
|
+
socialProofWindow24h: 'nas últimas 24h',
|
|
864
|
+
socialProofWindow48h: 'nas últimas 48h',
|
|
865
|
+
socialProofWindow7d: 'nos últimos 7 dias',
|
|
866
|
+
socialProofActionPurchase: 'comprou',
|
|
867
|
+
socialProofActionPix: 'gerou um Pix',
|
|
868
|
+
socialProofActionBoleto: 'gerou um boleto'
|
|
662
869
|
};
|
|
663
870
|
const EN = {
|
|
664
871
|
required: 'Required',
|
|
@@ -678,9 +885,43 @@ const EN = {
|
|
|
678
885
|
purchaseTimeout: 'The purchase is taking long. Check your email before trying again.',
|
|
679
886
|
pixExpired: 'The pix code expired. Generate a new one.',
|
|
680
887
|
offerBuyerNotEligible: 'This offer is not available for this email.',
|
|
888
|
+
checkoutUnavailableTitle: 'Product temporarily unavailable',
|
|
889
|
+
checkoutUnavailable: 'This product is not available for purchase at the moment. For more information, please contact the seller support',
|
|
890
|
+
offerPendingApproval: 'The checkout opens for sales as soon as the product is approved.',
|
|
891
|
+
trialUnavailable: 'This email has already used the free trial for this product. The first charge happens today.',
|
|
892
|
+
affiliateAccountNotice: 'By purchasing, you get a free Clickmax account to recommend this product and earn commission.',
|
|
681
893
|
includedInOrder: 'Included in your order',
|
|
682
894
|
specialOffer: 'Special offer',
|
|
683
|
-
specialOffers: 'Special offers'
|
|
895
|
+
specialOffers: 'Special offers',
|
|
896
|
+
perMonth: '/month',
|
|
897
|
+
perYear: '/year',
|
|
898
|
+
perQuarter: '/quarter',
|
|
899
|
+
perSemester: '/semester',
|
|
900
|
+
freeTrial: 'Free for {days} days.',
|
|
901
|
+
postTrialPrice: 'After this period, your subscription will be {price}.',
|
|
902
|
+
postTrialInstallments: 'After this period, your subscription will be charged in {installments}x of {value} ({price}).',
|
|
903
|
+
chargeLimit: 'Subscription with {count} charges, including today’s. After that it ends on its own.',
|
|
904
|
+
chargeLimitSingle: 'Single charge: the subscription does not renew.',
|
|
905
|
+
bumpTrialHighlight: '{free} for {days} days',
|
|
906
|
+
bumpTrialAfter: 'Then {price}',
|
|
907
|
+
socialProofRegion: 'Offer activity',
|
|
908
|
+
socialProofClose: 'Close notifications',
|
|
909
|
+
socialProofExtraItem: 'an extra item',
|
|
910
|
+
socialProofViewsOne: '**1 view** {window}',
|
|
911
|
+
socialProofViewsOther: '**{n} views** {window}',
|
|
912
|
+
socialProofPurchasesOne: '**1 person** purchased {window}',
|
|
913
|
+
socialProofPurchasesOther: '**{n} people** purchased {window}',
|
|
914
|
+
socialProofOrderBumpOne: '**1 person** also added {item} {window}',
|
|
915
|
+
socialProofOrderBumpOther: '**{n} people** also added {item} {window}',
|
|
916
|
+
socialProofWindow10m: 'in the last 10 min',
|
|
917
|
+
socialProofWindow1h: 'in the last hour',
|
|
918
|
+
socialProofWindow12h: 'in the last 12 hours',
|
|
919
|
+
socialProofWindow24h: 'in the last 24 hours',
|
|
920
|
+
socialProofWindow48h: 'in the last 48 hours',
|
|
921
|
+
socialProofWindow7d: 'in the last 7 days',
|
|
922
|
+
socialProofActionPurchase: 'bought',
|
|
923
|
+
socialProofActionPix: 'generated a Pix',
|
|
924
|
+
socialProofActionBoleto: 'generated a boleto'
|
|
684
925
|
};
|
|
685
926
|
const ES = {
|
|
686
927
|
required: 'Campo obligatorio',
|
|
@@ -700,9 +941,43 @@ const ES = {
|
|
|
700
941
|
purchaseTimeout: 'La compra está tardando. Revisa tu correo antes de intentar de nuevo.',
|
|
701
942
|
pixExpired: 'El código pix expiró. Genera otro.',
|
|
702
943
|
offerBuyerNotEligible: 'Esta oferta no está disponible para este correo.',
|
|
944
|
+
checkoutUnavailableTitle: 'Producto temporalmente no disponible',
|
|
945
|
+
checkoutUnavailable: 'Este producto no está disponible para la compra en este momento. Para más información, contacta al soporte del vendedor',
|
|
946
|
+
offerPendingApproval: 'El checkout se habilitará para ventas en cuanto se apruebe el producto.',
|
|
947
|
+
trialUnavailable: 'Este correo ya usó el período de prueba de este producto. El primer cobro se hace hoy.',
|
|
948
|
+
affiliateAccountNotice: 'Al comprar, recibes una cuenta Clickmax gratuita para recomendar este producto y ganar comisión.',
|
|
703
949
|
includedInOrder: 'Incluido en tu pedido',
|
|
704
950
|
specialOffer: 'Oferta especial',
|
|
705
|
-
specialOffers: 'Ofertas especiales'
|
|
951
|
+
specialOffers: 'Ofertas especiales',
|
|
952
|
+
perMonth: '/mes',
|
|
953
|
+
perYear: '/año',
|
|
954
|
+
perQuarter: '/trimestre',
|
|
955
|
+
perSemester: '/semestre',
|
|
956
|
+
freeTrial: 'Gratis por {days} días.',
|
|
957
|
+
postTrialPrice: 'Después de este período, tu suscripción costará {price}.',
|
|
958
|
+
postTrialInstallments: 'Después de este período, tu suscripción se cobrará en {installments}x de {value} ({price}).',
|
|
959
|
+
chargeLimit: 'Suscripción con {count} cobros, incluido el de hoy. Después termina sola.',
|
|
960
|
+
chargeLimitSingle: 'Cobro único: la suscripción no se renueva.',
|
|
961
|
+
bumpTrialHighlight: '{free} por {days} días',
|
|
962
|
+
bumpTrialAfter: 'Después, {price}',
|
|
963
|
+
socialProofRegion: 'Actividad en la oferta',
|
|
964
|
+
socialProofClose: 'Cerrar avisos',
|
|
965
|
+
socialProofExtraItem: 'un artículo extra',
|
|
966
|
+
socialProofViewsOne: '**1 visualización** {window}',
|
|
967
|
+
socialProofViewsOther: '**{n} visualizaciones** {window}',
|
|
968
|
+
socialProofPurchasesOne: '**1 persona** compró {window}',
|
|
969
|
+
socialProofPurchasesOther: '**{n} personas** compraron {window}',
|
|
970
|
+
socialProofOrderBumpOne: '**1 persona** también llevó {item} {window}',
|
|
971
|
+
socialProofOrderBumpOther: '**{n} personas** también llevaron {item} {window}',
|
|
972
|
+
socialProofWindow10m: 'en los últimos 10 min',
|
|
973
|
+
socialProofWindow1h: 'en la última hora',
|
|
974
|
+
socialProofWindow12h: 'en las últimas 12 h',
|
|
975
|
+
socialProofWindow24h: 'en las últimas 24 h',
|
|
976
|
+
socialProofWindow48h: 'en las últimas 48 h',
|
|
977
|
+
socialProofWindow7d: 'en los últimos 7 días',
|
|
978
|
+
socialProofActionPurchase: 'compró',
|
|
979
|
+
socialProofActionPix: 'generó un Pix',
|
|
980
|
+
socialProofActionBoleto: 'generó un boleto'
|
|
706
981
|
};
|
|
707
982
|
const BY_LOCALE = {
|
|
708
983
|
'pt-BR': PT_BR,
|
|
@@ -736,6 +1011,330 @@ const LANGUAGE = {
|
|
|
736
1011
|
}).format(cents / 100);
|
|
737
1012
|
}
|
|
738
1013
|
|
|
1014
|
+
/**
|
|
1015
|
+
* A generated pix lives only in React state: without this, reloading the page goes back to the
|
|
1016
|
+
* form, polling stops and `onApproved` never fires, so the funnel does not move on (the sale itself
|
|
1017
|
+
* still lands through the webhook). Mirrors the standard checkout.
|
|
1018
|
+
*
|
|
1019
|
+
* `sessionStorage` on purpose: it survives a reload in the same tab and never shows one buyer's
|
|
1020
|
+
* pix to another person on the same browser. Keyed by page path and offer, so two checkouts of the
|
|
1021
|
+
* same offer on different pages do not share a pix. Only read in effects (never during render).
|
|
1022
|
+
*/ const VERSION = 1;
|
|
1023
|
+
/** Without an expiry from the API, the longest the backend allows (Pix Automático, 30 min). */ const FALLBACK_TTL_MS = 30 * 60000;
|
|
1024
|
+
function storageKey(offerHash) {
|
|
1025
|
+
if (typeof window === 'undefined') return undefined;
|
|
1026
|
+
return `cx.checkout.pix:${window.location.pathname}:${offerHash}`;
|
|
1027
|
+
}
|
|
1028
|
+
function storage() {
|
|
1029
|
+
try {
|
|
1030
|
+
return window.sessionStorage;
|
|
1031
|
+
} catch {
|
|
1032
|
+
// Blocked storage (private mode, third-party iframe): no restore, the checkout still works.
|
|
1033
|
+
return undefined;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
const isRecord = (value)=>typeof value === 'object' && value !== null;
|
|
1037
|
+
/** Saves only what the pix screen shows; nothing about the buyer. */ function savePendingPix(offerHash, pix) {
|
|
1038
|
+
const key = storageKey(offerHash);
|
|
1039
|
+
if (!key) return;
|
|
1040
|
+
const { transactionId, code, qrcodeUrl, totalAmount, expiresAt } = pix;
|
|
1041
|
+
try {
|
|
1042
|
+
storage()?.setItem(key, JSON.stringify({
|
|
1043
|
+
v: VERSION,
|
|
1044
|
+
savedAt: Date.now(),
|
|
1045
|
+
pix: {
|
|
1046
|
+
transactionId,
|
|
1047
|
+
code,
|
|
1048
|
+
qrcodeUrl,
|
|
1049
|
+
totalAmount,
|
|
1050
|
+
expiresAt: expiresAt?.toISOString()
|
|
1051
|
+
}
|
|
1052
|
+
}));
|
|
1053
|
+
} catch {
|
|
1054
|
+
// Quota or blocked storage: no restore.
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
function clearPendingPix(offerHash) {
|
|
1058
|
+
const key = storageKey(offerHash);
|
|
1059
|
+
if (!key) return;
|
|
1060
|
+
try {
|
|
1061
|
+
storage()?.removeItem(key);
|
|
1062
|
+
} catch {
|
|
1063
|
+
// idem
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
/** The pending pix of this page and offer while it is still payable; drops stale entries. */ function readPendingPix(offerHash, now = Date.now()) {
|
|
1067
|
+
const key = storageKey(offerHash);
|
|
1068
|
+
if (!key) return undefined;
|
|
1069
|
+
let raw;
|
|
1070
|
+
try {
|
|
1071
|
+
raw = storage()?.getItem(key);
|
|
1072
|
+
} catch {
|
|
1073
|
+
return undefined;
|
|
1074
|
+
}
|
|
1075
|
+
if (!raw) return undefined;
|
|
1076
|
+
const pix = parse(raw, now);
|
|
1077
|
+
if (!pix) clearPendingPix(offerHash);
|
|
1078
|
+
return pix;
|
|
1079
|
+
}
|
|
1080
|
+
/** Rebuilt field by field: nothing from storage reaches the screen without its type checked. */ function parse(raw, now) {
|
|
1081
|
+
let data;
|
|
1082
|
+
try {
|
|
1083
|
+
data = JSON.parse(raw);
|
|
1084
|
+
} catch {
|
|
1085
|
+
return undefined;
|
|
1086
|
+
}
|
|
1087
|
+
if (!isRecord(data) || data.v !== VERSION) return undefined;
|
|
1088
|
+
// `savedAt` drives the fallback expiry; NaN or Infinity would keep a dead pix on screen.
|
|
1089
|
+
if (typeof data.savedAt !== 'number' || !Number.isFinite(data.savedAt) || data.savedAt < 0) {
|
|
1090
|
+
return undefined;
|
|
1091
|
+
}
|
|
1092
|
+
const { pix } = data;
|
|
1093
|
+
if (!isRecord(pix)) return undefined;
|
|
1094
|
+
const { transactionId, code, qrcodeUrl, totalAmount, expiresAt } = pix;
|
|
1095
|
+
if (typeof transactionId !== 'string' || typeof code !== 'string' || typeof qrcodeUrl !== 'string' || typeof totalAmount !== 'number' || !Number.isInteger(totalAmount) || expiresAt !== undefined && typeof expiresAt !== 'string') {
|
|
1096
|
+
return undefined;
|
|
1097
|
+
}
|
|
1098
|
+
const expiry = expiresAt ? Date.parse(expiresAt) : Number.NaN;
|
|
1099
|
+
const deadline = Number.isNaN(expiry) ? data.savedAt + FALLBACK_TTL_MS : expiry;
|
|
1100
|
+
if (now >= deadline) return undefined;
|
|
1101
|
+
return {
|
|
1102
|
+
transactionId,
|
|
1103
|
+
code,
|
|
1104
|
+
qrcodeUrl,
|
|
1105
|
+
totalAmount,
|
|
1106
|
+
expiresAt: Number.isNaN(expiry) ? undefined : new Date(expiry),
|
|
1107
|
+
restored: true
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
/** Replaces `{name}` tokens of a message. Unknown tokens stay as typed. */ function fillMessage(template, values) {
|
|
1113
|
+
return template.replace(/\{(\w+)\}/g, (token, name)=>Object.hasOwn(values, name) ? String(values[name]) : token);
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Suffix of a recurring price ("/mês"). `semi-annually` is how the database spells it and
|
|
1117
|
+
* `semiannual` shows up on older offers; both mean every six months. An unknown frequency gets no
|
|
1118
|
+
* suffix: imprecise is better than a wrong "/month".
|
|
1119
|
+
*/ function perFrequency(messages, frequency) {
|
|
1120
|
+
switch(frequency){
|
|
1121
|
+
case 'monthly':
|
|
1122
|
+
return messages.perMonth;
|
|
1123
|
+
case 'yearly':
|
|
1124
|
+
return messages.perYear;
|
|
1125
|
+
case 'quarterly':
|
|
1126
|
+
return messages.perQuarter;
|
|
1127
|
+
case 'semi-annually':
|
|
1128
|
+
case 'semiannual':
|
|
1129
|
+
return messages.perSemester;
|
|
1130
|
+
default:
|
|
1131
|
+
return '';
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
/** Charge limit notice; `undefined` when the subscription renews until canceled. */ function chargeLimitText(messages, maxCharges) {
|
|
1135
|
+
if (maxCharges == null) return undefined;
|
|
1136
|
+
if (maxCharges === 1) return messages.chargeLimitSingle;
|
|
1137
|
+
return fillMessage(messages.chargeLimit, {
|
|
1138
|
+
count: maxCharges
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* "After this period..." sentence of a free trial. It follows the installment the buyer picked
|
|
1143
|
+
* (count, installment value and cycle total) or the cash price at 1x, and the suffix follows the
|
|
1144
|
+
* frequency, so an annual plan never reads "/month".
|
|
1145
|
+
*/ function postTrialText(messages, locale, input) {
|
|
1146
|
+
const { cashValue, installment, installmentValue, per } = input;
|
|
1147
|
+
if (installment <= 1 || !installmentValue) {
|
|
1148
|
+
return fillMessage(messages.postTrialPrice, {
|
|
1149
|
+
price: `${formatMoney(cashValue, locale)}${per}`
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
return fillMessage(messages.postTrialInstallments, {
|
|
1153
|
+
installments: installment,
|
|
1154
|
+
value: formatMoney(installmentValue, locale),
|
|
1155
|
+
price: `${formatMoney(installmentValue * installment, locale)}${per}`
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
// The seller's editor suggests the token in their own language ({dias}/{days}, {preço}/{price}),
|
|
1159
|
+
// and people typing by hand drop the accent; every spelling resolves to the same value.
|
|
1160
|
+
const DAYS_TOKEN = /\{(dias|días|days)\}/gi;
|
|
1161
|
+
const PRICE_TOKEN = /\{(preço|preco|precio|price)\}/gi;
|
|
1162
|
+
/**
|
|
1163
|
+
* Texts of an order bump with a free trial: the highlight ("R$ 0,00 por 30 dias") and the later
|
|
1164
|
+
* charge ("Depois, R$ 497,00/mês"). Seller texts (`configs.orderBump.trialTexts[bumpId]`) win
|
|
1165
|
+
* over the defaults; their price token already carries the frequency suffix.
|
|
1166
|
+
*/ function bumpTrialTexts(messages, locale, input) {
|
|
1167
|
+
const priceText = `${formatMoney(input.price, locale)}${perFrequency(messages, input.frequency)}`;
|
|
1168
|
+
const resolve = (template)=>template.replace(DAYS_TOKEN, String(input.days)).replace(PRICE_TOKEN, priceText);
|
|
1169
|
+
return {
|
|
1170
|
+
highlight: resolve(input.custom?.highlight?.trim() || fillMessage(messages.bumpTrialHighlight, {
|
|
1171
|
+
free: formatMoney(0, locale),
|
|
1172
|
+
days: '{days}'
|
|
1173
|
+
})),
|
|
1174
|
+
after: resolve(input.custom?.after?.trim() || messages.bumpTrialAfter)
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
// Same rules as the standard checkout (`entities/social-proof` in pages/payments). The minimum
|
|
1179
|
+
// per type and the window are applied by the API; the client orders, caps and rotates.
|
|
1180
|
+
// Purchases first: the strongest proof.
|
|
1181
|
+
const TYPE_ORDER = [
|
|
1182
|
+
'purchases',
|
|
1183
|
+
'views',
|
|
1184
|
+
'orderBumpPurchases'
|
|
1185
|
+
];
|
|
1186
|
+
/** Counts in display order, capped at `maxBalloons`. */ function orderCounts(items, maxBalloons) {
|
|
1187
|
+
return [
|
|
1188
|
+
...items
|
|
1189
|
+
].sort((a, b)=>TYPE_ORDER.indexOf(a.type) - TYPE_ORDER.indexOf(b.type)).slice(0, Number.isFinite(maxBalloons) ? Math.max(0, maxBalloons) : 0);
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Next balloon: the newest activity not shown yet, otherwise the next count. Picked when it is
|
|
1193
|
+
* shown, so an event that arrives by polling takes the next slot. `maxBalloons` caps the total.
|
|
1194
|
+
*/ function pickNext(input) {
|
|
1195
|
+
const { counts, activity, seenIds, countsShown, maxBalloons } = input;
|
|
1196
|
+
if (seenIds.length + countsShown >= maxBalloons) return undefined;
|
|
1197
|
+
const fresh = activity.find((entry)=>!seenIds.includes(entry.id));
|
|
1198
|
+
if (fresh) return {
|
|
1199
|
+
kind: 'activity',
|
|
1200
|
+
activity: fresh
|
|
1201
|
+
};
|
|
1202
|
+
const item = counts[countsShown];
|
|
1203
|
+
return item && {
|
|
1204
|
+
kind: 'count',
|
|
1205
|
+
item
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
// Same key as the standard checkout: closing the balloons there or here hides them in both.
|
|
1209
|
+
const dismissedKey = (offerHash)=>`cx-social-proof-dismissed:${offerHash}`;
|
|
1210
|
+
function readDismissed(offerHash) {
|
|
1211
|
+
try {
|
|
1212
|
+
return sessionStorage.getItem(dismissedKey(offerHash)) !== null;
|
|
1213
|
+
} catch {
|
|
1214
|
+
return false;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
function writeDismissed(offerHash) {
|
|
1218
|
+
try {
|
|
1219
|
+
sessionStorage.setItem(dismissedKey(offerHash), '1');
|
|
1220
|
+
} catch {
|
|
1221
|
+
// Blocked storage: the balloons stay closed only on this page.
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
const MAX_ITEM_NAME = 28;
|
|
1225
|
+
function textFromParts(parts) {
|
|
1226
|
+
return parts.map((part)=>part.text).join('');
|
|
1227
|
+
}
|
|
1228
|
+
/** Splits `**bold**` markers of a message into parts. */ function toParts(template) {
|
|
1229
|
+
return template.split('**').map((text, index)=>({
|
|
1230
|
+
text,
|
|
1231
|
+
strong: index % 2 === 1
|
|
1232
|
+
})).filter((part)=>part.text !== '');
|
|
1233
|
+
}
|
|
1234
|
+
const WINDOW_MESSAGE = {
|
|
1235
|
+
'10m': 'socialProofWindow10m',
|
|
1236
|
+
'1h': 'socialProofWindow1h',
|
|
1237
|
+
'12h': 'socialProofWindow12h',
|
|
1238
|
+
'24h': 'socialProofWindow24h',
|
|
1239
|
+
'48h': 'socialProofWindow48h',
|
|
1240
|
+
'7d': 'socialProofWindow7d'
|
|
1241
|
+
};
|
|
1242
|
+
const COUNT_MESSAGE = {
|
|
1243
|
+
views: [
|
|
1244
|
+
'socialProofViewsOne',
|
|
1245
|
+
'socialProofViewsOther'
|
|
1246
|
+
],
|
|
1247
|
+
purchases: [
|
|
1248
|
+
'socialProofPurchasesOne',
|
|
1249
|
+
'socialProofPurchasesOther'
|
|
1250
|
+
],
|
|
1251
|
+
orderBumpPurchases: [
|
|
1252
|
+
'socialProofOrderBumpOne',
|
|
1253
|
+
'socialProofOrderBumpOther'
|
|
1254
|
+
]
|
|
1255
|
+
};
|
|
1256
|
+
const ACTION_MESSAGE = {
|
|
1257
|
+
purchase: 'socialProofActionPurchase',
|
|
1258
|
+
pix: 'socialProofActionPix',
|
|
1259
|
+
boleto: 'socialProofActionBoleto'
|
|
1260
|
+
};
|
|
1261
|
+
/**
|
|
1262
|
+
* Balloon of a count. `bumpName` is the name of the offer's only order bump; with more than one,
|
|
1263
|
+
* the text falls back to "an extra item".
|
|
1264
|
+
*/ function countBalloon(item, messages, bumpName, id) {
|
|
1265
|
+
const [one, other] = COUNT_MESSAGE[item.type];
|
|
1266
|
+
// `window` comes from the API: without the own-key check, `constructor` would read the prototype.
|
|
1267
|
+
const windowText = Object.hasOwn(WINDOW_MESSAGE, item.window) ? messages[WINDOW_MESSAGE[item.window]] : item.window;
|
|
1268
|
+
// A `*` in the bump name would close the bold too early.
|
|
1269
|
+
const chars = Array.from(bumpName?.replaceAll('*', '') ?? '');
|
|
1270
|
+
const itemName = chars.length > MAX_ITEM_NAME ? `${chars.slice(0, MAX_ITEM_NAME).join('')}…` : chars.join('');
|
|
1271
|
+
const template = messages[item.count === 1 ? one : other].replace('{n}', ()=>String(item.count)).replace('{window}', ()=>windowText).replace('{item}', ()=>itemName || messages.socialProofExtraItem);
|
|
1272
|
+
const parts = toParts(template);
|
|
1273
|
+
return {
|
|
1274
|
+
id,
|
|
1275
|
+
kind: 'count',
|
|
1276
|
+
icon: item.type,
|
|
1277
|
+
parts,
|
|
1278
|
+
text: textFromParts(parts),
|
|
1279
|
+
place: undefined,
|
|
1280
|
+
time: undefined
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
function countryName(code, locale) {
|
|
1284
|
+
try {
|
|
1285
|
+
return new Intl.DisplayNames([
|
|
1286
|
+
locale
|
|
1287
|
+
], {
|
|
1288
|
+
type: 'region'
|
|
1289
|
+
}).of(code);
|
|
1290
|
+
} catch {
|
|
1291
|
+
// Not an ISO alpha-2 code: the country drops out instead of breaking the balloon.
|
|
1292
|
+
return undefined;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
// Browser time zone. pt-BR "09h47" (as the standard checkout), en "1:21 PM", es "13:21".
|
|
1296
|
+
function formatTime(iso, locale) {
|
|
1297
|
+
const date = new Date(iso);
|
|
1298
|
+
if (locale === 'en') {
|
|
1299
|
+
return new Intl.DateTimeFormat('en-US', {
|
|
1300
|
+
hour: 'numeric',
|
|
1301
|
+
minute: '2-digit'
|
|
1302
|
+
}).format(date);
|
|
1303
|
+
}
|
|
1304
|
+
const time = new Intl.DateTimeFormat(locale, {
|
|
1305
|
+
hour: '2-digit',
|
|
1306
|
+
minute: '2-digit',
|
|
1307
|
+
hourCycle: 'h23'
|
|
1308
|
+
}).format(date);
|
|
1309
|
+
return locale === 'pt-BR' ? time.replace(':', 'h') : time;
|
|
1310
|
+
}
|
|
1311
|
+
/** Balloon of a recent purchase or charge. The name already comes masked from the API. */ function activityBalloon(activity, messages, locale) {
|
|
1312
|
+
const country = activity.country ? countryName(activity.country, locale) : undefined;
|
|
1313
|
+
const place = [
|
|
1314
|
+
activity.city,
|
|
1315
|
+
country
|
|
1316
|
+
].filter(Boolean).join(', ');
|
|
1317
|
+
const parts = [
|
|
1318
|
+
{
|
|
1319
|
+
text: activity.name,
|
|
1320
|
+
strong: true
|
|
1321
|
+
},
|
|
1322
|
+
{
|
|
1323
|
+
text: ` ${messages[ACTION_MESSAGE[activity.action]]}`,
|
|
1324
|
+
strong: false
|
|
1325
|
+
}
|
|
1326
|
+
];
|
|
1327
|
+
return {
|
|
1328
|
+
id: activity.id,
|
|
1329
|
+
kind: 'activity',
|
|
1330
|
+
icon: activity.action,
|
|
1331
|
+
parts,
|
|
1332
|
+
text: textFromParts(parts),
|
|
1333
|
+
place: place || undefined,
|
|
1334
|
+
time: formatTime(activity.occurredAt, locale)
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
|
|
739
1338
|
/** Digits only. */ function onlyDigits(value) {
|
|
740
1339
|
return value.replace(/\D/g, '');
|
|
741
1340
|
}
|
|
@@ -865,6 +1464,35 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
|
|
865
1464
|
return errors;
|
|
866
1465
|
}
|
|
867
1466
|
|
|
1467
|
+
const LOOKUP_TIMEOUT_MS = 8000;
|
|
1468
|
+
/**
|
|
1469
|
+
* Default lookup: ViaCEP, the public service the standard checkout uses. Called straight from the
|
|
1470
|
+
* browser (no payments route), so it works on any host.
|
|
1471
|
+
*/ const viaCepLookup = async (zipCode, { signal })=>{
|
|
1472
|
+
// A hung ViaCEP must not leave the address form in `loading` forever.
|
|
1473
|
+
const response = await fetch(`https://viacep.com.br/ws/${encodeURIComponent(zipCode)}/json/`, {
|
|
1474
|
+
signal: AbortSignal.any([
|
|
1475
|
+
signal,
|
|
1476
|
+
AbortSignal.timeout(LOOKUP_TIMEOUT_MS)
|
|
1477
|
+
])
|
|
1478
|
+
});
|
|
1479
|
+
if (!response.ok) throw new Error(`ViaCEP answered ${response.status}`);
|
|
1480
|
+
const data = await response.json();
|
|
1481
|
+
// ViaCEP answers 200 with `{ erro: true }` for a zip code that does not exist.
|
|
1482
|
+
if (typeof data !== 'object' || data === null || 'erro' in data) return undefined;
|
|
1483
|
+
const text = (key)=>{
|
|
1484
|
+
const value = data[key];
|
|
1485
|
+
return typeof value === 'string' && value ? value : undefined;
|
|
1486
|
+
};
|
|
1487
|
+
return {
|
|
1488
|
+
street: text('logradouro'),
|
|
1489
|
+
neighborhood: text('bairro'),
|
|
1490
|
+
city: text('localidade'),
|
|
1491
|
+
state: text('uf')
|
|
1492
|
+
};
|
|
1493
|
+
};
|
|
1494
|
+
|
|
1495
|
+
|
|
868
1496
|
|
|
869
1497
|
|
|
870
1498
|
|
|
@@ -992,6 +1620,7 @@ async function waitForJob(state, jobId) {
|
|
|
992
1620
|
method: 'pix',
|
|
993
1621
|
isUpsell: state.offer.isOTO
|
|
994
1622
|
};
|
|
1623
|
+
clearPendingPix(state.offer.hash);
|
|
995
1624
|
state.setSubmission((value)=>({
|
|
996
1625
|
...value,
|
|
997
1626
|
status: 'approved'
|
|
@@ -1028,6 +1657,7 @@ async function waitForJob(state, jobId) {
|
|
|
1028
1657
|
message
|
|
1029
1658
|
};
|
|
1030
1659
|
};
|
|
1660
|
+
if (state.purchaseBlocked) return fail(state.purchaseBlocked);
|
|
1031
1661
|
if (!method || !state.methods.includes(method)) return fail(state.messages.methodUnavailable);
|
|
1032
1662
|
if (!state.validate()) return {
|
|
1033
1663
|
status: 'invalid'
|
|
@@ -1104,6 +1734,7 @@ async function waitForJob(state, jobId) {
|
|
|
1104
1734
|
boleto: undefined,
|
|
1105
1735
|
transactionId: response.id
|
|
1106
1736
|
}));
|
|
1737
|
+
if (state.persistPendingPix) savePendingPix(state.offer.hash, pix);
|
|
1107
1738
|
state.callbacks.onPixGenerated?.(pix);
|
|
1108
1739
|
void watchPix(state, response.id, response.totalAmount);
|
|
1109
1740
|
return {
|
|
@@ -1189,6 +1820,335 @@ async function waitForJob(state, jobId) {
|
|
|
1189
1820
|
|
|
1190
1821
|
|
|
1191
1822
|
|
|
1823
|
+
/**
|
|
1824
|
+
* Groups the blurs of the personal data fields. Tabbing through five fields would otherwise send
|
|
1825
|
+
* five lead captures, each one publishing CRM events on the server.
|
|
1826
|
+
*/ const LEAD_WAIT_MS = 800;
|
|
1827
|
+
const tracking_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
1828
|
+
const tracking_FULL_NAME = /^[A-Za-zÀ-ÖØ-öø-ÿ]+(?:\s+[A-Za-zÀ-ÖØ-öø-ÿ]+)+\s*$/;
|
|
1829
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1830
|
+
function tracking_pageUrl(location) {
|
|
1831
|
+
if (location.pageUrl) return location.pageUrl;
|
|
1832
|
+
return typeof window === 'undefined' ? '' : window.location.href;
|
|
1833
|
+
}
|
|
1834
|
+
function readCookie(name) {
|
|
1835
|
+
if (typeof document === 'undefined') return undefined;
|
|
1836
|
+
const prefix = `${name}=`;
|
|
1837
|
+
return document.cookie.split(/;\s*/).find((part)=>part.startsWith(prefix))?.slice(prefix.length);
|
|
1838
|
+
}
|
|
1839
|
+
/**
|
|
1840
|
+
* Personal data good enough for ad platform matching: a valid email, first and last name and a
|
|
1841
|
+
* phone with at least 8 digits. Not the form validation: the document is optional here, so a
|
|
1842
|
+
* foreign buyer still counts.
|
|
1843
|
+
*/ function isBuyerReady(values) {
|
|
1844
|
+
return tracking_EMAIL.test(values.email.trim()) && tracking_FULL_NAME.test(values.name.trim()) && onlyDigits(values.phone).length >= 8;
|
|
1845
|
+
}
|
|
1846
|
+
function buyerSnapshot(input) {
|
|
1847
|
+
const { personalDataActive, personalData, oneClick, address } = input;
|
|
1848
|
+
if (!personalDataActive && oneClick) {
|
|
1849
|
+
return {
|
|
1850
|
+
email: oneClick.email,
|
|
1851
|
+
name: oneClick.name,
|
|
1852
|
+
document: oneClick.document ?? undefined,
|
|
1853
|
+
telephone: oneClick.telephone
|
|
1854
|
+
};
|
|
1855
|
+
}
|
|
1856
|
+
const email = personalData.email.trim().toLowerCase();
|
|
1857
|
+
const document1 = onlyDigits(personalData.document);
|
|
1858
|
+
const buyer = {
|
|
1859
|
+
email: tracking_EMAIL.test(email) ? email : undefined,
|
|
1860
|
+
name: personalData.name.trim() || undefined,
|
|
1861
|
+
document: document1 && isValidDocument(document1) ? document1 : undefined,
|
|
1862
|
+
telephone: parseTelephone(personalData.phone)
|
|
1863
|
+
};
|
|
1864
|
+
if (address) {
|
|
1865
|
+
buyer.address = {
|
|
1866
|
+
zipCode: address.zipCode.trim() || undefined,
|
|
1867
|
+
street: address.street.trim() || undefined,
|
|
1868
|
+
number: address.number.trim() || undefined,
|
|
1869
|
+
complement: address.complement.trim() || undefined,
|
|
1870
|
+
neighborhood: address.neighborhood.trim() || undefined,
|
|
1871
|
+
city: address.city.trim() || undefined,
|
|
1872
|
+
state: address.state.trim().toUpperCase() || undefined,
|
|
1873
|
+
country: /^[A-Za-z]{2}$/.test(address.country) ? address.country.toUpperCase() : undefined
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
return Object.values(buyer).some((value)=>value !== undefined) ? buyer : undefined;
|
|
1877
|
+
}
|
|
1878
|
+
/**
|
|
1879
|
+
* Lead capture, payment interaction and pixel events of the checkout, the same signals the
|
|
1880
|
+
* standard checkout sends: the lead and interaction feed cart abandonment, the pixel events feed
|
|
1881
|
+
* Meta and Google Ads.
|
|
1882
|
+
*
|
|
1883
|
+
* Each pixel event goes two ways with the same event id, so the ad platform keeps one: the host
|
|
1884
|
+
* fires the browser pixel from `onPixelEvent` (loading `fbq`/`gtag` is the host's call), and the
|
|
1885
|
+
* package sends `initiateCheckout` and `addPaymentInfo` to the conversions API. Purchase reaches
|
|
1886
|
+
* the conversions API from the server on its own.
|
|
1887
|
+
*
|
|
1888
|
+
* Every effect waits for the visitor route: the event ids the server deduplicates against are
|
|
1889
|
+
* built from the visitor's session, and firing before them would count each event twice.
|
|
1890
|
+
*/ function useCheckoutTracking(input) {
|
|
1891
|
+
const inputRef = useRef(input);
|
|
1892
|
+
inputRef.current = input;
|
|
1893
|
+
const fired = useRef(new Set()).current;
|
|
1894
|
+
const emit = useCallback((name, targets, extra = {})=>{
|
|
1895
|
+
if (targets.length === 0) return;
|
|
1896
|
+
try {
|
|
1897
|
+
inputRef.current.callbacks.onPixelEvent?.({
|
|
1898
|
+
name,
|
|
1899
|
+
pixels: targets,
|
|
1900
|
+
...extra
|
|
1901
|
+
});
|
|
1902
|
+
} catch (error) {
|
|
1903
|
+
// A broken host handler must not take the checkout down with it.
|
|
1904
|
+
console.error('[clickmax-checkout] onPixelEvent threw', {
|
|
1905
|
+
op: 'onPixelEvent',
|
|
1906
|
+
name,
|
|
1907
|
+
error
|
|
1908
|
+
});
|
|
1909
|
+
}
|
|
1910
|
+
}, []);
|
|
1911
|
+
/** Sends a canonical event to the conversions API, best effort, for pixels with a session id. */ const dispatch = useCallback((canonicalEvent, targets)=>{
|
|
1912
|
+
const current = inputRef.current;
|
|
1913
|
+
const url = tracking_pageUrl(current.location);
|
|
1914
|
+
const tracking = current.location.tracking;
|
|
1915
|
+
const clientFbp = tracking?.clientFbp ?? readCookie('_fbp');
|
|
1916
|
+
const clientFbc = tracking?.clientFbc ?? readCookie('_fbc');
|
|
1917
|
+
const buyer = buyerSnapshot(current);
|
|
1918
|
+
for (const { pixel, eventId } of targets){
|
|
1919
|
+
if (pixel.eventIds?.[canonicalEvent] !== eventId) continue;
|
|
1920
|
+
void current.api.dispatchPixelEvent({
|
|
1921
|
+
offerHash: current.offer.hash,
|
|
1922
|
+
canonicalEvent,
|
|
1923
|
+
eventId,
|
|
1924
|
+
...buyer ? {
|
|
1925
|
+
buyer
|
|
1926
|
+
} : {},
|
|
1927
|
+
...clientFbp ? {
|
|
1928
|
+
clientFbp
|
|
1929
|
+
} : {},
|
|
1930
|
+
...clientFbc ? {
|
|
1931
|
+
clientFbc
|
|
1932
|
+
} : {},
|
|
1933
|
+
// Over the schema limit the event goes without its URL; a 400 would lose all of it.
|
|
1934
|
+
.../^https?:\/\//.test(url) && url.length <= 2048 ? {
|
|
1935
|
+
eventSourceUrl: url
|
|
1936
|
+
} : {}
|
|
1937
|
+
}).catch(()=>{
|
|
1938
|
+
// The browser pixel already went out through the host; nothing to recover here.
|
|
1939
|
+
});
|
|
1940
|
+
}
|
|
1941
|
+
}, []);
|
|
1942
|
+
const targets = useCallback((name, filter, sourceId)=>inputRef.current.pixels.filter(filter).map((pixel)=>({
|
|
1943
|
+
pixel,
|
|
1944
|
+
eventId: (name === 'initiateCheckout' || name === 'addPaymentInfo' ? pixel.eventIds?.[name] : undefined) ?? `${name}-${sourceId}-${pixel.serviceId}`,
|
|
1945
|
+
label: pixel.eventLabels?.[name]
|
|
1946
|
+
})), []);
|
|
1947
|
+
const fireOnce = useCallback((key, name, filter, extra)=>{
|
|
1948
|
+
if (fired.has(key)) return;
|
|
1949
|
+
const matching = targets(name, filter, String(Date.now()));
|
|
1950
|
+
if (matching.length === 0) return;
|
|
1951
|
+
fired.add(key);
|
|
1952
|
+
emit(name, matching, extra);
|
|
1953
|
+
dispatch(name, matching);
|
|
1954
|
+
}, [
|
|
1955
|
+
fired,
|
|
1956
|
+
targets,
|
|
1957
|
+
emit,
|
|
1958
|
+
dispatch
|
|
1959
|
+
]);
|
|
1960
|
+
// A method picked before the visitor answers waits for it: fired now, the event would carry a
|
|
1961
|
+
// fallback id the conversions API cannot match, and it fires only once.
|
|
1962
|
+
const pendingPaymentInfo = useRef(undefined);
|
|
1963
|
+
const addPaymentInfo = useCallback((method)=>{
|
|
1964
|
+
if (!inputRef.current.visitorSettled) {
|
|
1965
|
+
pendingPaymentInfo.current = method;
|
|
1966
|
+
return;
|
|
1967
|
+
}
|
|
1968
|
+
fireOnce('addPaymentInfo', 'addPaymentInfo', (pixel)=>pixel.eventsConfig.addPaymentInfo?.enabled === true, {
|
|
1969
|
+
paymentMethod: method
|
|
1970
|
+
});
|
|
1971
|
+
}, [
|
|
1972
|
+
fireOnce
|
|
1973
|
+
]);
|
|
1974
|
+
const { visitorSettled, method } = input;
|
|
1975
|
+
// Page view and the initiate checkout that does not wait for the buyer's data.
|
|
1976
|
+
useEffect(()=>{
|
|
1977
|
+
if (!visitorSettled || fired.has('mount')) return;
|
|
1978
|
+
fired.add('mount');
|
|
1979
|
+
emit('pageView', targets('pageView', (pixel)=>pixel.eventsConfig.pageView?.enabled === true, String(Date.now())));
|
|
1980
|
+
fireOnce('initiateCheckout', 'initiateCheckout', (pixel)=>pixel.eventsConfig.initiateCheckout?.enabled === true && pixel.eventsConfig.initiateCheckout.afterPersonalData !== true);
|
|
1981
|
+
}, [
|
|
1982
|
+
visitorSettled,
|
|
1983
|
+
fired,
|
|
1984
|
+
emit,
|
|
1985
|
+
targets,
|
|
1986
|
+
fireOnce
|
|
1987
|
+
]);
|
|
1988
|
+
// Initiate checkout of pixels set to wait for the buyer's data, so it carries email and phone.
|
|
1989
|
+
const buyerReady = input.personalDataActive ? isBuyerReady(input.personalData) : Boolean(input.oneClick);
|
|
1990
|
+
useEffect(()=>{
|
|
1991
|
+
if (!visitorSettled || !buyerReady) return;
|
|
1992
|
+
fireOnce('initiateCheckoutAfterData', 'initiateCheckout', (pixel)=>pixel.eventsConfig.initiateCheckout?.enabled === true && pixel.eventsConfig.initiateCheckout.afterPersonalData === true);
|
|
1993
|
+
}, [
|
|
1994
|
+
visitorSettled,
|
|
1995
|
+
buyerReady,
|
|
1996
|
+
fireOnce
|
|
1997
|
+
]);
|
|
1998
|
+
// A pix or boleto picked up front (single method, or the method of the buyer's last purchase)
|
|
1999
|
+
// is already the payment info. Card waits for the buyer to focus the card fields.
|
|
2000
|
+
useEffect(()=>{
|
|
2001
|
+
if (!visitorSettled) return;
|
|
2002
|
+
const pending = pendingPaymentInfo.current;
|
|
2003
|
+
pendingPaymentInfo.current = undefined;
|
|
2004
|
+
if (pending) addPaymentInfo(pending);
|
|
2005
|
+
else if (method && method !== 'credit') addPaymentInfo(method);
|
|
2006
|
+
}, [
|
|
2007
|
+
visitorSettled,
|
|
2008
|
+
method,
|
|
2009
|
+
addPaymentInfo
|
|
2010
|
+
]);
|
|
2011
|
+
const interaction = useCallback((body)=>{
|
|
2012
|
+
const current = inputRef.current;
|
|
2013
|
+
void current.api.trackInteraction({
|
|
2014
|
+
hash: current.offer.hash,
|
|
2015
|
+
...body,
|
|
2016
|
+
...current.location.visitorId ? {
|
|
2017
|
+
visitorId: current.location.visitorId
|
|
2018
|
+
} : {}
|
|
2019
|
+
}).catch(()=>{});
|
|
2020
|
+
}, []);
|
|
2021
|
+
// region Lead
|
|
2022
|
+
const createdLead = useRef(false);
|
|
2023
|
+
const lastLead = useRef(null);
|
|
2024
|
+
const leadTimer = useRef(null);
|
|
2025
|
+
const pendingLead = useRef(false);
|
|
2026
|
+
// One capture at a time: `funnelCreatedLead` flips only after the first answer, so two captures
|
|
2027
|
+
// in flight would both create the lead. A capture asked meanwhile goes when the first returns.
|
|
2028
|
+
const leadInFlight = useRef(false);
|
|
2029
|
+
const leadQueued = useRef(false);
|
|
2030
|
+
const sendLead = useCallback(function send() {
|
|
2031
|
+
if (leadInFlight.current) {
|
|
2032
|
+
leadQueued.current = true;
|
|
2033
|
+
return;
|
|
2034
|
+
}
|
|
2035
|
+
const current = inputRef.current;
|
|
2036
|
+
if (!current.personalDataActive) return;
|
|
2037
|
+
const { personalData, location, offer } = current;
|
|
2038
|
+
const email = personalData.email.trim();
|
|
2039
|
+
if (!tracking_EMAIL.test(email)) return;
|
|
2040
|
+
const document1 = onlyDigits(personalData.document);
|
|
2041
|
+
const tracking = location.tracking ?? {};
|
|
2042
|
+
const body = {
|
|
2043
|
+
hash: offer.hash,
|
|
2044
|
+
email,
|
|
2045
|
+
fullName: personalData.name.trim(),
|
|
2046
|
+
// Partial phone or document would land in the CRM as is; send them only once complete.
|
|
2047
|
+
telephone: parseTelephone(personalData.phone) ? personalData.phone.trim() : '',
|
|
2048
|
+
document: document1 && isValidDocument(document1) ? document1 : undefined,
|
|
2049
|
+
utmSource: tracking.utmSource,
|
|
2050
|
+
utmMedium: tracking.utmMedium,
|
|
2051
|
+
utmCampaign: tracking.utmCampaign,
|
|
2052
|
+
utmTerm: tracking.utmTerm,
|
|
2053
|
+
utmContent: tracking.utmContent,
|
|
2054
|
+
extraParams: tracking.extraParams,
|
|
2055
|
+
src: tracking.src,
|
|
2056
|
+
sck: tracking.sck,
|
|
2057
|
+
referrer: tracking.referrer,
|
|
2058
|
+
landingUrl: tracking.landingUrl,
|
|
2059
|
+
pageId: location.pageId && UUID.test(location.pageId) ? location.pageId : undefined,
|
|
2060
|
+
visitorId: location.visitorId,
|
|
2061
|
+
sessionId: location.sessionId,
|
|
2062
|
+
affiliateHash: current.affiliateHash,
|
|
2063
|
+
funnelCreatedLead: false
|
|
2064
|
+
};
|
|
2065
|
+
// A blur on a field already sent changes nothing on the server.
|
|
2066
|
+
const signature = JSON.stringify(body);
|
|
2067
|
+
if (signature === lastLead.current) return;
|
|
2068
|
+
lastLead.current = signature;
|
|
2069
|
+
leadInFlight.current = true;
|
|
2070
|
+
current.api.trackLead({
|
|
2071
|
+
...body,
|
|
2072
|
+
funnelCreatedLead: createdLead.current
|
|
2073
|
+
}).then(()=>{
|
|
2074
|
+
createdLead.current = true;
|
|
2075
|
+
}).catch(()=>{}).finally(()=>{
|
|
2076
|
+
leadInFlight.current = false;
|
|
2077
|
+
if (!leadQueued.current) return;
|
|
2078
|
+
leadQueued.current = false;
|
|
2079
|
+
send();
|
|
2080
|
+
});
|
|
2081
|
+
}, []);
|
|
2082
|
+
// Leading edge: the first capture of a burst goes at once. Closing the tab runs no cleanup, so
|
|
2083
|
+
// a capture held back by a plain debounce would be lost; this way only a later refinement is.
|
|
2084
|
+
const captureLead = useCallback(()=>{
|
|
2085
|
+
if (leadTimer.current) {
|
|
2086
|
+
pendingLead.current = true;
|
|
2087
|
+
return;
|
|
2088
|
+
}
|
|
2089
|
+
sendLead();
|
|
2090
|
+
leadTimer.current = setTimeout(function flush() {
|
|
2091
|
+
leadTimer.current = null;
|
|
2092
|
+
if (!pendingLead.current) return;
|
|
2093
|
+
pendingLead.current = false;
|
|
2094
|
+
sendLead();
|
|
2095
|
+
}, LEAD_WAIT_MS);
|
|
2096
|
+
}, [
|
|
2097
|
+
sendLead
|
|
2098
|
+
]);
|
|
2099
|
+
useEffect(()=>()=>{
|
|
2100
|
+
if (leadTimer.current) clearTimeout(leadTimer.current);
|
|
2101
|
+
leadTimer.current = null;
|
|
2102
|
+
if (pendingLead.current) sendLead();
|
|
2103
|
+
pendingLead.current = false;
|
|
2104
|
+
}, [
|
|
2105
|
+
sendLead
|
|
2106
|
+
]);
|
|
2107
|
+
// endregion
|
|
2108
|
+
return useMemo(()=>({
|
|
2109
|
+
captureLead,
|
|
2110
|
+
methodChosen: (chosen)=>{
|
|
2111
|
+
interaction({
|
|
2112
|
+
selectedPaymentMethod: chosen
|
|
2113
|
+
});
|
|
2114
|
+
addPaymentInfo(chosen);
|
|
2115
|
+
},
|
|
2116
|
+
cardFocused: ()=>{
|
|
2117
|
+
if (fired.has('cardInteracted')) return;
|
|
2118
|
+
fired.add('cardInteracted');
|
|
2119
|
+
interaction({
|
|
2120
|
+
cardInteracted: true
|
|
2121
|
+
});
|
|
2122
|
+
addPaymentInfo('credit');
|
|
2123
|
+
},
|
|
2124
|
+
purchased: (paid, amount, id)=>{
|
|
2125
|
+
// Free and subscription purchases count as card, like the standard checkout.
|
|
2126
|
+
const method = paid === 'pix' || paid === 'boleto' ? paid : 'credit';
|
|
2127
|
+
emit('purchase', targets('purchase', (pixel)=>pixel.eventsConfig.purchase?.enabled === true && pixel.eventsConfig.purchase.paymentMethods[method], id), {
|
|
2128
|
+
paymentMethod: method,
|
|
2129
|
+
amountCents: amount,
|
|
2130
|
+
currency: 'BRL',
|
|
2131
|
+
transactionId: id
|
|
2132
|
+
});
|
|
2133
|
+
}
|
|
2134
|
+
}), [
|
|
2135
|
+
captureLead,
|
|
2136
|
+
interaction,
|
|
2137
|
+
addPaymentInfo,
|
|
2138
|
+
fired,
|
|
2139
|
+
emit,
|
|
2140
|
+
targets
|
|
2141
|
+
]);
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
|
|
2145
|
+
|
|
2146
|
+
|
|
2147
|
+
|
|
2148
|
+
|
|
2149
|
+
|
|
2150
|
+
|
|
2151
|
+
|
|
1192
2152
|
|
|
1193
2153
|
|
|
1194
2154
|
|
|
@@ -1212,6 +2172,12 @@ const EMPTY_ADDRESS = {
|
|
|
1212
2172
|
state: '',
|
|
1213
2173
|
country: 'BR'
|
|
1214
2174
|
};
|
|
2175
|
+
const provider_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
|
2176
|
+
const NO_IDS = [];
|
|
2177
|
+
/** Same rule as the server's coupon discount, used only to compare with an automatic coupon. */ function couponDiscount(coupon, base) {
|
|
2178
|
+
const value = coupon.discountValue ?? 0;
|
|
2179
|
+
return coupon.discountType === 'percentage' ? Math.round(base * (value / 100)) : Math.min(value, base);
|
|
2180
|
+
}
|
|
1215
2181
|
const IDLE_SUBMISSION = {
|
|
1216
2182
|
status: 'idle',
|
|
1217
2183
|
error: undefined,
|
|
@@ -1252,7 +2218,7 @@ function staticInstallments(offer) {
|
|
|
1252
2218
|
* session id, affiliate status), the server pricing and an initial coupon, and only the parts that
|
|
1253
2219
|
* depend on them re-render.
|
|
1254
2220
|
*/ function CheckoutProvider(props) {
|
|
1255
|
-
const { offer, transport, paymentsOrigin, location: locationProp, locale = 'pt-BR', messages: messageOverrides, initialPricing, requireEmailConfirmation = false, children } = props;
|
|
2221
|
+
const { offer, transport, paymentsOrigin, location: locationProp, locale = 'pt-BR', messages: messageOverrides, initialPricing, requireEmailConfirmation = false, restorePendingPix = true, children } = props;
|
|
1256
2222
|
const location = locationProp ?? {};
|
|
1257
2223
|
const baseUrl = transport?.baseUrl ?? DEFAULT_PAYMENTS_BASE_URL;
|
|
1258
2224
|
const api = useMemo(()=>createCheckoutApi({
|
|
@@ -1273,13 +2239,22 @@ function staticInstallments(offer) {
|
|
|
1273
2239
|
// `submit` stable.
|
|
1274
2240
|
const propsRef = useRef(props);
|
|
1275
2241
|
propsRef.current = props;
|
|
2242
|
+
// Set once tracking is created below; the purchase callbacks report through it.
|
|
2243
|
+
const trackingRef = useRef(null);
|
|
1276
2244
|
const callbacks = useMemo(()=>({
|
|
1277
|
-
onApproved: (purchase)=>
|
|
2245
|
+
onApproved: (purchase)=>{
|
|
2246
|
+
trackingRef.current?.purchased(purchase.method, purchase.totalAmount, purchase.transactionId);
|
|
2247
|
+
propsRef.current.onApproved?.(purchase);
|
|
2248
|
+
},
|
|
1278
2249
|
onDeclined: (purchase)=>propsRef.current.onDeclined?.(purchase),
|
|
1279
2250
|
onPixGenerated: (pix)=>propsRef.current.onPixGenerated?.(pix),
|
|
1280
|
-
onBoletoGenerated: (boleto)=>
|
|
2251
|
+
onBoletoGenerated: (boleto)=>{
|
|
2252
|
+
trackingRef.current?.purchased('boleto', boleto.totalAmount, boleto.transactionId);
|
|
2253
|
+
propsRef.current.onBoletoGenerated?.(boleto);
|
|
2254
|
+
},
|
|
1281
2255
|
onUpsellAccepted: (purchase)=>propsRef.current.onUpsellAccepted?.(purchase),
|
|
1282
|
-
onUpsellDeclined: (event)=>propsRef.current.onUpsellDeclined?.(event)
|
|
2256
|
+
onUpsellDeclined: (event)=>propsRef.current.onUpsellDeclined?.(event),
|
|
2257
|
+
onPixelEvent: (event)=>propsRef.current.onPixelEvent?.(event)
|
|
1283
2258
|
}), []);
|
|
1284
2259
|
const [isHydrated, setHydrated] = useState(false);
|
|
1285
2260
|
useEffect(()=>setHydrated(true), []);
|
|
@@ -1354,6 +2329,7 @@ function staticInstallments(offer) {
|
|
|
1354
2329
|
phone: current.phone || `+${telephone.countryCode} ${telephone.areaCode}${telephone.number}`,
|
|
1355
2330
|
document: current.document || (oneClickData.document ?? '')
|
|
1356
2331
|
}));
|
|
2332
|
+
if (address.zipCode) lookedUpZip.current = onlyDigits(address.zipCode);
|
|
1357
2333
|
setAddressValues((current)=>current.zipCode ? current : {
|
|
1358
2334
|
zipCode: address.zipCode ?? '',
|
|
1359
2335
|
street: address.street ?? '',
|
|
@@ -1397,6 +2373,123 @@ function staticInstallments(offer) {
|
|
|
1397
2373
|
addressValues,
|
|
1398
2374
|
messages
|
|
1399
2375
|
]);
|
|
2376
|
+
// Zip code lookup. A zip code that came with saved one-click data is not looked up again, so
|
|
2377
|
+
// the buyer's own street is not replaced by the generic one of the zip code.
|
|
2378
|
+
const zipCodeLookup = props.zipCodeLookup === undefined ? viaCepLookup : props.zipCodeLookup;
|
|
2379
|
+
const lookupZip = onlyDigits(addressValues.zipCode);
|
|
2380
|
+
const lookedUpZip = useRef('');
|
|
2381
|
+
const [zipLookup, setZipLookup] = useState({
|
|
2382
|
+
status: 'idle'
|
|
2383
|
+
});
|
|
2384
|
+
useEffect(()=>{
|
|
2385
|
+
if (!zipCodeLookup || isForeign || !addressRequired) return;
|
|
2386
|
+
if (lookupZip.length !== 8 || lookupZip === lookedUpZip.current) return;
|
|
2387
|
+
const controller = new AbortController();
|
|
2388
|
+
const timer = setTimeout(()=>{
|
|
2389
|
+
lookedUpZip.current = lookupZip;
|
|
2390
|
+
setZipLookup({
|
|
2391
|
+
status: 'loading'
|
|
2392
|
+
});
|
|
2393
|
+
zipCodeLookup(lookupZip, {
|
|
2394
|
+
signal: controller.signal
|
|
2395
|
+
}).then((found)=>{
|
|
2396
|
+
// A custom lookup may ignore the signal: a stale answer must not fill the new zip code.
|
|
2397
|
+
if (controller.signal.aborted) return;
|
|
2398
|
+
setZipLookup({
|
|
2399
|
+
status: found ? 'success' : 'error'
|
|
2400
|
+
});
|
|
2401
|
+
if (!found) return;
|
|
2402
|
+
const filled = Object.fromEntries(Object.entries(found).filter(([, value])=>value));
|
|
2403
|
+
setAddressValues((current)=>({
|
|
2404
|
+
...current,
|
|
2405
|
+
...filled
|
|
2406
|
+
}));
|
|
2407
|
+
setAddressErrors((current)=>({
|
|
2408
|
+
...current,
|
|
2409
|
+
...Object.fromEntries(Object.keys(filled).map((key)=>[
|
|
2410
|
+
key,
|
|
2411
|
+
undefined
|
|
2412
|
+
]))
|
|
2413
|
+
}));
|
|
2414
|
+
}).catch(()=>{
|
|
2415
|
+
if (controller.signal.aborted) return;
|
|
2416
|
+
// Typing the address by hand still works; a later edit of the zip code retries.
|
|
2417
|
+
lookedUpZip.current = '';
|
|
2418
|
+
setZipLookup({
|
|
2419
|
+
status: 'error'
|
|
2420
|
+
});
|
|
2421
|
+
});
|
|
2422
|
+
}, 300);
|
|
2423
|
+
return ()=>{
|
|
2424
|
+
clearTimeout(timer);
|
|
2425
|
+
controller.abort();
|
|
2426
|
+
};
|
|
2427
|
+
}, [
|
|
2428
|
+
zipCodeLookup,
|
|
2429
|
+
isForeign,
|
|
2430
|
+
addressRequired,
|
|
2431
|
+
lookupZip
|
|
2432
|
+
]);
|
|
2433
|
+
// endregion
|
|
2434
|
+
// region Settled email and eligibility
|
|
2435
|
+
// The email the automatic coupon and the audience check run against. It settles 600 ms after
|
|
2436
|
+
// typing stops, so a keystroke fires no request; an incomplete email keeps the last valid one
|
|
2437
|
+
// (the coupon must not blink while the buyer fixes a letter), an empty field clears it.
|
|
2438
|
+
const typedEmail = personalDataActive ? personalValues.email.trim().toLowerCase() : oneClickData?.email.trim().toLowerCase() ?? '';
|
|
2439
|
+
const [settledEmail, setSettledEmail] = useState('');
|
|
2440
|
+
useEffect(()=>{
|
|
2441
|
+
if (!typedEmail) {
|
|
2442
|
+
setSettledEmail('');
|
|
2443
|
+
return;
|
|
2444
|
+
}
|
|
2445
|
+
if (!provider_EMAIL.test(typedEmail)) return;
|
|
2446
|
+
const timer = setTimeout(()=>setSettledEmail(typedEmail), 600);
|
|
2447
|
+
return ()=>clearTimeout(timer);
|
|
2448
|
+
}, [
|
|
2449
|
+
typedEmail
|
|
2450
|
+
]);
|
|
2451
|
+
const restrictedBumpIds = useMemo(()=>offer.orderBumps.filter((bump)=>bump.isAudienceRestricted).map((bump)=>bump.id), [
|
|
2452
|
+
offer.orderBumps
|
|
2453
|
+
]);
|
|
2454
|
+
// A trial is once per buyer and product: an email that used it is charged right away.
|
|
2455
|
+
const hasTrial = Boolean(offer.methods.recurrence?.gracePeriod);
|
|
2456
|
+
const checksEligibility = offer.isAudienceRestricted || restrictedBumpIds.length > 0 || hasTrial;
|
|
2457
|
+
const [eligibilityAnswer, setEligibilityAnswer] = useState(undefined);
|
|
2458
|
+
useEffect(()=>{
|
|
2459
|
+
if (!checksEligibility || !settledEmail) return;
|
|
2460
|
+
const controller = new AbortController();
|
|
2461
|
+
api.checkEligibility({
|
|
2462
|
+
offerHash: offer.hash,
|
|
2463
|
+
buyerEmail: settledEmail,
|
|
2464
|
+
orderBumpIds: restrictedBumpIds
|
|
2465
|
+
}, {
|
|
2466
|
+
signal: controller.signal
|
|
2467
|
+
}).then((data)=>setEligibilityAnswer({
|
|
2468
|
+
offer: offer.hash,
|
|
2469
|
+
email: settledEmail,
|
|
2470
|
+
data
|
|
2471
|
+
})).catch(()=>{
|
|
2472
|
+
// No answer blocks nothing: the purchase route refuses an ineligible buyer anyway.
|
|
2473
|
+
});
|
|
2474
|
+
return ()=>controller.abort();
|
|
2475
|
+
}, [
|
|
2476
|
+
api,
|
|
2477
|
+
offer.hash,
|
|
2478
|
+
checksEligibility,
|
|
2479
|
+
settledEmail,
|
|
2480
|
+
restrictedBumpIds
|
|
2481
|
+
]);
|
|
2482
|
+
// An answer counts only for the offer and email it was asked for: the host may swap the offer.
|
|
2483
|
+
const eligibilityData = settledEmail && eligibilityAnswer?.email === settledEmail && eligibilityAnswer.offer === offer.hash ? eligibilityAnswer.data : undefined;
|
|
2484
|
+
const eligibility = useMemo(()=>({
|
|
2485
|
+
offerBlocked: offer.isAudienceRestricted && eligibilityData?.eligible === false,
|
|
2486
|
+
ineligibleBumpIds: eligibilityData?.ineligibleOrderBumpIds ?? NO_IDS,
|
|
2487
|
+
trialAvailable: !(hasTrial && eligibilityData?.trialAvailable === false)
|
|
2488
|
+
}), [
|
|
2489
|
+
offer.isAudienceRestricted,
|
|
2490
|
+
eligibilityData,
|
|
2491
|
+
hasTrial
|
|
2492
|
+
]);
|
|
1400
2493
|
// endregion
|
|
1401
2494
|
// region Order bumps
|
|
1402
2495
|
const requiredBumpIds = useMemo(()=>offer.configs?.orderBump.required.filter((id)=>offer.orderBumps.some((b)=>b.id === id)) ?? [], [
|
|
@@ -1404,15 +2497,19 @@ function staticInstallments(offer) {
|
|
|
1404
2497
|
offer.orderBumps
|
|
1405
2498
|
]);
|
|
1406
2499
|
const [optionalBumpIds, setOptionalBumpIds] = useState([]);
|
|
2500
|
+
// A bump outside the buyer's audience leaves the order, required or not: the purchase would
|
|
2501
|
+
// refuse it, and the buyer can still buy the offer without it.
|
|
1407
2502
|
const selectedBumpIds = useMemo(()=>[
|
|
1408
|
-
...requiredBumpIds,
|
|
1409
|
-
...optionalBumpIds.filter((id)=>!requiredBumpIds.includes(id))
|
|
2503
|
+
...requiredBumpIds.filter((id)=>!eligibility.ineligibleBumpIds.includes(id)),
|
|
2504
|
+
...optionalBumpIds.filter((id)=>!requiredBumpIds.includes(id) && !eligibility.ineligibleBumpIds.includes(id))
|
|
1410
2505
|
], [
|
|
1411
2506
|
requiredBumpIds,
|
|
1412
|
-
optionalBumpIds
|
|
2507
|
+
optionalBumpIds,
|
|
2508
|
+
eligibility.ineligibleBumpIds
|
|
1413
2509
|
]);
|
|
1414
2510
|
const toggleBump = useCallback((id, selected)=>{
|
|
1415
2511
|
if (requiredBumpIds.includes(id)) return;
|
|
2512
|
+
if (selected !== false && eligibility.ineligibleBumpIds.includes(id)) return;
|
|
1416
2513
|
setOptionalBumpIds((current)=>{
|
|
1417
2514
|
const isSelected = current.includes(id);
|
|
1418
2515
|
const next = selected ?? !isSelected;
|
|
@@ -1423,16 +2520,18 @@ function staticInstallments(offer) {
|
|
|
1423
2520
|
] : current.filter((value)=>value !== id);
|
|
1424
2521
|
});
|
|
1425
2522
|
}, [
|
|
1426
|
-
requiredBumpIds
|
|
2523
|
+
requiredBumpIds,
|
|
2524
|
+
eligibility.ineligibleBumpIds
|
|
1427
2525
|
]);
|
|
1428
2526
|
// endregion
|
|
1429
2527
|
// region Coupon and pricing
|
|
1430
2528
|
const [couponCode, setCouponCode] = useState(undefined);
|
|
2529
|
+
const [couponSource, setCouponSource] = useState(undefined);
|
|
1431
2530
|
const [couponStatus, setCouponStatus] = useState('idle');
|
|
1432
2531
|
const [couponResult, setCouponResult] = useState(undefined);
|
|
1433
2532
|
const couponRequest = useRef(0);
|
|
1434
|
-
const buyerEmail =
|
|
1435
|
-
const
|
|
2533
|
+
const buyerEmail = provider_EMAIL.test(personalValues.email.trim()) ? personalValues.email.trim().toLowerCase() : oneClickData?.email;
|
|
2534
|
+
const applyCouponFrom = useCallback(async (code, source)=>{
|
|
1436
2535
|
const normalized = code.trim().toUpperCase();
|
|
1437
2536
|
if (!normalized) return false;
|
|
1438
2537
|
const request = ++couponRequest.current;
|
|
@@ -1448,11 +2547,13 @@ function staticInstallments(offer) {
|
|
|
1448
2547
|
setCouponResult(result);
|
|
1449
2548
|
setCouponStatus(result.valid ? 'valid' : 'invalid');
|
|
1450
2549
|
setCouponCode(result.valid ? normalized : undefined);
|
|
2550
|
+
setCouponSource(result.valid ? source : undefined);
|
|
1451
2551
|
return result.valid;
|
|
1452
2552
|
} catch {
|
|
1453
2553
|
if (request === couponRequest.current) {
|
|
1454
2554
|
setCouponStatus('invalid');
|
|
1455
2555
|
setCouponCode(undefined);
|
|
2556
|
+
setCouponSource(undefined);
|
|
1456
2557
|
}
|
|
1457
2558
|
return false;
|
|
1458
2559
|
}
|
|
@@ -1461,23 +2562,106 @@ function staticInstallments(offer) {
|
|
|
1461
2562
|
offer.hash,
|
|
1462
2563
|
buyerEmail
|
|
1463
2564
|
]);
|
|
1464
|
-
const
|
|
2565
|
+
const applyCoupon = useCallback((code)=>applyCouponFrom(code, 'manual'), [
|
|
2566
|
+
applyCouponFrom
|
|
2567
|
+
]);
|
|
2568
|
+
const clearCoupon = useCallback(()=>{
|
|
1465
2569
|
couponRequest.current++;
|
|
1466
2570
|
setCouponCode(undefined);
|
|
2571
|
+
setCouponSource(undefined);
|
|
1467
2572
|
setCouponResult(undefined);
|
|
1468
2573
|
setCouponStatus('idle');
|
|
1469
2574
|
}, []);
|
|
2575
|
+
// The buyer removing an automatic coupon keeps it off for that email.
|
|
2576
|
+
const dismissedAutoEmail = useRef('');
|
|
2577
|
+
const removeCoupon = useCallback(()=>{
|
|
2578
|
+
if (couponSource === 'auto') dismissedAutoEmail.current = settledEmail;
|
|
2579
|
+
clearCoupon();
|
|
2580
|
+
}, [
|
|
2581
|
+
couponSource,
|
|
2582
|
+
settledEmail,
|
|
2583
|
+
clearCoupon
|
|
2584
|
+
]);
|
|
1470
2585
|
// A coupon from the link is applied once, after hydration (it is per visit, not per page).
|
|
1471
2586
|
const initialCoupon = location.couponCode;
|
|
1472
2587
|
const appliedInitialCoupon = useRef(false);
|
|
1473
2588
|
useEffect(()=>{
|
|
1474
2589
|
if (appliedInitialCoupon.current || !initialCoupon || !offer.showCoupon) return;
|
|
1475
2590
|
appliedInitialCoupon.current = true;
|
|
1476
|
-
void
|
|
2591
|
+
void applyCouponFrom(initialCoupon, 'link');
|
|
1477
2592
|
}, [
|
|
1478
2593
|
initialCoupon,
|
|
1479
2594
|
offer.showCoupon,
|
|
1480
|
-
|
|
2595
|
+
applyCouponFrom
|
|
2596
|
+
]);
|
|
2597
|
+
// Automatic coupon: each settled email asks the server for the best coupon the seller reserved
|
|
2598
|
+
// for it. The effect below decides whether it replaces the coupon already applied.
|
|
2599
|
+
const [autoCandidate, setAutoCandidate] = useState(undefined);
|
|
2600
|
+
useEffect(()=>{
|
|
2601
|
+
if (!settledEmail) return;
|
|
2602
|
+
const controller = new AbortController();
|
|
2603
|
+
api.findAutoCoupon({
|
|
2604
|
+
offerHash: offer.hash,
|
|
2605
|
+
buyerEmail: settledEmail
|
|
2606
|
+
}, {
|
|
2607
|
+
signal: controller.signal
|
|
2608
|
+
}).then((coupon)=>setAutoCandidate({
|
|
2609
|
+
offer: offer.hash,
|
|
2610
|
+
email: settledEmail,
|
|
2611
|
+
coupon
|
|
2612
|
+
})).catch(()=>{
|
|
2613
|
+
// A failure only means no automatic discount.
|
|
2614
|
+
if (!controller.signal.aborted) setAutoCandidate({
|
|
2615
|
+
offer: offer.hash,
|
|
2616
|
+
email: settledEmail,
|
|
2617
|
+
coupon: null
|
|
2618
|
+
});
|
|
2619
|
+
});
|
|
2620
|
+
return ()=>controller.abort();
|
|
2621
|
+
}, [
|
|
2622
|
+
api,
|
|
2623
|
+
offer.hash,
|
|
2624
|
+
settledEmail
|
|
2625
|
+
]);
|
|
2626
|
+
useEffect(()=>{
|
|
2627
|
+
if (!autoCandidate || autoCandidate.email !== settledEmail || autoCandidate.offer !== offer.hash) return;
|
|
2628
|
+
if (couponStatus === 'validating') return;
|
|
2629
|
+
const applied = couponStatus === 'valid' && couponCode !== undefined;
|
|
2630
|
+
const candidate = autoCandidate.coupon;
|
|
2631
|
+
if (!candidate) {
|
|
2632
|
+
// Switched to an email with no right to it: drop the discount that was only for the last.
|
|
2633
|
+
if (applied && couponSource === 'auto') clearCoupon();
|
|
2634
|
+
return;
|
|
2635
|
+
}
|
|
2636
|
+
if (dismissedAutoEmail.current === settledEmail) return;
|
|
2637
|
+
if (applied) {
|
|
2638
|
+
if (couponSource === 'auto' && couponCode === candidate.code) return;
|
|
2639
|
+
if (couponSource !== 'auto') {
|
|
2640
|
+
// A typed or link coupon still waiting for the email check: let that check decide.
|
|
2641
|
+
if (couponResult?.pendingBuyerCheck) return;
|
|
2642
|
+
if (couponResult && couponDiscount(couponResult, offerPrice(offer)) >= candidate.discount) return;
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
couponRequest.current++;
|
|
2646
|
+
setCouponCode(candidate.code);
|
|
2647
|
+
setCouponSource('auto');
|
|
2648
|
+
setCouponResult({
|
|
2649
|
+
valid: true,
|
|
2650
|
+
code: candidate.code,
|
|
2651
|
+
discountType: candidate.discountType,
|
|
2652
|
+
discountValue: candidate.discountValue,
|
|
2653
|
+
pendingBuyerCheck: false
|
|
2654
|
+
});
|
|
2655
|
+
setCouponStatus('valid');
|
|
2656
|
+
}, [
|
|
2657
|
+
autoCandidate,
|
|
2658
|
+
settledEmail,
|
|
2659
|
+
couponStatus,
|
|
2660
|
+
couponCode,
|
|
2661
|
+
couponSource,
|
|
2662
|
+
couponResult,
|
|
2663
|
+
offer,
|
|
2664
|
+
clearCoupon
|
|
1481
2665
|
]);
|
|
1482
2666
|
const [pricing, setPricing] = useState({
|
|
1483
2667
|
status: initialPricing ? 'success' : 'idle',
|
|
@@ -1615,6 +2799,35 @@ function staticInstallments(offer) {
|
|
|
1615
2799
|
const [cardHolderName, setCardHolderName] = useState('');
|
|
1616
2800
|
const [card, registerCard] = useState(undefined);
|
|
1617
2801
|
// endregion
|
|
2802
|
+
// region Recurrence
|
|
2803
|
+
const offerRecurrence = 'recurrence' in offer.methods ? offer.methods.recurrence : undefined;
|
|
2804
|
+
const recurrence = useMemo(()=>offerRecurrence ? {
|
|
2805
|
+
frequency: offerRecurrence.frequency,
|
|
2806
|
+
interval: offerRecurrence.interval,
|
|
2807
|
+
// A buyer who already used the product's trial pays today, like the standard checkout.
|
|
2808
|
+
gracePeriod: eligibility.trialAvailable ? offerRecurrence.gracePeriod : 0,
|
|
2809
|
+
tolerancePeriod: offerRecurrence.tolerancePeriod,
|
|
2810
|
+
maxCharges: offerRecurrence.maxCharges ?? null
|
|
2811
|
+
} : undefined, [
|
|
2812
|
+
offerRecurrence,
|
|
2813
|
+
eligibility.trialAvailable
|
|
2814
|
+
]);
|
|
2815
|
+
// endregion
|
|
2816
|
+
const tracking = useCheckoutTracking({
|
|
2817
|
+
api,
|
|
2818
|
+
offer,
|
|
2819
|
+
location,
|
|
2820
|
+
affiliateHash,
|
|
2821
|
+
pixels,
|
|
2822
|
+
visitorSettled: visitor.status === 'success' || visitor.status === 'error',
|
|
2823
|
+
personalDataActive,
|
|
2824
|
+
personalData: personalValues,
|
|
2825
|
+
oneClick: oneClickData,
|
|
2826
|
+
address: addressRequired ? addressValues : undefined,
|
|
2827
|
+
method,
|
|
2828
|
+
callbacks
|
|
2829
|
+
});
|
|
2830
|
+
trackingRef.current = tracking;
|
|
1618
2831
|
// region Summary
|
|
1619
2832
|
const summary = useMemo(()=>{
|
|
1620
2833
|
const data = pricing.data;
|
|
@@ -1673,14 +2886,27 @@ function staticInstallments(offer) {
|
|
|
1673
2886
|
recurrenceFrequency: bump.recurrenceFrequency,
|
|
1674
2887
|
selected: selectedBumpIds.includes(bump.id),
|
|
1675
2888
|
required: requiredBumpIds.includes(bump.id),
|
|
1676
|
-
|
|
2889
|
+
ineligible: eligibility.ineligibleBumpIds.includes(bump.id),
|
|
2890
|
+
disabled: eligibility.ineligibleBumpIds.includes(bump.id) || (method ? !bump.paymentMethods[method] : false),
|
|
2891
|
+
trial: bump.gracePeriod > 0 ? {
|
|
2892
|
+
days: bump.gracePeriod,
|
|
2893
|
+
...bumpTrialTexts(messages, locale, {
|
|
2894
|
+
custom: offer.configs?.orderBump.trialTexts?.[bump.id],
|
|
2895
|
+
days: bump.gracePeriod,
|
|
2896
|
+
price: bumpPrice(bump),
|
|
2897
|
+
frequency: bump.recurrenceFrequency
|
|
2898
|
+
})
|
|
2899
|
+
} : undefined
|
|
1677
2900
|
}));
|
|
1678
2901
|
}, [
|
|
1679
2902
|
offer,
|
|
1680
2903
|
pricing.data?.items,
|
|
1681
2904
|
selectedBumpIds,
|
|
1682
2905
|
requiredBumpIds,
|
|
1683
|
-
method
|
|
2906
|
+
method,
|
|
2907
|
+
eligibility,
|
|
2908
|
+
messages,
|
|
2909
|
+
locale
|
|
1684
2910
|
]);
|
|
1685
2911
|
const requiredBumps = useMemo(()=>bumpItems.filter((bump)=>bump.required), [
|
|
1686
2912
|
bumpItems
|
|
@@ -1691,6 +2917,45 @@ function staticInstallments(offer) {
|
|
|
1691
2917
|
// Empty title falls back to the translated default: older pages have no title.
|
|
1692
2918
|
const bumpTitle = offer.configs?.orderBump.title?.trim() || (optionalBumps.length > 1 ? messages.specialOffers : messages.specialOffer);
|
|
1693
2919
|
// endregion
|
|
2920
|
+
// region Availability and notices
|
|
2921
|
+
const availability = useMemo(()=>({
|
|
2922
|
+
status: offer.isSellerPending || offer.isOfferUnavailable ? 'unavailable' : offer.isAnyOfferPending ? 'pendingApproval' : 'available',
|
|
2923
|
+
supportEmail: offer.supportEmail || undefined
|
|
2924
|
+
}), [
|
|
2925
|
+
offer.isSellerPending,
|
|
2926
|
+
offer.isOfferUnavailable,
|
|
2927
|
+
offer.isAnyOfferPending,
|
|
2928
|
+
offer.supportEmail
|
|
2929
|
+
]);
|
|
2930
|
+
const notices = useMemo(()=>{
|
|
2931
|
+
const list = [];
|
|
2932
|
+
const notice = (kind, message, extra = {})=>list.push({
|
|
2933
|
+
kind,
|
|
2934
|
+
message,
|
|
2935
|
+
title: undefined,
|
|
2936
|
+
supportEmail: undefined,
|
|
2937
|
+
...extra
|
|
2938
|
+
});
|
|
2939
|
+
if (availability.status === 'unavailable') {
|
|
2940
|
+
notice('unavailable', messages.checkoutUnavailable, {
|
|
2941
|
+
title: messages.checkoutUnavailableTitle,
|
|
2942
|
+
supportEmail: availability.supportEmail
|
|
2943
|
+
});
|
|
2944
|
+
} else if (availability.status === 'pendingApproval') {
|
|
2945
|
+
notice('pendingApproval', messages.offerPendingApproval);
|
|
2946
|
+
}
|
|
2947
|
+
if (eligibility.offerBlocked) notice('offerIneligible', messages.offerBuyerNotEligible);
|
|
2948
|
+
else if (!eligibility.trialAvailable) notice('trialUnavailable', messages.trialUnavailable);
|
|
2949
|
+
if (offer.showAffiliateAccountNotice) notice('affiliateAccount', messages.affiliateAccountNotice);
|
|
2950
|
+
return list;
|
|
2951
|
+
}, [
|
|
2952
|
+
availability,
|
|
2953
|
+
eligibility,
|
|
2954
|
+
offer.showAffiliateAccountNotice,
|
|
2955
|
+
messages
|
|
2956
|
+
]);
|
|
2957
|
+
const purchaseBlocked = availability.status === 'unavailable' ? messages.checkoutUnavailableTitle : availability.status === 'pendingApproval' ? messages.offerPendingApproval : eligibility.offerBlocked ? messages.offerBuyerNotEligible : undefined;
|
|
2958
|
+
// endregion
|
|
1694
2959
|
// region Submit
|
|
1695
2960
|
const [submission, setSubmissionState] = useState(IDLE_SUBMISSION);
|
|
1696
2961
|
// Mirrors `submission` synchronously so a running purchase (pix polling) can tell whether the
|
|
@@ -1716,6 +2981,8 @@ function staticInstallments(offer) {
|
|
|
1716
2981
|
callbacks,
|
|
1717
2982
|
getRecaptchaToken: ()=>propsRef.current.getRecaptchaToken?.() ?? Promise.resolve(''),
|
|
1718
2983
|
pixPollIntervalMs: positiveFinite(props.pixPollIntervalMs, 5000),
|
|
2984
|
+
persistPendingPix: restorePendingPix,
|
|
2985
|
+
purchaseBlocked,
|
|
1719
2986
|
affiliateHash,
|
|
1720
2987
|
oneClick: oneClickData,
|
|
1721
2988
|
personalDataActive,
|
|
@@ -1748,12 +3015,54 @@ function staticInstallments(offer) {
|
|
|
1748
3015
|
}, []);
|
|
1749
3016
|
const reset = useCallback(()=>{
|
|
1750
3017
|
attempts.current++;
|
|
3018
|
+
clearPendingPix(offer.hash);
|
|
1751
3019
|
setSubmission(()=>IDLE_SUBMISSION);
|
|
1752
3020
|
}, [
|
|
1753
3021
|
attempts,
|
|
3022
|
+
setSubmission,
|
|
3023
|
+
offer.hash
|
|
3024
|
+
]);
|
|
3025
|
+
// Back to the pix generated before a reload, after hydration (storage is browser-only). It does
|
|
3026
|
+
// not fire `onPixGenerated` again; polling resumes and `onApproved` fires once it is paid.
|
|
3027
|
+
useEffect(()=>{
|
|
3028
|
+
if (!restorePendingPix) return;
|
|
3029
|
+
const pix = readPendingPix(offer.hash);
|
|
3030
|
+
const state = stateRef.current;
|
|
3031
|
+
if (!pix || !state || submissionRef.current.status !== 'idle') return;
|
|
3032
|
+
setSubmission(()=>({
|
|
3033
|
+
...IDLE_SUBMISSION,
|
|
3034
|
+
status: 'pix_pending',
|
|
3035
|
+
pix,
|
|
3036
|
+
transactionId: pix.transactionId
|
|
3037
|
+
}));
|
|
3038
|
+
void watchPix(state, pix.transactionId, pix.totalAmount);
|
|
3039
|
+
}, [
|
|
3040
|
+
restorePendingPix,
|
|
3041
|
+
offer.hash,
|
|
1754
3042
|
setSubmission
|
|
1755
3043
|
]);
|
|
1756
3044
|
// endregion
|
|
3045
|
+
// region Social proof
|
|
3046
|
+
const [socialProofDismissed, setSocialProofDismissed] = useState(false);
|
|
3047
|
+
// sessionStorage only after hydration (SSR contract); a new offer reads its own key.
|
|
3048
|
+
useEffect(()=>setSocialProofDismissed(readDismissed(offer.hash)), [
|
|
3049
|
+
offer.hash
|
|
3050
|
+
]);
|
|
3051
|
+
// Once the payment is sent no balloon may show again, even after `reset` (as the standard
|
|
3052
|
+
// checkout): a balloon over a pix code or a refusal message distracts at the worst moment.
|
|
3053
|
+
const [paymentStarted, setPaymentStarted] = useState(false);
|
|
3054
|
+
useEffect(()=>{
|
|
3055
|
+
if (submission.status !== 'idle') setPaymentStarted(true);
|
|
3056
|
+
}, [
|
|
3057
|
+
submission.status
|
|
3058
|
+
]);
|
|
3059
|
+
const dismissSocialProof = useCallback(()=>{
|
|
3060
|
+
writeDismissed(offer.hash);
|
|
3061
|
+
setSocialProofDismissed(true);
|
|
3062
|
+
}, [
|
|
3063
|
+
offer.hash
|
|
3064
|
+
]);
|
|
3065
|
+
// endregion
|
|
1757
3066
|
const value = {
|
|
1758
3067
|
offer,
|
|
1759
3068
|
api,
|
|
@@ -1784,7 +3093,8 @@ function staticInstallments(offer) {
|
|
|
1784
3093
|
}));
|
|
1785
3094
|
},
|
|
1786
3095
|
validate: validatePersonal,
|
|
1787
|
-
isActive: personalDataActive
|
|
3096
|
+
isActive: personalDataActive,
|
|
3097
|
+
captureLead: tracking.captureLead
|
|
1788
3098
|
},
|
|
1789
3099
|
address: {
|
|
1790
3100
|
values: addressValues,
|
|
@@ -1800,7 +3110,8 @@ function staticInstallments(offer) {
|
|
|
1800
3110
|
}));
|
|
1801
3111
|
},
|
|
1802
3112
|
validate: validateAddressFields,
|
|
1803
|
-
required: addressRequired
|
|
3113
|
+
required: addressRequired,
|
|
3114
|
+
lookup: zipLookup
|
|
1804
3115
|
},
|
|
1805
3116
|
bumps: {
|
|
1806
3117
|
items: bumpItems,
|
|
@@ -1811,9 +3122,15 @@ function staticInstallments(offer) {
|
|
|
1811
3122
|
toggle: toggleBump
|
|
1812
3123
|
},
|
|
1813
3124
|
pricing,
|
|
3125
|
+
recurrence,
|
|
1814
3126
|
summary,
|
|
3127
|
+
availability,
|
|
3128
|
+
eligibility,
|
|
3129
|
+
notices,
|
|
3130
|
+
purchaseBlocked,
|
|
1815
3131
|
coupon: {
|
|
1816
3132
|
code: couponCode,
|
|
3133
|
+
source: couponSource,
|
|
1817
3134
|
status: couponStatus,
|
|
1818
3135
|
result: couponResult,
|
|
1819
3136
|
apply: applyCoupon,
|
|
@@ -1829,7 +3146,10 @@ function staticInstallments(offer) {
|
|
|
1829
3146
|
payment: {
|
|
1830
3147
|
methods,
|
|
1831
3148
|
method,
|
|
1832
|
-
setMethod:
|
|
3149
|
+
setMethod: (next)=>{
|
|
3150
|
+
setChosenMethod(next);
|
|
3151
|
+
tracking.methodChosen(next);
|
|
3152
|
+
},
|
|
1833
3153
|
installments,
|
|
1834
3154
|
installment,
|
|
1835
3155
|
setInstallment: setChosenInstallment,
|
|
@@ -1839,7 +3159,13 @@ function staticInstallments(offer) {
|
|
|
1839
3159
|
cardHolderName,
|
|
1840
3160
|
setCardHolderName,
|
|
1841
3161
|
card,
|
|
1842
|
-
registerCard
|
|
3162
|
+
registerCard,
|
|
3163
|
+
cardInteracted: tracking.cardFocused
|
|
3164
|
+
},
|
|
3165
|
+
socialProof: {
|
|
3166
|
+
enabled: Boolean(offer.socialProof?.enabled),
|
|
3167
|
+
stopped: socialProofDismissed || paymentStarted,
|
|
3168
|
+
dismiss: dismissSocialProof
|
|
1843
3169
|
},
|
|
1844
3170
|
submission,
|
|
1845
3171
|
submit,
|
|
@@ -1877,7 +3203,9 @@ const ELEMENTS_LOCALE = {
|
|
|
1877
3203
|
const propsRef = useRef(props);
|
|
1878
3204
|
propsRef.current = props;
|
|
1879
3205
|
const showFrame = !payment.useSavedCard;
|
|
1880
|
-
const { registerCard } = payment;
|
|
3206
|
+
const { registerCard, cardInteracted } = payment;
|
|
3207
|
+
const cardInteractedRef = useRef(cardInteracted);
|
|
3208
|
+
cardInteractedRef.current = cardInteracted;
|
|
1881
3209
|
// Created once per mount, like react-stripe-js: later prop changes go through `update`.
|
|
1882
3210
|
useClientLayoutEffect(()=>{
|
|
1883
3211
|
if (!showFrame || !containerRef.current) return;
|
|
@@ -1894,7 +3222,10 @@ const ELEMENTS_LOCALE = {
|
|
|
1894
3222
|
locale: ELEMENTS_LOCALE[locale],
|
|
1895
3223
|
disabled: propsRef.current.disabled
|
|
1896
3224
|
});
|
|
1897
|
-
card.on('ready', ()=>propsRef.current.onReady?.()).on('change', (event)=>propsRef.current.onChange?.(event)).on('focus', (event)=>
|
|
3225
|
+
card.on('ready', ()=>propsRef.current.onReady?.()).on('change', (event)=>propsRef.current.onChange?.(event)).on('focus', (event)=>{
|
|
3226
|
+
cardInteractedRef.current();
|
|
3227
|
+
propsRef.current.onFocus?.(event);
|
|
3228
|
+
}).on('blur', (event)=>propsRef.current.onBlur?.(event)).on('loaderror', (event)=>propsRef.current.onLoadError?.(event));
|
|
1898
3229
|
card.mount(containerRef.current);
|
|
1899
3230
|
cardRef.current = card;
|
|
1900
3231
|
registerCard(card);
|
|
@@ -1942,6 +3273,8 @@ const ELEMENTS_LOCALE = {
|
|
|
1942
3273
|
|
|
1943
3274
|
|
|
1944
3275
|
|
|
3276
|
+
|
|
3277
|
+
|
|
1945
3278
|
/** Formats cents with the checkout locale. */ function useFormatMoney() {
|
|
1946
3279
|
const { locale } = useCheckout();
|
|
1947
3280
|
return useCallback((cents)=>formatMoney(cents, locale), [
|
|
@@ -1949,7 +3282,7 @@ const ELEMENTS_LOCALE = {
|
|
|
1949
3282
|
]);
|
|
1950
3283
|
}
|
|
1951
3284
|
/** Main item and price of the offer. */ function useOfferItem() {
|
|
1952
|
-
const { offer, pricing, payment } = useCheckout();
|
|
3285
|
+
const { offer, pricing, payment, messages, recurrence } = useCheckout();
|
|
1953
3286
|
const format = useFormatMoney();
|
|
1954
3287
|
const main = pricing.data?.items.find((item)=>item.type === 'main');
|
|
1955
3288
|
const price = main?.effectivePrice ?? offer.newPrice ?? offer.originalPrice;
|
|
@@ -1969,7 +3302,32 @@ const ELEMENTS_LOCALE = {
|
|
|
1969
3302
|
installment: last.installment,
|
|
1970
3303
|
value: last.value,
|
|
1971
3304
|
formattedValue: format(last.value)
|
|
1972
|
-
} : undefined
|
|
3305
|
+
} : undefined,
|
|
3306
|
+
highlightInstallment: offer.highlightInstallment,
|
|
3307
|
+
perFrequency: recurrence ? perFrequency(messages, recurrence.frequency) : '',
|
|
3308
|
+
freeTrialDays: recurrence?.gracePeriod ?? 0
|
|
3309
|
+
};
|
|
3310
|
+
}
|
|
3311
|
+
/** Period, free trial and charge limit of a recurring offer; `undefined` for one-time offers. */ function useRecurrence() {
|
|
3312
|
+
const { recurrence, messages, locale, payment } = useCheckout();
|
|
3313
|
+
const item = useOfferItem();
|
|
3314
|
+
if (!recurrence) return undefined;
|
|
3315
|
+
const per = perFrequency(messages, recurrence.frequency);
|
|
3316
|
+
const selected = payment.installments.find((option)=>option.installment === payment.installment);
|
|
3317
|
+
const hasTrial = recurrence.gracePeriod > 0;
|
|
3318
|
+
return {
|
|
3319
|
+
...recurrence,
|
|
3320
|
+
perFrequency: per,
|
|
3321
|
+
trialText: hasTrial ? fillMessage(messages.freeTrial, {
|
|
3322
|
+
days: recurrence.gracePeriod
|
|
3323
|
+
}) : undefined,
|
|
3324
|
+
postTrialText: hasTrial ? postTrialText(messages, locale, {
|
|
3325
|
+
cashValue: item.price,
|
|
3326
|
+
installment: payment.method === 'credit' ? payment.installment : 1,
|
|
3327
|
+
installmentValue: selected?.value,
|
|
3328
|
+
per
|
|
3329
|
+
}) : undefined,
|
|
3330
|
+
chargeLimitText: chargeLimitText(messages, recurrence.maxCharges)
|
|
1973
3331
|
};
|
|
1974
3332
|
}
|
|
1975
3333
|
/** Order bumps and their selection. */ function useOrderBumps() {
|
|
@@ -2014,12 +3372,13 @@ const ELEMENTS_LOCALE = {
|
|
|
2014
3372
|
};
|
|
2015
3373
|
}
|
|
2016
3374
|
/** Purchase state and the function that submits it. */ function useSubmit() {
|
|
2017
|
-
const { submit, reset, submission } = useCheckout();
|
|
3375
|
+
const { submit, reset, submission, purchaseBlocked } = useCheckout();
|
|
2018
3376
|
return {
|
|
2019
3377
|
submit,
|
|
2020
3378
|
reset,
|
|
2021
3379
|
submission,
|
|
2022
|
-
isSubmitting: submission.status === 'submitting' || submission.status === 'processing'
|
|
3380
|
+
isSubmitting: submission.status === 'submitting' || submission.status === 'processing',
|
|
3381
|
+
blocked: purchaseBlocked
|
|
2023
3382
|
};
|
|
2024
3383
|
}
|
|
2025
3384
|
/**
|
|
@@ -2092,6 +3451,7 @@ const ELEMENTS_LOCALE = {
|
|
|
2092
3451
|
]);
|
|
2093
3452
|
return {
|
|
2094
3453
|
pix,
|
|
3454
|
+
restored: Boolean(pix?.restored),
|
|
2095
3455
|
secondsLeft: pix?.expiresAt && Number.isFinite(left) ? left : undefined,
|
|
2096
3456
|
expired: Boolean(pix?.expiresAt) && left === 0,
|
|
2097
3457
|
copy,
|
|
@@ -2127,6 +3487,168 @@ const ELEMENTS_LOCALE = {
|
|
|
2127
3487
|
decline
|
|
2128
3488
|
};
|
|
2129
3489
|
}
|
|
3490
|
+
// Timings of the standard checkout: first balloon after 8 s, 5 s on screen, 10 s between them.
|
|
3491
|
+
const SOCIAL_PROOF_FIRST_DELAY_MS = 8000;
|
|
3492
|
+
const SOCIAL_PROOF_GAP_MS = 10000;
|
|
3493
|
+
const SOCIAL_PROOF_VISIBLE_MS = 5000;
|
|
3494
|
+
const SOCIAL_PROOF_EXIT_MS = 200;
|
|
3495
|
+
const RECENT_ACTIVITY_REFETCH_MS = 15000;
|
|
3496
|
+
/**
|
|
3497
|
+
* Social proof balloons of the offer, one at a time: recent purchases first (newest first), then
|
|
3498
|
+
* the counts (purchases, views, order bumps), up to the seller's maximum of balloons. Window and
|
|
3499
|
+
* minimum per type are applied by the API.
|
|
3500
|
+
*
|
|
3501
|
+
* Fetches the counts once per visit and the recent activity every 15 s, both after hydration and
|
|
3502
|
+
* only while mounted, so render it once per page (`SocialProof` does). Pauses while the tab is
|
|
3503
|
+
* hidden, and stops for good when the buyer closes it or sends the payment.
|
|
3504
|
+
*/ function useSocialProof() {
|
|
3505
|
+
const { offer, api, isHydrated, messages, locale, socialProof } = useCheckout();
|
|
3506
|
+
const config = offer.socialProof;
|
|
3507
|
+
const active = isHydrated && socialProof.enabled && !socialProof.stopped;
|
|
3508
|
+
const activityOn = Boolean(config?.recentActivity?.enabled);
|
|
3509
|
+
const maxBalloons = config?.maxBalloons ?? 0;
|
|
3510
|
+
const [counts, setCounts] = useState([]);
|
|
3511
|
+
useEffect(()=>{
|
|
3512
|
+
if (!active) return;
|
|
3513
|
+
const controller = new AbortController();
|
|
3514
|
+
api.getSocialProof({
|
|
3515
|
+
offer: offer.hash
|
|
3516
|
+
}, {
|
|
3517
|
+
signal: controller.signal
|
|
3518
|
+
})// Failure = no count balloons; the checkout goes on.
|
|
3519
|
+
.then((data)=>setCounts(data.items)).catch(()=>{});
|
|
3520
|
+
return ()=>controller.abort();
|
|
3521
|
+
// Once per offer: the numbers do not refresh with the page open.
|
|
3522
|
+
}, [
|
|
3523
|
+
active,
|
|
3524
|
+
api,
|
|
3525
|
+
offer.hash
|
|
3526
|
+
]);
|
|
3527
|
+
const [activity, setActivity] = useState([]);
|
|
3528
|
+
useEffect(()=>{
|
|
3529
|
+
if (!active || !activityOn) return;
|
|
3530
|
+
const controller = new AbortController();
|
|
3531
|
+
let timer;
|
|
3532
|
+
// The next request starts only after the previous one settles, so a slow answer can never
|
|
3533
|
+
// land after (and overwrite) a newer one.
|
|
3534
|
+
const load = ()=>api.getRecentActivity({
|
|
3535
|
+
offer: offer.hash
|
|
3536
|
+
}, {
|
|
3537
|
+
signal: controller.signal
|
|
3538
|
+
}).then((data)=>setActivity(data.items)).catch(()=>{}).finally(()=>{
|
|
3539
|
+
if (!controller.signal.aborted) timer = setTimeout(load, RECENT_ACTIVITY_REFETCH_MS);
|
|
3540
|
+
});
|
|
3541
|
+
void load();
|
|
3542
|
+
return ()=>{
|
|
3543
|
+
clearTimeout(timer);
|
|
3544
|
+
controller.abort();
|
|
3545
|
+
};
|
|
3546
|
+
}, [
|
|
3547
|
+
active,
|
|
3548
|
+
activityOn,
|
|
3549
|
+
api,
|
|
3550
|
+
offer.hash
|
|
3551
|
+
]);
|
|
3552
|
+
const [hidden, setHidden] = useState(false);
|
|
3553
|
+
useEffect(()=>{
|
|
3554
|
+
if (!active) return;
|
|
3555
|
+
const update = ()=>setHidden(document.hidden);
|
|
3556
|
+
update();
|
|
3557
|
+
document.addEventListener('visibilitychange', update);
|
|
3558
|
+
return ()=>document.removeEventListener('visibilitychange', update);
|
|
3559
|
+
}, [
|
|
3560
|
+
active
|
|
3561
|
+
]);
|
|
3562
|
+
const [progress, setProgress] = useState({
|
|
3563
|
+
seenIds: [],
|
|
3564
|
+
countsShown: 0,
|
|
3565
|
+
current: null
|
|
3566
|
+
});
|
|
3567
|
+
const [phase, setPhase] = useState('waiting');
|
|
3568
|
+
// A host that swaps the offer without remounting starts the balloons over: counts, activity and
|
|
3569
|
+
// progress of the previous offer must not show (or hide events) in the new checkout.
|
|
3570
|
+
const [stateHash, setStateHash] = useState(offer.hash);
|
|
3571
|
+
if (stateHash !== offer.hash) {
|
|
3572
|
+
setStateHash(offer.hash);
|
|
3573
|
+
setCounts([]);
|
|
3574
|
+
setActivity([]);
|
|
3575
|
+
setProgress({
|
|
3576
|
+
seenIds: [],
|
|
3577
|
+
countsShown: 0,
|
|
3578
|
+
current: null
|
|
3579
|
+
});
|
|
3580
|
+
setPhase('waiting');
|
|
3581
|
+
}
|
|
3582
|
+
const [engaged, setEngaged] = useState(false);
|
|
3583
|
+
useEffect(()=>{
|
|
3584
|
+
if (phase === 'waiting') setEngaged(false);
|
|
3585
|
+
}, [
|
|
3586
|
+
phase
|
|
3587
|
+
]);
|
|
3588
|
+
const ordered = orderCounts(counts, maxBalloons);
|
|
3589
|
+
const { seenIds, countsShown, current } = progress;
|
|
3590
|
+
const shown = seenIds.length + countsShown;
|
|
3591
|
+
const next = pickNext({
|
|
3592
|
+
counts: ordered,
|
|
3593
|
+
activity,
|
|
3594
|
+
seenIds,
|
|
3595
|
+
countsShown,
|
|
3596
|
+
maxBalloons
|
|
3597
|
+
});
|
|
3598
|
+
// No next while waiting = queue done for now; a new event from polling reopens it.
|
|
3599
|
+
const paused = !active || hidden || phase === 'waiting' && !next || phase === 'visible' && engaged;
|
|
3600
|
+
const duration = phase === 'waiting' ? shown === 0 ? SOCIAL_PROOF_FIRST_DELAY_MS : SOCIAL_PROOF_GAP_MS : phase === 'visible' ? SOCIAL_PROOF_VISIBLE_MS : SOCIAL_PROOF_EXIT_MS;
|
|
3601
|
+
const step = ()=>{
|
|
3602
|
+
if (phase === 'waiting' && next) {
|
|
3603
|
+
setProgress(next.kind === 'activity' ? {
|
|
3604
|
+
seenIds: [
|
|
3605
|
+
...seenIds,
|
|
3606
|
+
next.activity.id
|
|
3607
|
+
],
|
|
3608
|
+
countsShown,
|
|
3609
|
+
current: next
|
|
3610
|
+
} : {
|
|
3611
|
+
seenIds,
|
|
3612
|
+
countsShown: countsShown + 1,
|
|
3613
|
+
current: next
|
|
3614
|
+
});
|
|
3615
|
+
setPhase('visible');
|
|
3616
|
+
} else if (phase === 'visible') setPhase('leaving');
|
|
3617
|
+
else setPhase('waiting');
|
|
3618
|
+
};
|
|
3619
|
+
// Pausable timeout: hovering or a hidden tab keeps the time left of the current step.
|
|
3620
|
+
const stepRef = useRef(step);
|
|
3621
|
+
stepRef.current = step;
|
|
3622
|
+
const remaining = useRef(duration);
|
|
3623
|
+
const stepKey = `${shown}-${phase}`;
|
|
3624
|
+
const lastKey = useRef(null);
|
|
3625
|
+
useEffect(()=>{
|
|
3626
|
+
if (lastKey.current !== stepKey) {
|
|
3627
|
+
lastKey.current = stepKey;
|
|
3628
|
+
remaining.current = duration;
|
|
3629
|
+
}
|
|
3630
|
+
if (paused) return;
|
|
3631
|
+
const startedAt = Date.now();
|
|
3632
|
+
const timer = setTimeout(()=>stepRef.current(), remaining.current);
|
|
3633
|
+
return ()=>{
|
|
3634
|
+
clearTimeout(timer);
|
|
3635
|
+
remaining.current -= Date.now() - startedAt;
|
|
3636
|
+
};
|
|
3637
|
+
}, [
|
|
3638
|
+
stepKey,
|
|
3639
|
+
paused,
|
|
3640
|
+
duration
|
|
3641
|
+
]);
|
|
3642
|
+
const bumpName = offer.orderBumps.length === 1 ? offer.orderBumps[0]?.name : undefined;
|
|
3643
|
+
const balloon = active && phase !== 'waiting' && current ? current.kind === 'count' ? countBalloon(current.item, messages, bumpName, `count-${current.item.type}`) : activityBalloon(current.activity, messages, locale) : undefined;
|
|
3644
|
+
return {
|
|
3645
|
+
enabled: socialProof.enabled && !socialProof.stopped,
|
|
3646
|
+
balloon,
|
|
3647
|
+
leaving: phase === 'leaving',
|
|
3648
|
+
setEngaged,
|
|
3649
|
+
dismiss: socialProof.dismiss
|
|
3650
|
+
};
|
|
3651
|
+
}
|
|
2130
3652
|
|
|
2131
3653
|
|
|
2132
3654
|
|
|
@@ -2153,32 +3675,100 @@ const ELEMENTS_LOCALE = {
|
|
|
2153
3675
|
"data-cx-checkout": "offer-description",
|
|
2154
3676
|
children: item.description
|
|
2155
3677
|
}) : null,
|
|
2156
|
-
/*#__PURE__*/ jsx(Price, {})
|
|
3678
|
+
/*#__PURE__*/ jsx(Price, {}),
|
|
3679
|
+
/*#__PURE__*/ jsx(Recurrence, {})
|
|
2157
3680
|
]
|
|
2158
3681
|
});
|
|
2159
3682
|
}
|
|
2160
|
-
/**
|
|
3683
|
+
/**
|
|
3684
|
+
* Price of the offer, with the original price struck through when there is a discount. A
|
|
3685
|
+
* subscription carries its suffix ("/mês"); during a free trial the price today is zero. When the
|
|
3686
|
+
* seller highlights the installment, it leads and the cash price follows (`data-highlight`).
|
|
3687
|
+
*/ function Price({ className, children }) {
|
|
2161
3688
|
const item = useOfferItem();
|
|
3689
|
+
const format = useFormatMoney();
|
|
2162
3690
|
if (children) return children(item);
|
|
3691
|
+
const per = item.perFrequency;
|
|
3692
|
+
const installments = item.maxInstallment && item.maxInstallment.installment > 1 ? item.maxInstallment : undefined;
|
|
3693
|
+
if (item.freeTrialDays > 0) {
|
|
3694
|
+
return /*#__PURE__*/ jsx("div", {
|
|
3695
|
+
className: className,
|
|
3696
|
+
"data-cx-checkout": "price",
|
|
3697
|
+
"data-trial": "true",
|
|
3698
|
+
children: /*#__PURE__*/ jsx("strong", {
|
|
3699
|
+
"data-cx-checkout": "price-current",
|
|
3700
|
+
children: format(0)
|
|
3701
|
+
})
|
|
3702
|
+
});
|
|
3703
|
+
}
|
|
3704
|
+
const cash = /*#__PURE__*/ jsxs("strong", {
|
|
3705
|
+
"data-cx-checkout": "price-current",
|
|
3706
|
+
children: [
|
|
3707
|
+
item.formattedPrice,
|
|
3708
|
+
per
|
|
3709
|
+
]
|
|
3710
|
+
});
|
|
3711
|
+
const split = installments ? /*#__PURE__*/ jsxs("span", {
|
|
3712
|
+
"data-cx-checkout": "price-installments",
|
|
3713
|
+
children: [
|
|
3714
|
+
installments.installment,
|
|
3715
|
+
"x ",
|
|
3716
|
+
installments.formattedValue
|
|
3717
|
+
]
|
|
3718
|
+
}) : null;
|
|
3719
|
+
const highlight = Boolean(installments) && item.highlightInstallment;
|
|
2163
3720
|
return /*#__PURE__*/ jsxs("div", {
|
|
2164
3721
|
className: className,
|
|
2165
3722
|
"data-cx-checkout": "price",
|
|
3723
|
+
"data-highlight": highlight || undefined,
|
|
2166
3724
|
children: [
|
|
2167
|
-
item.hasDiscount ? /*#__PURE__*/
|
|
3725
|
+
item.hasDiscount ? /*#__PURE__*/ jsxs("s", {
|
|
2168
3726
|
"data-cx-checkout": "price-original",
|
|
2169
|
-
children:
|
|
3727
|
+
children: [
|
|
3728
|
+
item.formattedOriginalPrice,
|
|
3729
|
+
per
|
|
3730
|
+
]
|
|
2170
3731
|
}) : null,
|
|
2171
|
-
/*#__PURE__*/
|
|
2172
|
-
"data-cx-checkout": "price-current",
|
|
2173
|
-
children: item.formattedPrice
|
|
2174
|
-
}),
|
|
2175
|
-
item.maxInstallment && item.maxInstallment.installment > 1 ? /*#__PURE__*/ jsxs("span", {
|
|
2176
|
-
"data-cx-checkout": "price-installments",
|
|
3732
|
+
highlight ? /*#__PURE__*/ jsxs(Fragment, {
|
|
2177
3733
|
children: [
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
item.maxInstallment.formattedValue
|
|
3734
|
+
split,
|
|
3735
|
+
cash
|
|
2181
3736
|
]
|
|
3737
|
+
}) : /*#__PURE__*/ jsxs(Fragment, {
|
|
3738
|
+
children: [
|
|
3739
|
+
cash,
|
|
3740
|
+
split
|
|
3741
|
+
]
|
|
3742
|
+
})
|
|
3743
|
+
]
|
|
3744
|
+
});
|
|
3745
|
+
}
|
|
3746
|
+
/**
|
|
3747
|
+
* Subscription terms: the free trial with what is charged after it (following the selected
|
|
3748
|
+
* installment) and the charge limit. Renders nothing for one-time offers or a subscription with
|
|
3749
|
+
* neither.
|
|
3750
|
+
*/ function Recurrence({ className, children }) {
|
|
3751
|
+
const recurrence = useRecurrence();
|
|
3752
|
+
if (!recurrence) return null;
|
|
3753
|
+
if (children) return children(recurrence);
|
|
3754
|
+
if (!recurrence.trialText && !recurrence.chargeLimitText) return null;
|
|
3755
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
3756
|
+
className: className,
|
|
3757
|
+
"data-cx-checkout": "recurrence",
|
|
3758
|
+
children: [
|
|
3759
|
+
recurrence.trialText ? /*#__PURE__*/ jsxs("p", {
|
|
3760
|
+
"data-cx-checkout": "recurrence-trial",
|
|
3761
|
+
children: [
|
|
3762
|
+
/*#__PURE__*/ jsx("strong", {
|
|
3763
|
+
children: recurrence.trialText
|
|
3764
|
+
}),
|
|
3765
|
+
" ",
|
|
3766
|
+
recurrence.postTrialText
|
|
3767
|
+
]
|
|
3768
|
+
}) : null,
|
|
3769
|
+
recurrence.chargeLimitText ? /*#__PURE__*/ jsx("p", {
|
|
3770
|
+
"data-cx-checkout": "recurrence-charge-limit",
|
|
3771
|
+
children: recurrence.chargeLimitText
|
|
2182
3772
|
}) : null
|
|
2183
3773
|
]
|
|
2184
3774
|
});
|
|
@@ -2273,14 +3863,26 @@ function OrderBumpContent({ bump }) {
|
|
|
2273
3863
|
"data-cx-checkout": "order-bump-description",
|
|
2274
3864
|
children: bump.description
|
|
2275
3865
|
}) : null,
|
|
2276
|
-
/*#__PURE__*/
|
|
3866
|
+
bump.trial ? /*#__PURE__*/ jsxs(Fragment, {
|
|
3867
|
+
children: [
|
|
3868
|
+
/*#__PURE__*/ jsx("span", {
|
|
3869
|
+
"data-cx-checkout": "order-bump-price",
|
|
3870
|
+
"data-trial": "true",
|
|
3871
|
+
children: bump.trial.highlight
|
|
3872
|
+
}),
|
|
3873
|
+
/*#__PURE__*/ jsx("span", {
|
|
3874
|
+
"data-cx-checkout": "order-bump-trial-after",
|
|
3875
|
+
children: bump.trial.after
|
|
3876
|
+
})
|
|
3877
|
+
]
|
|
3878
|
+
}) : /*#__PURE__*/ jsx("span", {
|
|
2277
3879
|
"data-cx-checkout": "order-bump-price",
|
|
2278
3880
|
children: bump.formattedPrice
|
|
2279
3881
|
})
|
|
2280
3882
|
]
|
|
2281
3883
|
});
|
|
2282
3884
|
}
|
|
2283
|
-
function useFieldFactory(values, errors, setValue, meta) {
|
|
3885
|
+
function useFieldFactory(values, errors, setValue, meta, onBlur) {
|
|
2284
3886
|
const baseId = useId();
|
|
2285
3887
|
const result = {};
|
|
2286
3888
|
for (const key of Object.keys(meta)){
|
|
@@ -2297,7 +3899,10 @@ function useFieldFactory(values, errors, setValue, meta) {
|
|
|
2297
3899
|
'aria-invalid': Boolean(error),
|
|
2298
3900
|
'aria-describedby': error ? `${id}-error` : undefined,
|
|
2299
3901
|
autoComplete: meta[key].autoComplete,
|
|
2300
|
-
inputMode: meta[key].inputMode
|
|
3902
|
+
inputMode: meta[key].inputMode,
|
|
3903
|
+
...onBlur ? {
|
|
3904
|
+
onBlur
|
|
3905
|
+
} : {}
|
|
2301
3906
|
}
|
|
2302
3907
|
};
|
|
2303
3908
|
}
|
|
@@ -2353,8 +3958,8 @@ function DefaultField({ label, field }) {
|
|
|
2353
3958
|
});
|
|
2354
3959
|
}
|
|
2355
3960
|
/** Name, email, phone and document of the buyer. */ function PersonalDataFields({ className, labels, children }) {
|
|
2356
|
-
const { values, errors, setValue, isActive, oneClick } = usePersonalData();
|
|
2357
|
-
const fields = useFieldFactory(values, errors, setValue, PERSONAL_META);
|
|
3961
|
+
const { values, errors, setValue, isActive, oneClick, captureLead } = usePersonalData();
|
|
3962
|
+
const fields = useFieldFactory(values, errors, setValue, PERSONAL_META, captureLead);
|
|
2358
3963
|
const state = {
|
|
2359
3964
|
fields,
|
|
2360
3965
|
oneClick: !isActive && oneClick.data ? {
|
|
@@ -2452,11 +4057,12 @@ const ADDRESS_LABELS = {
|
|
|
2452
4057
|
* Address of the buyer. Renders nothing when the offer does not ask for one (and while a
|
|
2453
4058
|
* returning buyer buys with saved data). Physical offers quote freight from the zip code.
|
|
2454
4059
|
*/ function AddressFields({ className, labels, children }) {
|
|
2455
|
-
const { values, errors, setValue, required } = useAddress();
|
|
4060
|
+
const { values, errors, setValue, required, lookup } = useAddress();
|
|
2456
4061
|
const fields = useFieldFactory(values, errors, setValue, ADDRESS_META);
|
|
2457
4062
|
if (children) return children({
|
|
2458
4063
|
fields,
|
|
2459
|
-
required
|
|
4064
|
+
required,
|
|
4065
|
+
lookup
|
|
2460
4066
|
});
|
|
2461
4067
|
if (!required) return null;
|
|
2462
4068
|
const text = {
|
|
@@ -2466,6 +4072,8 @@ const ADDRESS_LABELS = {
|
|
|
2466
4072
|
return /*#__PURE__*/ jsx("div", {
|
|
2467
4073
|
className: className,
|
|
2468
4074
|
"data-cx-checkout": "address",
|
|
4075
|
+
"aria-busy": lookup.status === 'loading',
|
|
4076
|
+
"data-lookup": lookup.status,
|
|
2469
4077
|
children: [
|
|
2470
4078
|
'zipCode',
|
|
2471
4079
|
'street',
|
|
@@ -2696,11 +4304,14 @@ const METHOD_LABELS = {
|
|
|
2696
4304
|
]
|
|
2697
4305
|
});
|
|
2698
4306
|
}
|
|
2699
|
-
/**
|
|
4307
|
+
/**
|
|
4308
|
+
* Coupon input. Renders nothing when the offer does not accept coupons, except for a coupon the
|
|
4309
|
+
* offer applied on its own for the buyer's email, which still shows (and still counts).
|
|
4310
|
+
*/ function CouponField({ className, children }) {
|
|
2700
4311
|
const coupon = useCoupon();
|
|
2701
4312
|
const [draft, setDraft] = useState('');
|
|
2702
4313
|
if (children) return children(coupon);
|
|
2703
|
-
if (!coupon.enabled) return null;
|
|
4314
|
+
if (!coupon.enabled && coupon.source !== 'auto') return null;
|
|
2704
4315
|
if (coupon.code) {
|
|
2705
4316
|
return /*#__PURE__*/ jsxs("div", {
|
|
2706
4317
|
className: className,
|
|
@@ -2756,6 +4367,62 @@ const METHOD_LABELS = {
|
|
|
2756
4367
|
]
|
|
2757
4368
|
});
|
|
2758
4369
|
}
|
|
4370
|
+
/**
|
|
4371
|
+
* Social proof balloons ("12 people bought in the last 24 hours", "***dro B. R. bought"), one at
|
|
4372
|
+
* a time, with a close button that hides them for the visit. Renders nothing when the seller turned
|
|
4373
|
+
* social proof off or after the buyer closed it or sent the payment. Positioning is the page's:
|
|
4374
|
+
* the default markup is a live region (`data-cx-checkout="social-proof"`) to place where it fits.
|
|
4375
|
+
* Render it once per page.
|
|
4376
|
+
*/ function SocialProof({ className, children }) {
|
|
4377
|
+
const state = useSocialProof();
|
|
4378
|
+
const { messages } = useCheckout();
|
|
4379
|
+
if (!state.enabled) return null;
|
|
4380
|
+
if (children) return children(state);
|
|
4381
|
+
const { balloon } = state;
|
|
4382
|
+
// The region stays mounted (even empty) so screen readers announce each new balloon.
|
|
4383
|
+
return /*#__PURE__*/ jsx("div", {
|
|
4384
|
+
className: className,
|
|
4385
|
+
role: "status",
|
|
4386
|
+
"aria-live": "polite",
|
|
4387
|
+
"aria-label": messages.socialProofRegion,
|
|
4388
|
+
"data-cx-checkout": "social-proof",
|
|
4389
|
+
children: balloon ? // biome-ignore lint/a11y/noStaticElementInteractions: hover and focus only hold the balloon on screen; the close button is the only control
|
|
4390
|
+
/*#__PURE__*/ jsxs("div", {
|
|
4391
|
+
"data-cx-checkout": "social-proof-balloon",
|
|
4392
|
+
"data-kind": balloon.kind,
|
|
4393
|
+
"data-icon": balloon.icon,
|
|
4394
|
+
"data-leaving": state.leaving,
|
|
4395
|
+
onPointerEnter: ()=>state.setEngaged(true),
|
|
4396
|
+
onPointerLeave: ()=>state.setEngaged(false),
|
|
4397
|
+
onFocus: ()=>state.setEngaged(true),
|
|
4398
|
+
onBlur: (event)=>{
|
|
4399
|
+
if (!event.currentTarget.contains(event.relatedTarget)) state.setEngaged(false);
|
|
4400
|
+
},
|
|
4401
|
+
children: [
|
|
4402
|
+
/*#__PURE__*/ jsx("p", {
|
|
4403
|
+
"data-cx-checkout": "social-proof-text",
|
|
4404
|
+
children: balloon.parts.map((part, index)=>part.strong ? /*#__PURE__*/ jsx("strong", {
|
|
4405
|
+
children: part.text
|
|
4406
|
+
}, index) : part.text)
|
|
4407
|
+
}),
|
|
4408
|
+
balloon.time ? /*#__PURE__*/ jsxs("p", {
|
|
4409
|
+
"data-cx-checkout": "social-proof-meta",
|
|
4410
|
+
children: [
|
|
4411
|
+
balloon.place ? `${balloon.place} · ` : null,
|
|
4412
|
+
balloon.time
|
|
4413
|
+
]
|
|
4414
|
+
}) : null,
|
|
4415
|
+
/*#__PURE__*/ jsx("button", {
|
|
4416
|
+
type: "button",
|
|
4417
|
+
"aria-label": messages.socialProofClose,
|
|
4418
|
+
"data-cx-checkout": "social-proof-close",
|
|
4419
|
+
onClick: state.dismiss,
|
|
4420
|
+
children: "\xd7"
|
|
4421
|
+
})
|
|
4422
|
+
]
|
|
4423
|
+
}, balloon.id) : null
|
|
4424
|
+
});
|
|
4425
|
+
}
|
|
2759
4426
|
/** Submits the purchase with the selected method. */ function SubmitButton({ className, label = 'Finalizar compra', children }) {
|
|
2760
4427
|
const state = useSubmit();
|
|
2761
4428
|
if (children) return children(state);
|
|
@@ -2763,7 +4430,7 @@ const METHOD_LABELS = {
|
|
|
2763
4430
|
type: "button",
|
|
2764
4431
|
className: className,
|
|
2765
4432
|
"data-cx-checkout": "submit",
|
|
2766
|
-
disabled: state.isSubmitting,
|
|
4433
|
+
disabled: state.isSubmitting || Boolean(state.blocked),
|
|
2767
4434
|
"aria-busy": state.isSubmitting,
|
|
2768
4435
|
onClick: ()=>void state.submit(),
|
|
2769
4436
|
children: label
|
|
@@ -2784,9 +4451,53 @@ const METHOD_LABELS = {
|
|
|
2784
4451
|
children: state.message
|
|
2785
4452
|
});
|
|
2786
4453
|
}
|
|
4454
|
+
/**
|
|
4455
|
+
* Notices about the offer and the buyer: offer not for sale (with the seller's support email),
|
|
4456
|
+
* offer waiting for approval, email outside the offer's audience, free trial already used, and
|
|
4457
|
+
* the free account an affiliate-split purchase creates. Renders nothing when there is none.
|
|
4458
|
+
*
|
|
4459
|
+
* `unavailable` and `pendingApproval` come from the public offer and render on the server; the
|
|
4460
|
+
* others appear once the buyer's email is checked. The submit button stays disabled while the
|
|
4461
|
+
* offer is not for sale or the email is outside its audience.
|
|
4462
|
+
*/ function CheckoutNotices({ className, children }) {
|
|
4463
|
+
const { notices } = useCheckout();
|
|
4464
|
+
if (children) return children({
|
|
4465
|
+
notices
|
|
4466
|
+
});
|
|
4467
|
+
if (notices.length === 0) return null;
|
|
4468
|
+
return /*#__PURE__*/ jsx("div", {
|
|
4469
|
+
className: className,
|
|
4470
|
+
"data-cx-checkout": "notices",
|
|
4471
|
+
children: notices.map((notice)=>/*#__PURE__*/ jsxs("div", {
|
|
4472
|
+
role: notice.kind === 'unavailable' || notice.kind === 'offerIneligible' ? 'alert' : 'status',
|
|
4473
|
+
"data-cx-checkout": "notice",
|
|
4474
|
+
"data-kind": notice.kind,
|
|
4475
|
+
children: [
|
|
4476
|
+
notice.title ? /*#__PURE__*/ jsx("strong", {
|
|
4477
|
+
"data-cx-checkout": "notice-title",
|
|
4478
|
+
children: notice.title
|
|
4479
|
+
}) : null,
|
|
4480
|
+
/*#__PURE__*/ jsxs("p", {
|
|
4481
|
+
children: [
|
|
4482
|
+
notice.message,
|
|
4483
|
+
notice.supportEmail ? /*#__PURE__*/ jsxs(Fragment, {
|
|
4484
|
+
children: [
|
|
4485
|
+
': ',
|
|
4486
|
+
/*#__PURE__*/ jsx("a", {
|
|
4487
|
+
href: `mailto:${notice.supportEmail}`,
|
|
4488
|
+
children: notice.supportEmail
|
|
4489
|
+
})
|
|
4490
|
+
]
|
|
4491
|
+
}) : notice.title ? '.' : null
|
|
4492
|
+
]
|
|
4493
|
+
})
|
|
4494
|
+
]
|
|
4495
|
+
}, notice.kind))
|
|
4496
|
+
});
|
|
4497
|
+
}
|
|
2787
4498
|
/** Buys the one-time offer. A returning buyer with a saved card buys with one click. */ function UpsellAcceptButton({ className, label = 'Sim, quero aproveitar', children }) {
|
|
2788
4499
|
const upsell = useUpsell();
|
|
2789
|
-
const { isSubmitting } = useSubmit();
|
|
4500
|
+
const { isSubmitting, blocked } = useSubmit();
|
|
2790
4501
|
if (children) return children({
|
|
2791
4502
|
...upsell,
|
|
2792
4503
|
isSubmitting
|
|
@@ -2795,7 +4506,7 @@ const METHOD_LABELS = {
|
|
|
2795
4506
|
type: "button",
|
|
2796
4507
|
className: className,
|
|
2797
4508
|
"data-cx-checkout": "upsell-accept",
|
|
2798
|
-
disabled: isSubmitting,
|
|
4509
|
+
disabled: isSubmitting || Boolean(blocked),
|
|
2799
4510
|
"aria-busy": isSubmitting,
|
|
2800
4511
|
onClick: ()=>void upsell.accept(),
|
|
2801
4512
|
children: label
|
|
@@ -2825,4 +4536,5 @@ const METHOD_LABELS = {
|
|
|
2825
4536
|
|
|
2826
4537
|
|
|
2827
4538
|
|
|
2828
|
-
|
|
4539
|
+
|
|
4540
|
+
export { AddressFields, BoletoPayment, CardFields, CheckoutApiError, CheckoutError, CheckoutNotices, CheckoutProvider, ClickmaxElementsError, CountdownTimer, CouponField, DEFAULT_PAYMENTS_BASE_URL, FreightOptions, Installments, OfferItem, OrderBumps, OrderSummary, PaymentMethods, PersonalDataFields, PixPayment, Price, Recurrence, SocialProof, SubmitButton, UpsellAcceptButton, UpsellDeclineButton, createCheckoutApi, formatMoney, isValidDocument, parseTelephone, useAddress, useBoleto, useCheckout, useCountdown, useCoupon, useFormatMoney, useFreight, useOfferItem, useOrderBumps, usePayment, usePersonalData, usePix, useRecurrence, useSocialProof, useSubmit, useSummary, useUpsell, viaCepLookup };
|