@clickmax/checkout-react 12.5.15 → 12.5.17

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 CHANGED
@@ -118,9 +118,44 @@ The same state is available through hooks: `useOfferItem`, `useOrderBumps`, `use
118
118
  |`onBoletoGenerated`|A boleto was issued.|
119
119
  |`onUpsellAccepted`|The one-time offer was bought.|
120
120
  |`onUpsellDeclined`|The buyer declined the one-time offer (`downsellUrl`).|
121
+ |`onPixelEvent`|An offer pixel should fire in the browser (see below).|
121
122
 
122
123
  Callbacks never block the flow. Redirects are up to you.
123
124
 
125
+ ## Leads and pixels
126
+
127
+ The checkout records the buyer as a lead once the email is valid and a personal data field loses focus, and records the payment step when the buyer picks a method or focuses the card. Both start cart abandonment. The field props of `PersonalDataFields` already call `captureLead`; with fully custom inputs, call `usePersonalData().captureLead()` on blur. Pass `location.visitorId` and `location.sessionId` from your analytics so abandonment links to the visit.
128
+
129
+ Offer pixels (Meta, Google Ads) go two ways with the same event id, so the platform counts each event once:
130
+
131
+ - In the browser, by you: the package does not load `fbq` or `gtag`. `onPixelEvent` gives the event (`pageView`, `initiateCheckout`, `addPaymentInfo`, `purchase`), the pixels set to track it, and the `eventId` each one must send.
132
+ - To the conversions API, by the package: `initiateCheckout` and `addPaymentInfo`, with the buyer data typed so far. Purchases reach it from the server.
133
+
134
+ ```tsx
135
+ const META_EVENTS = {
136
+ pageView: 'PageView',
137
+ initiateCheckout: 'InitiateCheckout',
138
+ addPaymentInfo: 'AddPaymentInfo',
139
+ purchase: 'Purchase',
140
+ }
141
+
142
+ <CheckoutProvider
143
+ offer={offer}
144
+ location={{ visitorId, sessionId }}
145
+ onPixelEvent={({ name, pixels, amountCents, currency }) => {
146
+ for (const { pixel, eventId } of pixels) {
147
+ if (pixel.service === 'facebook') {
148
+ window.fbq?.('trackSingle', pixel.serviceId, META_EVENTS[name], {
149
+ ...(amountCents !== undefined ? { value: amountCents / 100, currency } : {}),
150
+ }, { eventID: eventId })
151
+ }
152
+ }
153
+ }}
154
+ >
155
+ ```
156
+
157
+ Events wait for the visitor route, whose session id builds the ids. `initiateCheckout` fires on load, or once name, email and phone are filled when the pixel asks for it (`afterPersonalData`). `addPaymentInfo` fires once, when the buyer picks a method, focuses the card, or the checkout opens on pix or boleto.
158
+
124
159
  ## One-time offers (upsell and downsell)
125
160
 
126
161
  For an offer with `isOTO`, render `UpsellAcceptButton` and `UpsellDeclineButton`. A page with no Clickmax page configuration declares the kind of page with `getPublicOffer({ offer, mode: 'upsell' })` (or `'downsell'`), which sets `isOTO`. The declaration only changes the interface: buying without card data still needs the previous purchase in the same browser. A returning buyer with a saved card buys with one click; otherwise render the buyer form and `CardFields` as in a regular checkout.
package/dist/index.d.ts CHANGED
@@ -221,6 +221,21 @@ export declare interface CheckoutApi {
221
221
  getPurchaseStatus(jobId: string, options?: CheckoutCallOptions): Promise<PurchaseStatus>;
222
222
  /** Purchase details, used to learn when a pix was paid. */
223
223
  getPurchaseDetails(transactionId: string, options?: CheckoutCallOptions): Promise<CheckoutDetails>;
224
+ /**
225
+ * Records the buyer as a lead before the purchase, which starts cart abandonment. Browser only
226
+ * (uses cookies). Send `funnelCreatedLead: true` after the first capture of the visit.
227
+ */
228
+ trackLead(body: CheckoutLeadRequest, options?: CheckoutCallOptions): Promise<void>;
229
+ /** Records the payment step (method picked, card touched) for cart abandonment. Browser only. */
230
+ trackInteraction(body: CheckoutInteractionRequest, options?: CheckoutCallOptions): Promise<void>;
231
+ /**
232
+ * Sends a pixel event to the ad platform's conversions API, with the event id the browser pixel
233
+ * used. `dispatched` is `false` when no pixel of the offer takes it.
234
+ */
235
+ dispatchPixelEvent(body: CheckoutPixelDispatchRequest, options?: CheckoutCallOptions): Promise<{
236
+ dispatched: boolean;
237
+ reason?: string;
238
+ }>;
224
239
  }
225
240
 
226
241
  /** A non-2xx answer or a network failure of a checkout API call. */
@@ -255,6 +270,12 @@ export declare interface CheckoutCallbacks {
255
270
  onUpsellDeclined?: (event: {
256
271
  downsellUrl: string | undefined;
257
272
  }) => void;
273
+ /**
274
+ * An offer pixel should fire in the browser. The package does not load `fbq` or `gtag`: the host
275
+ * fires each pixel with the `eventId` given. Called only when some offer pixel tracks the event,
276
+ * once per event per mount (every approved purchase for `purchase`).
277
+ */
278
+ onPixelEvent?: (event: CheckoutPixelEvent) => void;
258
279
  }
259
280
 
260
281
  /** Per-call options of every {@link CheckoutApi} method. */
@@ -293,6 +314,11 @@ export declare interface CheckoutContextValue {
293
314
  validate: () => boolean;
294
315
  /** Whether the purchase sends typed data (`false` while buying with saved one-click data). */
295
316
  isActive: boolean;
317
+ /**
318
+ * Records the buyer as a lead (cart abandonment) once the email is valid. Call it when a field
319
+ * loses focus; the field props of `PersonalDataFields` already do. Bursts are grouped.
320
+ */
321
+ captureLead: () => void;
296
322
  };
297
323
  address: {
298
324
  values: AddressValues;
@@ -350,6 +376,11 @@ export declare interface CheckoutContextValue {
350
376
  /** Registered by `CardFields`; `undefined` until the iframe mounts. */
351
377
  card: CardElement | undefined;
352
378
  registerCard: (card: CardElement | undefined) => void;
379
+ /**
380
+ * The buyer started typing the card: records the payment step and the `addPaymentInfo` pixel
381
+ * event. `CardFields` calls it on focus; call it yourself only with your own card iframe.
382
+ */
383
+ cardInteracted: () => void;
353
384
  };
354
385
  submission: SubmissionState;
355
386
  submit: (options?: SubmitOptions) => Promise<SubmitOutcome>;
@@ -395,6 +426,12 @@ export declare interface CheckoutErrorProps {
395
426
  }>;
396
427
  }
397
428
 
429
+ /** Body of the payment interaction record. */
430
+ export declare type CheckoutInteractionRequest = TrackCheckoutInteractionBody;
431
+
432
+ /** Body of the lead capture. */
433
+ export declare type CheckoutLeadRequest = TrackCheckoutLeadsBody;
434
+
398
435
  /** Locale of texts and number formatting. */
399
436
  export declare type CheckoutLocale = 'pt-BR' | 'en' | 'es';
400
437
 
@@ -413,6 +450,13 @@ export declare interface CheckoutLocation {
413
450
  couponCode?: string;
414
451
  /** Where "decline" in a one-time offer sends the buyer. */
415
452
  downsellUrl?: string;
453
+ /**
454
+ * Visitor id of the site's own analytics (the `cm.v` key of the Clickmax runtime). Goes with the
455
+ * lead and the payment interaction, so cart abandonment links them to the visit.
456
+ */
457
+ visitorId?: string;
458
+ /** Session id of the site's own analytics (the `cm.s` key of the Clickmax runtime). */
459
+ sessionId?: string;
416
460
  /** Values to prefill the personal data form with. */
417
461
  prefill?: Partial<PersonalDataValues>;
418
462
  tracking?: CheckoutTracking;
@@ -441,6 +485,38 @@ export declare interface CheckoutMessages extends ValidationMessages {
441
485
  /** One pixel configured on the offer. */
442
486
  export declare type CheckoutPixel = GetPublicOfferCheckout2xx['pixels'][number];
443
487
 
488
+ /** Body of a pixel event sent to the conversions API. */
489
+ export declare type CheckoutPixelDispatchRequest = DispatchCheckoutPixelEventBody;
490
+
491
+ /** Payload of `onPixelEvent`. */
492
+ export declare interface CheckoutPixelEvent {
493
+ name: CheckoutPixelEventName;
494
+ /** Offer pixels set to track this event. Never empty. */
495
+ pixels: CheckoutPixelTarget[];
496
+ /** Set on `addPaymentInfo` and `purchase`. */
497
+ paymentMethod?: PaymentMethod;
498
+ /** Set on `purchase`, in cents. */
499
+ amountCents?: number;
500
+ currency?: 'BRL';
501
+ /** Set on `purchase`. */
502
+ transactionId?: string;
503
+ }
504
+
505
+ /** Pixel events the checkout reports, named as in the offer's pixel settings. */
506
+ export declare type CheckoutPixelEventName = 'pageView' | 'initiateCheckout' | 'addPaymentInfo' | 'purchase';
507
+
508
+ /** One offer pixel that tracks an event, with the id the browser pixel must send. */
509
+ export declare interface CheckoutPixelTarget {
510
+ pixel: CheckoutPixel;
511
+ /**
512
+ * Event id for the browser pixel (`eventID` in `fbq`, `transaction_id` in `gtag`). The
513
+ * conversions API gets the same id, which is how the platform drops the duplicate.
514
+ */
515
+ eventId: string;
516
+ /** Conversion label the seller set for this event (Google Ads), when any. */
517
+ label: string | undefined;
518
+ }
519
+
444
520
  /** Server-computed prices, installments and coupon result for the current selection. */
445
521
  export declare type CheckoutPricing = GetCheckoutPricing2xx;
446
522
 
@@ -613,6 +689,80 @@ export declare const DEFAULT_PAYMENTS_BASE_URL = "/__clickmax/payments";
613
689
 
614
690
  declare type DiscountTypeSchema = 'percentage' | 'fixed';
615
691
 
692
+ declare type DispatchCheckoutPixelEventBody = {
693
+ offerHash: string;
694
+ canonicalEvent: DispatchCheckoutPixelEventBodyCanonicalEvent;
695
+ eventId: string;
696
+ buyer?: DispatchCheckoutPixelEventBodyBuyer;
697
+ /** @minimum 0 */
698
+ amountCents?: number;
699
+ currency?: DispatchCheckoutPixelEventBodyCurrency;
700
+ /** @maxLength 255 */
701
+ clientFbp?: string;
702
+ /** @maxLength 255 */
703
+ clientFbc?: string;
704
+ /**
705
+ * @maxLength 2048
706
+ * @pattern ^https?://
707
+ */
708
+ eventSourceUrl?: string;
709
+ };
710
+
711
+ declare type DispatchCheckoutPixelEventBodyBuyer = {
712
+ /**
713
+ * @minLength 5
714
+ * @maxLength 255
715
+ */
716
+ email?: string;
717
+ name?: string;
718
+ document?: string;
719
+ telephone?: DispatchCheckoutPixelEventBodyBuyerTelephone;
720
+ address?: DispatchCheckoutPixelEventBodyBuyerAddress;
721
+ };
722
+
723
+ declare type DispatchCheckoutPixelEventBodyBuyerAddress = {
724
+ /** @nullable */
725
+ street?: string | null;
726
+ /** @nullable */
727
+ number?: string | null;
728
+ /** @nullable */
729
+ complement?: string | null;
730
+ /** @nullable */
731
+ neighborhood?: string | null;
732
+ /** @nullable */
733
+ city?: string | null;
734
+ /**
735
+ * @maxLength 100
736
+ * @nullable
737
+ */
738
+ state?: string | null;
739
+ /**
740
+ * @minLength 2
741
+ * @maxLength 2
742
+ * @nullable
743
+ * @pattern ^[A-Z]{2}$
744
+ */
745
+ country?: string | null;
746
+ /**
747
+ * @minLength 3
748
+ * @maxLength 12
749
+ * @nullable
750
+ */
751
+ zipCode?: string | null;
752
+ /** @nullable */
753
+ referencePoint?: string | null;
754
+ };
755
+
756
+ declare type DispatchCheckoutPixelEventBodyBuyerTelephone = {
757
+ countryCode: string;
758
+ areaCode: string;
759
+ number: string;
760
+ };
761
+
762
+ declare type DispatchCheckoutPixelEventBodyCanonicalEvent = 'initiateCheckout' | 'addPaymentInfo';
763
+
764
+ declare type DispatchCheckoutPixelEventBodyCurrency = 'BRL' | 'USD' | 'EUR';
765
+
616
766
  export declare type ElementsAppearance = {
617
767
  variables?: ElementsAppearanceVariables;
618
768
  /** Só folhas do Google Fonts, que é o que a CSP do payments libera. */
@@ -677,6 +827,8 @@ export declare interface FieldProps {
677
827
  'aria-describedby': string | undefined;
678
828
  autoComplete: string;
679
829
  inputMode?: 'text' | 'email' | 'tel' | 'numeric';
830
+ /** Set on personal data fields: leaving one records the buyer as a lead. */
831
+ onBlur?: () => void;
680
832
  }
681
833
 
682
834
  /** One field: input props, label-friendly id and error. */
@@ -971,6 +1123,8 @@ declare type GetPublicOfferCheckout2xx = {
971
1123
  socialProof?: GetPublicOfferCheckout2xxSocialProof;
972
1124
  /** @nullable */
973
1125
  checkoutPlugins?: GetPublicOfferCheckout2xxCheckoutPlugins;
1126
+ /** @nullable */
1127
+ combo?: GetPublicOfferCheckout2xxCombo;
974
1128
  /**
975
1129
  * @maxLength 1000
976
1130
  * @nullable
@@ -1026,6 +1180,7 @@ declare type GetPublicOfferCheckout2xxCheckoutPlugins = {
1026
1180
  reviews?: GetPublicOfferCheckout2xxCheckoutPluginsReviews;
1027
1181
  video?: GetPublicOfferCheckout2xxCheckoutPluginsVideo;
1028
1182
  chat?: GetPublicOfferCheckout2xxCheckoutPluginsChat;
1183
+ combo?: GetPublicOfferCheckout2xxCheckoutPluginsCombo;
1029
1184
  } | null;
1030
1185
 
1031
1186
  declare type GetPublicOfferCheckout2xxCheckoutPluginsChat = {
@@ -1033,6 +1188,17 @@ declare type GetPublicOfferCheckout2xxCheckoutPluginsChat = {
1033
1188
  channelId?: string;
1034
1189
  };
1035
1190
 
1191
+ declare type GetPublicOfferCheckout2xxCheckoutPluginsCombo = {
1192
+ enabled: boolean;
1193
+ /**
1194
+ * @minItems 1
1195
+ * @maxItems 5
1196
+ */
1197
+ offerIds: string[];
1198
+ /** @minimum 1 */
1199
+ price: number;
1200
+ };
1201
+
1036
1202
  declare type GetPublicOfferCheckout2xxCheckoutPluginsDiscountPopup = {
1037
1203
  enabled: boolean;
1038
1204
  /**
@@ -1090,6 +1256,24 @@ declare type GetPublicOfferCheckout2xxCheckoutPluginsWhatsapp = {
1090
1256
  message: string;
1091
1257
  };
1092
1258
 
1259
+ /**
1260
+ * @nullable
1261
+ */
1262
+ declare type GetPublicOfferCheckout2xxCombo = {
1263
+ /** @minimum 1 */
1264
+ price: number;
1265
+ items: GetPublicOfferCheckout2xxComboItemsItem[];
1266
+ } | null;
1267
+
1268
+ declare type GetPublicOfferCheckout2xxComboItemsItem = {
1269
+ id: string;
1270
+ /** @maxLength 1000 */
1271
+ name: string;
1272
+ /** @minimum 1 */
1273
+ effectivePrice: number;
1274
+ thumbnail: string;
1275
+ };
1276
+
1093
1277
  declare type GetPublicOfferCheckout2xxConfigs = {
1094
1278
  opt: GetPublicOfferCheckout2xxConfigsOpt;
1095
1279
  oto?: GetPublicOfferCheckout2xxConfigsOto;
@@ -1665,7 +1849,7 @@ declare type GetPublicOfferCheckout2xxMethods = {
1665
1849
  maxCharges?: number | null;
1666
1850
  };
1667
1851
  credit: {
1668
- active: true;
1852
+ active: boolean;
1669
1853
  installments: {
1670
1854
  /**
1671
1855
  * @minimum 1
@@ -1999,6 +2183,7 @@ declare type OfferCheckoutBody = ({
1999
2183
  linkCheckout: string;
2000
2184
  recaptcha: string;
2001
2185
  couponCode?: string;
2186
+ combo?: boolean;
2002
2187
  freightMethod?: TransactionFreightMethod;
2003
2188
  isForeign?: boolean;
2004
2189
  language?: LanguageSchema;
@@ -2385,6 +2570,42 @@ declare type TokenizeResult = {
2385
2570
  brand: CardBrand;
2386
2571
  };
2387
2572
 
2573
+ declare type TrackCheckoutInteractionBody = {
2574
+ hash: string;
2575
+ selectedPaymentMethod?: TrackCheckoutInteractionBodySelectedPaymentMethod;
2576
+ cardInteracted?: boolean;
2577
+ visitorId?: string;
2578
+ };
2579
+
2580
+ declare type TrackCheckoutInteractionBodySelectedPaymentMethod = 'credit' | 'pix' | 'boleto';
2581
+
2582
+ declare type TrackCheckoutLeadsBody = {
2583
+ hash: string;
2584
+ /**
2585
+ * @minLength 5
2586
+ * @maxLength 255
2587
+ */
2588
+ email: string;
2589
+ fullName?: string;
2590
+ telephone?: string;
2591
+ document?: string;
2592
+ affiliateHash?: string;
2593
+ funnelCreatedLead: boolean;
2594
+ visitorId?: string;
2595
+ sessionId?: string;
2596
+ utmSource?: string;
2597
+ utmMedium?: string;
2598
+ utmCampaign?: string;
2599
+ utmTerm?: string;
2600
+ utmContent?: string;
2601
+ extraParams?: TrackingExtraParamsSchema;
2602
+ src?: string;
2603
+ sck?: string;
2604
+ pageId?: string;
2605
+ referrer?: string;
2606
+ landingUrl?: string;
2607
+ };
2608
+
2388
2609
  declare type TrackingExtraParamsSchema = {
2389
2610
  vkSource?: string;
2390
2611
  vkAdId?: string;
package/dist/index.js CHANGED
@@ -164,6 +164,84 @@ const getCheckoutDetails = async (id, options)=>{
164
164
  method: 'GET'
165
165
  });
166
166
  };
167
+ const getTrackCheckoutLeadsUrl = ()=>{
168
+ return `/checkout/offer/track`;
169
+ };
170
+ const trackCheckoutLeads = async (trackCheckoutLeadsBody, options)=>{
171
+ const getHeaders = (h)=>{
172
+ if (!h) return {};
173
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
174
+ if (Symbol.iterator in h) {
175
+ return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
176
+ }
177
+ const headers = {};
178
+ for (const [name, value] of Object.entries(h)){
179
+ if (value !== undefined) headers[name] = value;
180
+ }
181
+ return headers;
182
+ };
183
+ return http(getTrackCheckoutLeadsUrl(), {
184
+ ...options,
185
+ method: 'POST',
186
+ headers: {
187
+ 'Content-Type': 'application/json',
188
+ ...getHeaders(options?.headers)
189
+ },
190
+ body: JSON.stringify(trackCheckoutLeadsBody)
191
+ });
192
+ };
193
+ const getTrackCheckoutInteractionUrl = ()=>{
194
+ return `/checkout/offer/track-interaction`;
195
+ };
196
+ const trackCheckoutInteraction = async (trackCheckoutInteractionBody, options)=>{
197
+ const getHeaders = (h)=>{
198
+ if (!h) return {};
199
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
200
+ if (Symbol.iterator in h) {
201
+ return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
202
+ }
203
+ const headers = {};
204
+ for (const [name, value] of Object.entries(h)){
205
+ if (value !== undefined) headers[name] = value;
206
+ }
207
+ return headers;
208
+ };
209
+ return http(getTrackCheckoutInteractionUrl(), {
210
+ ...options,
211
+ method: 'POST',
212
+ headers: {
213
+ 'Content-Type': 'application/json',
214
+ ...getHeaders(options?.headers)
215
+ },
216
+ body: JSON.stringify(trackCheckoutInteractionBody)
217
+ });
218
+ };
219
+ const getDispatchCheckoutPixelEventUrl = ()=>{
220
+ return `/checkout/pixels/dispatch`;
221
+ };
222
+ const dispatchCheckoutPixelEvent = async (dispatchCheckoutPixelEventBody, options)=>{
223
+ const getHeaders = (h)=>{
224
+ if (!h) return {};
225
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
226
+ if (Symbol.iterator in h) {
227
+ return Object.fromEntries(Array.from(h, (entry)=>Array.from(entry)));
228
+ }
229
+ const headers = {};
230
+ for (const [name, value] of Object.entries(h)){
231
+ if (value !== undefined) headers[name] = value;
232
+ }
233
+ return headers;
234
+ };
235
+ return http(getDispatchCheckoutPixelEventUrl(), {
236
+ ...options,
237
+ method: 'POST',
238
+ headers: {
239
+ 'Content-Type': 'application/json',
240
+ ...getHeaders(options?.headers)
241
+ },
242
+ body: JSON.stringify(dispatchCheckoutPixelEventBody)
243
+ });
244
+ };
167
245
  const getValidateCheckoutCouponUrl = ()=>{
168
246
  return `/checkout/coupon/validate`;
169
247
  };
@@ -275,7 +353,14 @@ function publicOfferQuery({ bumps, bumpTitle, mode, ...rest }) {
275
353
  }
276
354
  }),
277
355
  getPurchaseStatus: (jobId, options)=>getCheckoutStatus(jobId, call(options)),
278
- getPurchaseDetails: (transactionId, options)=>getCheckoutDetails(transactionId, call(options))
356
+ getPurchaseDetails: (transactionId, options)=>getCheckoutDetails(transactionId, call(options)),
357
+ trackLead: async (body, options)=>{
358
+ await trackCheckoutLeads(body, call(options));
359
+ },
360
+ trackInteraction: async (body, options)=>{
361
+ await trackCheckoutInteraction(body, call(options));
362
+ },
363
+ dispatchPixelEvent: (body, options)=>dispatchCheckoutPixelEvent(body, call(options))
279
364
  };
280
365
  }
281
366
 
@@ -1189,6 +1274,331 @@ async function waitForJob(state, jobId) {
1189
1274
 
1190
1275
 
1191
1276
 
1277
+ /**
1278
+ * Groups the blurs of the personal data fields. Tabbing through five fields would otherwise send
1279
+ * five lead captures, each one publishing CRM events on the server.
1280
+ */ const LEAD_WAIT_MS = 800;
1281
+ const tracking_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1282
+ const tracking_FULL_NAME = /^[A-Za-zÀ-ÖØ-öø-ÿ]+(?:\s+[A-Za-zÀ-ÖØ-öø-ÿ]+)+\s*$/;
1283
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1284
+ function tracking_pageUrl(location) {
1285
+ if (location.pageUrl) return location.pageUrl;
1286
+ return typeof window === 'undefined' ? '' : window.location.href;
1287
+ }
1288
+ function readCookie(name) {
1289
+ if (typeof document === 'undefined') return undefined;
1290
+ const prefix = `${name}=`;
1291
+ return document.cookie.split(/;\s*/).find((part)=>part.startsWith(prefix))?.slice(prefix.length);
1292
+ }
1293
+ /**
1294
+ * Personal data good enough for ad platform matching: a valid email, first and last name and a
1295
+ * phone with at least 8 digits. Not the form validation: the document is optional here, so a
1296
+ * foreign buyer still counts.
1297
+ */ function isBuyerReady(values) {
1298
+ return tracking_EMAIL.test(values.email.trim()) && tracking_FULL_NAME.test(values.name.trim()) && onlyDigits(values.phone).length >= 8;
1299
+ }
1300
+ function buyerSnapshot(input) {
1301
+ const { personalDataActive, personalData, oneClick, address } = input;
1302
+ if (!personalDataActive && oneClick) {
1303
+ return {
1304
+ email: oneClick.email,
1305
+ name: oneClick.name,
1306
+ document: oneClick.document ?? undefined,
1307
+ telephone: oneClick.telephone
1308
+ };
1309
+ }
1310
+ const email = personalData.email.trim().toLowerCase();
1311
+ const document1 = onlyDigits(personalData.document);
1312
+ const buyer = {
1313
+ email: tracking_EMAIL.test(email) ? email : undefined,
1314
+ name: personalData.name.trim() || undefined,
1315
+ document: document1 && isValidDocument(document1) ? document1 : undefined,
1316
+ telephone: parseTelephone(personalData.phone)
1317
+ };
1318
+ if (address) {
1319
+ buyer.address = {
1320
+ zipCode: address.zipCode.trim() || undefined,
1321
+ street: address.street.trim() || undefined,
1322
+ number: address.number.trim() || undefined,
1323
+ complement: address.complement.trim() || undefined,
1324
+ neighborhood: address.neighborhood.trim() || undefined,
1325
+ city: address.city.trim() || undefined,
1326
+ state: address.state.trim().toUpperCase() || undefined,
1327
+ country: /^[A-Za-z]{2}$/.test(address.country) ? address.country.toUpperCase() : undefined
1328
+ };
1329
+ }
1330
+ return Object.values(buyer).some((value)=>value !== undefined) ? buyer : undefined;
1331
+ }
1332
+ /**
1333
+ * Lead capture, payment interaction and pixel events of the checkout, the same signals the
1334
+ * standard checkout sends: the lead and interaction feed cart abandonment, the pixel events feed
1335
+ * Meta and Google Ads.
1336
+ *
1337
+ * Each pixel event goes two ways with the same event id, so the ad platform keeps one: the host
1338
+ * fires the browser pixel from `onPixelEvent` (loading `fbq`/`gtag` is the host's call), and the
1339
+ * package sends `initiateCheckout` and `addPaymentInfo` to the conversions API. Purchase reaches
1340
+ * the conversions API from the server on its own.
1341
+ *
1342
+ * Every effect waits for the visitor route: the event ids the server deduplicates against are
1343
+ * built from the visitor's session, and firing before them would count each event twice.
1344
+ */ function useCheckoutTracking(input) {
1345
+ const inputRef = useRef(input);
1346
+ inputRef.current = input;
1347
+ const fired = useRef(new Set()).current;
1348
+ const emit = useCallback((name, targets, extra = {})=>{
1349
+ if (targets.length === 0) return;
1350
+ try {
1351
+ inputRef.current.callbacks.onPixelEvent?.({
1352
+ name,
1353
+ pixels: targets,
1354
+ ...extra
1355
+ });
1356
+ } catch (error) {
1357
+ // A broken host handler must not take the checkout down with it.
1358
+ console.error('[clickmax-checkout] onPixelEvent threw', {
1359
+ op: 'onPixelEvent',
1360
+ name,
1361
+ error
1362
+ });
1363
+ }
1364
+ }, []);
1365
+ /** Sends a canonical event to the conversions API, best effort, for pixels with a session id. */ const dispatch = useCallback((canonicalEvent, targets)=>{
1366
+ const current = inputRef.current;
1367
+ const url = tracking_pageUrl(current.location);
1368
+ const tracking = current.location.tracking;
1369
+ const clientFbp = tracking?.clientFbp ?? readCookie('_fbp');
1370
+ const clientFbc = tracking?.clientFbc ?? readCookie('_fbc');
1371
+ const buyer = buyerSnapshot(current);
1372
+ for (const { pixel, eventId } of targets){
1373
+ if (pixel.eventIds?.[canonicalEvent] !== eventId) continue;
1374
+ void current.api.dispatchPixelEvent({
1375
+ offerHash: current.offer.hash,
1376
+ canonicalEvent,
1377
+ eventId,
1378
+ ...buyer ? {
1379
+ buyer
1380
+ } : {},
1381
+ ...clientFbp ? {
1382
+ clientFbp
1383
+ } : {},
1384
+ ...clientFbc ? {
1385
+ clientFbc
1386
+ } : {},
1387
+ // Over the schema limit the event goes without its URL; a 400 would lose all of it.
1388
+ .../^https?:\/\//.test(url) && url.length <= 2048 ? {
1389
+ eventSourceUrl: url
1390
+ } : {}
1391
+ }).catch(()=>{
1392
+ // The browser pixel already went out through the host; nothing to recover here.
1393
+ });
1394
+ }
1395
+ }, []);
1396
+ const targets = useCallback((name, filter, sourceId)=>inputRef.current.pixels.filter(filter).map((pixel)=>({
1397
+ pixel,
1398
+ eventId: (name === 'initiateCheckout' || name === 'addPaymentInfo' ? pixel.eventIds?.[name] : undefined) ?? `${name}-${sourceId}-${pixel.serviceId}`,
1399
+ label: pixel.eventLabels?.[name]
1400
+ })), []);
1401
+ const fireOnce = useCallback((key, name, filter, extra)=>{
1402
+ if (fired.has(key)) return;
1403
+ const matching = targets(name, filter, String(Date.now()));
1404
+ if (matching.length === 0) return;
1405
+ fired.add(key);
1406
+ emit(name, matching, extra);
1407
+ dispatch(name, matching);
1408
+ }, [
1409
+ fired,
1410
+ targets,
1411
+ emit,
1412
+ dispatch
1413
+ ]);
1414
+ // A method picked before the visitor answers waits for it: fired now, the event would carry a
1415
+ // fallback id the conversions API cannot match, and it fires only once.
1416
+ const pendingPaymentInfo = useRef(undefined);
1417
+ const addPaymentInfo = useCallback((method)=>{
1418
+ if (!inputRef.current.visitorSettled) {
1419
+ pendingPaymentInfo.current = method;
1420
+ return;
1421
+ }
1422
+ fireOnce('addPaymentInfo', 'addPaymentInfo', (pixel)=>pixel.eventsConfig.addPaymentInfo?.enabled === true, {
1423
+ paymentMethod: method
1424
+ });
1425
+ }, [
1426
+ fireOnce
1427
+ ]);
1428
+ const { visitorSettled, method } = input;
1429
+ // Page view and the initiate checkout that does not wait for the buyer's data.
1430
+ useEffect(()=>{
1431
+ if (!visitorSettled || fired.has('mount')) return;
1432
+ fired.add('mount');
1433
+ emit('pageView', targets('pageView', (pixel)=>pixel.eventsConfig.pageView?.enabled === true, String(Date.now())));
1434
+ fireOnce('initiateCheckout', 'initiateCheckout', (pixel)=>pixel.eventsConfig.initiateCheckout?.enabled === true && pixel.eventsConfig.initiateCheckout.afterPersonalData !== true);
1435
+ }, [
1436
+ visitorSettled,
1437
+ fired,
1438
+ emit,
1439
+ targets,
1440
+ fireOnce
1441
+ ]);
1442
+ // Initiate checkout of pixels set to wait for the buyer's data, so it carries email and phone.
1443
+ const buyerReady = input.personalDataActive ? isBuyerReady(input.personalData) : Boolean(input.oneClick);
1444
+ useEffect(()=>{
1445
+ if (!visitorSettled || !buyerReady) return;
1446
+ fireOnce('initiateCheckoutAfterData', 'initiateCheckout', (pixel)=>pixel.eventsConfig.initiateCheckout?.enabled === true && pixel.eventsConfig.initiateCheckout.afterPersonalData === true);
1447
+ }, [
1448
+ visitorSettled,
1449
+ buyerReady,
1450
+ fireOnce
1451
+ ]);
1452
+ // A pix or boleto picked up front (single method, or the method of the buyer's last purchase)
1453
+ // is already the payment info. Card waits for the buyer to focus the card fields.
1454
+ useEffect(()=>{
1455
+ if (!visitorSettled) return;
1456
+ const pending = pendingPaymentInfo.current;
1457
+ pendingPaymentInfo.current = undefined;
1458
+ if (pending) addPaymentInfo(pending);
1459
+ else if (method && method !== 'credit') addPaymentInfo(method);
1460
+ }, [
1461
+ visitorSettled,
1462
+ method,
1463
+ addPaymentInfo
1464
+ ]);
1465
+ const interaction = useCallback((body)=>{
1466
+ const current = inputRef.current;
1467
+ void current.api.trackInteraction({
1468
+ hash: current.offer.hash,
1469
+ ...body,
1470
+ ...current.location.visitorId ? {
1471
+ visitorId: current.location.visitorId
1472
+ } : {}
1473
+ }).catch(()=>{});
1474
+ }, []);
1475
+ // region Lead
1476
+ const createdLead = useRef(false);
1477
+ const lastLead = useRef(null);
1478
+ const leadTimer = useRef(null);
1479
+ const pendingLead = useRef(false);
1480
+ // One capture at a time: `funnelCreatedLead` flips only after the first answer, so two captures
1481
+ // in flight would both create the lead. A capture asked meanwhile goes when the first returns.
1482
+ const leadInFlight = useRef(false);
1483
+ const leadQueued = useRef(false);
1484
+ const sendLead = useCallback(function send() {
1485
+ if (leadInFlight.current) {
1486
+ leadQueued.current = true;
1487
+ return;
1488
+ }
1489
+ const current = inputRef.current;
1490
+ if (!current.personalDataActive) return;
1491
+ const { personalData, location, offer } = current;
1492
+ const email = personalData.email.trim();
1493
+ if (!tracking_EMAIL.test(email)) return;
1494
+ const document1 = onlyDigits(personalData.document);
1495
+ const tracking = location.tracking ?? {};
1496
+ const body = {
1497
+ hash: offer.hash,
1498
+ email,
1499
+ fullName: personalData.name.trim(),
1500
+ // Partial phone or document would land in the CRM as is; send them only once complete.
1501
+ telephone: parseTelephone(personalData.phone) ? personalData.phone.trim() : '',
1502
+ document: document1 && isValidDocument(document1) ? document1 : undefined,
1503
+ utmSource: tracking.utmSource,
1504
+ utmMedium: tracking.utmMedium,
1505
+ utmCampaign: tracking.utmCampaign,
1506
+ utmTerm: tracking.utmTerm,
1507
+ utmContent: tracking.utmContent,
1508
+ extraParams: tracking.extraParams,
1509
+ src: tracking.src,
1510
+ sck: tracking.sck,
1511
+ referrer: tracking.referrer,
1512
+ landingUrl: tracking.landingUrl,
1513
+ pageId: location.pageId && UUID.test(location.pageId) ? location.pageId : undefined,
1514
+ visitorId: location.visitorId,
1515
+ sessionId: location.sessionId,
1516
+ affiliateHash: current.affiliateHash,
1517
+ funnelCreatedLead: false
1518
+ };
1519
+ // A blur on a field already sent changes nothing on the server.
1520
+ const signature = JSON.stringify(body);
1521
+ if (signature === lastLead.current) return;
1522
+ lastLead.current = signature;
1523
+ leadInFlight.current = true;
1524
+ current.api.trackLead({
1525
+ ...body,
1526
+ funnelCreatedLead: createdLead.current
1527
+ }).then(()=>{
1528
+ createdLead.current = true;
1529
+ }).catch(()=>{}).finally(()=>{
1530
+ leadInFlight.current = false;
1531
+ if (!leadQueued.current) return;
1532
+ leadQueued.current = false;
1533
+ send();
1534
+ });
1535
+ }, []);
1536
+ // Leading edge: the first capture of a burst goes at once. Closing the tab runs no cleanup, so
1537
+ // a capture held back by a plain debounce would be lost; this way only a later refinement is.
1538
+ const captureLead = useCallback(()=>{
1539
+ if (leadTimer.current) {
1540
+ pendingLead.current = true;
1541
+ return;
1542
+ }
1543
+ sendLead();
1544
+ leadTimer.current = setTimeout(function flush() {
1545
+ leadTimer.current = null;
1546
+ if (!pendingLead.current) return;
1547
+ pendingLead.current = false;
1548
+ sendLead();
1549
+ }, LEAD_WAIT_MS);
1550
+ }, [
1551
+ sendLead
1552
+ ]);
1553
+ useEffect(()=>()=>{
1554
+ if (leadTimer.current) clearTimeout(leadTimer.current);
1555
+ leadTimer.current = null;
1556
+ if (pendingLead.current) sendLead();
1557
+ pendingLead.current = false;
1558
+ }, [
1559
+ sendLead
1560
+ ]);
1561
+ // endregion
1562
+ return useMemo(()=>({
1563
+ captureLead,
1564
+ methodChosen: (chosen)=>{
1565
+ interaction({
1566
+ selectedPaymentMethod: chosen
1567
+ });
1568
+ addPaymentInfo(chosen);
1569
+ },
1570
+ cardFocused: ()=>{
1571
+ if (fired.has('cardInteracted')) return;
1572
+ fired.add('cardInteracted');
1573
+ interaction({
1574
+ cardInteracted: true
1575
+ });
1576
+ addPaymentInfo('credit');
1577
+ },
1578
+ purchased: (paid, amount, id)=>{
1579
+ // Free and subscription purchases count as card, like the standard checkout.
1580
+ const method = paid === 'pix' || paid === 'boleto' ? paid : 'credit';
1581
+ emit('purchase', targets('purchase', (pixel)=>pixel.eventsConfig.purchase?.enabled === true && pixel.eventsConfig.purchase.paymentMethods[method], id), {
1582
+ paymentMethod: method,
1583
+ amountCents: amount,
1584
+ currency: 'BRL',
1585
+ transactionId: id
1586
+ });
1587
+ }
1588
+ }), [
1589
+ captureLead,
1590
+ interaction,
1591
+ addPaymentInfo,
1592
+ fired,
1593
+ emit,
1594
+ targets
1595
+ ]);
1596
+ }
1597
+
1598
+
1599
+
1600
+
1601
+
1192
1602
 
1193
1603
 
1194
1604
 
@@ -1273,13 +1683,22 @@ function staticInstallments(offer) {
1273
1683
  // `submit` stable.
1274
1684
  const propsRef = useRef(props);
1275
1685
  propsRef.current = props;
1686
+ // Set once tracking is created below; the purchase callbacks report through it.
1687
+ const trackingRef = useRef(null);
1276
1688
  const callbacks = useMemo(()=>({
1277
- onApproved: (purchase)=>propsRef.current.onApproved?.(purchase),
1689
+ onApproved: (purchase)=>{
1690
+ trackingRef.current?.purchased(purchase.method, purchase.totalAmount, purchase.transactionId);
1691
+ propsRef.current.onApproved?.(purchase);
1692
+ },
1278
1693
  onDeclined: (purchase)=>propsRef.current.onDeclined?.(purchase),
1279
1694
  onPixGenerated: (pix)=>propsRef.current.onPixGenerated?.(pix),
1280
- onBoletoGenerated: (boleto)=>propsRef.current.onBoletoGenerated?.(boleto),
1695
+ onBoletoGenerated: (boleto)=>{
1696
+ trackingRef.current?.purchased('boleto', boleto.totalAmount, boleto.transactionId);
1697
+ propsRef.current.onBoletoGenerated?.(boleto);
1698
+ },
1281
1699
  onUpsellAccepted: (purchase)=>propsRef.current.onUpsellAccepted?.(purchase),
1282
- onUpsellDeclined: (event)=>propsRef.current.onUpsellDeclined?.(event)
1700
+ onUpsellDeclined: (event)=>propsRef.current.onUpsellDeclined?.(event),
1701
+ onPixelEvent: (event)=>propsRef.current.onPixelEvent?.(event)
1283
1702
  }), []);
1284
1703
  const [isHydrated, setHydrated] = useState(false);
1285
1704
  useEffect(()=>setHydrated(true), []);
@@ -1615,6 +2034,21 @@ function staticInstallments(offer) {
1615
2034
  const [cardHolderName, setCardHolderName] = useState('');
1616
2035
  const [card, registerCard] = useState(undefined);
1617
2036
  // endregion
2037
+ const tracking = useCheckoutTracking({
2038
+ api,
2039
+ offer,
2040
+ location,
2041
+ affiliateHash,
2042
+ pixels,
2043
+ visitorSettled: visitor.status === 'success' || visitor.status === 'error',
2044
+ personalDataActive,
2045
+ personalData: personalValues,
2046
+ oneClick: oneClickData,
2047
+ address: addressRequired ? addressValues : undefined,
2048
+ method,
2049
+ callbacks
2050
+ });
2051
+ trackingRef.current = tracking;
1618
2052
  // region Summary
1619
2053
  const summary = useMemo(()=>{
1620
2054
  const data = pricing.data;
@@ -1784,7 +2218,8 @@ function staticInstallments(offer) {
1784
2218
  }));
1785
2219
  },
1786
2220
  validate: validatePersonal,
1787
- isActive: personalDataActive
2221
+ isActive: personalDataActive,
2222
+ captureLead: tracking.captureLead
1788
2223
  },
1789
2224
  address: {
1790
2225
  values: addressValues,
@@ -1829,7 +2264,10 @@ function staticInstallments(offer) {
1829
2264
  payment: {
1830
2265
  methods,
1831
2266
  method,
1832
- setMethod: setChosenMethod,
2267
+ setMethod: (next)=>{
2268
+ setChosenMethod(next);
2269
+ tracking.methodChosen(next);
2270
+ },
1833
2271
  installments,
1834
2272
  installment,
1835
2273
  setInstallment: setChosenInstallment,
@@ -1839,7 +2277,8 @@ function staticInstallments(offer) {
1839
2277
  cardHolderName,
1840
2278
  setCardHolderName,
1841
2279
  card,
1842
- registerCard
2280
+ registerCard,
2281
+ cardInteracted: tracking.cardFocused
1843
2282
  },
1844
2283
  submission,
1845
2284
  submit,
@@ -1877,7 +2316,9 @@ const ELEMENTS_LOCALE = {
1877
2316
  const propsRef = useRef(props);
1878
2317
  propsRef.current = props;
1879
2318
  const showFrame = !payment.useSavedCard;
1880
- const { registerCard } = payment;
2319
+ const { registerCard, cardInteracted } = payment;
2320
+ const cardInteractedRef = useRef(cardInteracted);
2321
+ cardInteractedRef.current = cardInteracted;
1881
2322
  // Created once per mount, like react-stripe-js: later prop changes go through `update`.
1882
2323
  useClientLayoutEffect(()=>{
1883
2324
  if (!showFrame || !containerRef.current) return;
@@ -1894,7 +2335,10 @@ const ELEMENTS_LOCALE = {
1894
2335
  locale: ELEMENTS_LOCALE[locale],
1895
2336
  disabled: propsRef.current.disabled
1896
2337
  });
1897
- card.on('ready', ()=>propsRef.current.onReady?.()).on('change', (event)=>propsRef.current.onChange?.(event)).on('focus', (event)=>propsRef.current.onFocus?.(event)).on('blur', (event)=>propsRef.current.onBlur?.(event)).on('loaderror', (event)=>propsRef.current.onLoadError?.(event));
2338
+ card.on('ready', ()=>propsRef.current.onReady?.()).on('change', (event)=>propsRef.current.onChange?.(event)).on('focus', (event)=>{
2339
+ cardInteractedRef.current();
2340
+ propsRef.current.onFocus?.(event);
2341
+ }).on('blur', (event)=>propsRef.current.onBlur?.(event)).on('loaderror', (event)=>propsRef.current.onLoadError?.(event));
1898
2342
  card.mount(containerRef.current);
1899
2343
  cardRef.current = card;
1900
2344
  registerCard(card);
@@ -2280,7 +2724,7 @@ function OrderBumpContent({ bump }) {
2280
2724
  ]
2281
2725
  });
2282
2726
  }
2283
- function useFieldFactory(values, errors, setValue, meta) {
2727
+ function useFieldFactory(values, errors, setValue, meta, onBlur) {
2284
2728
  const baseId = useId();
2285
2729
  const result = {};
2286
2730
  for (const key of Object.keys(meta)){
@@ -2297,7 +2741,10 @@ function useFieldFactory(values, errors, setValue, meta) {
2297
2741
  'aria-invalid': Boolean(error),
2298
2742
  'aria-describedby': error ? `${id}-error` : undefined,
2299
2743
  autoComplete: meta[key].autoComplete,
2300
- inputMode: meta[key].inputMode
2744
+ inputMode: meta[key].inputMode,
2745
+ ...onBlur ? {
2746
+ onBlur
2747
+ } : {}
2301
2748
  }
2302
2749
  };
2303
2750
  }
@@ -2353,8 +2800,8 @@ function DefaultField({ label, field }) {
2353
2800
  });
2354
2801
  }
2355
2802
  /** 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);
2803
+ const { values, errors, setValue, isActive, oneClick, captureLead } = usePersonalData();
2804
+ const fields = useFieldFactory(values, errors, setValue, PERSONAL_META, captureLead);
2358
2805
  const state = {
2359
2806
  fields,
2360
2807
  oneClick: !isActive && oneClick.data ? {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clickmax/checkout-react",
3
- "version": "12.5.15",
3
+ "version": "12.5.17",
4
4
  "description": "Headless React components for the Clickmax checkout",
5
5
  "keywords": [
6
6
  "clickmax",