@cartbase/storefront 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -58
- package/package.json +11 -1
- package/src/api/integrations.ts +118 -117
- package/src/tracking/attribution.ts +126 -0
- package/src/tracking/consent.ts +14 -0
- package/src/tracking/events.ts +294 -0
- package/src/tracking/ga4.tsx +93 -49
- package/src/tracking/get-tracking-attribution.ts +30 -0
- package/src/tracking/google-ads.ts +84 -0
- package/src/tracking/gtag.ts +26 -13
- package/src/tracking/gtm.tsx +60 -0
- package/src/tracking/index.ts +176 -133
- package/src/tracking/inline-script.ts +49 -0
- package/src/tracking/storefront-tags.tsx +67 -0
- package/src/tracking/tiktok-pixel.tsx +83 -0
- package/src/tracking/track-init.tsx +56 -0
- package/src/tracking/track-order-purchase.tsx +122 -0
- package/src/tracking/ttq.ts +180 -0
- package/src/tracking/types.ts +23 -0
- package/src/tracking/use-tracking-config.ts +54 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { useEffect, useRef } from "react"
|
|
4
|
+
|
|
5
|
+
import type { CartLineItem, CompletedOrder } from "../api/carts"
|
|
6
|
+
import { trackOrderPurchase, type TrackedLine } from "./events"
|
|
7
|
+
import type { TrackingConfig } from "./types"
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* TrackOrderPurchase — fires the purchase event to every configured
|
|
11
|
+
* vendor from the order confirmation page.
|
|
12
|
+
*
|
|
13
|
+
* A component rather than four calls in the app, because purchase is the
|
|
14
|
+
* one event nobody may get wrong and it is the one with the most ways to
|
|
15
|
+
* go wrong: the dedup keys must match the server's exactly, the ids must
|
|
16
|
+
* be the CATALOGUE's, and every vendor must fire from the same place.
|
|
17
|
+
* A storefront mounts this and is done.
|
|
18
|
+
*
|
|
19
|
+
* FIRES ONCE PER ORDER, per browser. The guard is real, not defensive
|
|
20
|
+
* tidiness: this page is linked from every order email, so a buyer opens
|
|
21
|
+
* it again days later, and React strict mode double-mounts effects in
|
|
22
|
+
* development. The vendors dedupe too (Meta and TikTok on the shared
|
|
23
|
+
* event id, GA4 and Google Ads on the transaction id) and the platform's
|
|
24
|
+
* server side carries its own idempotency flag, so this is the third of
|
|
25
|
+
* three layers — but it is the only one that stops the request being made
|
|
26
|
+
* at all.
|
|
27
|
+
*
|
|
28
|
+
* `customerType` comes from `order.metadata.customer_type`, which the
|
|
29
|
+
* platform's order.placed forwarder computes ONCE and persists. Reading
|
|
30
|
+
* it from the order rather than deriving it in the browser is what keeps
|
|
31
|
+
* the browser and the server from telling Google and TikTok different
|
|
32
|
+
* things about the same buyer.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
const FIRED_KEY_PREFIX = "_cb_purchase_tracked_"
|
|
36
|
+
|
|
37
|
+
function alreadyFired(key: string): boolean {
|
|
38
|
+
try {
|
|
39
|
+
return sessionStorage.getItem(key) === "1"
|
|
40
|
+
} catch {
|
|
41
|
+
// Private mode / blocked storage: fall back to the in-memory ref
|
|
42
|
+
// only. Worst case is a second event the vendors then dedupe.
|
|
43
|
+
return false
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function markFired(key: string): void {
|
|
48
|
+
try {
|
|
49
|
+
sessionStorage.setItem(key, "1")
|
|
50
|
+
} catch {
|
|
51
|
+
// Non-fatal — see above.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function TrackOrderPurchase({
|
|
56
|
+
order,
|
|
57
|
+
items,
|
|
58
|
+
config,
|
|
59
|
+
}: {
|
|
60
|
+
order: CompletedOrder
|
|
61
|
+
/** The cart lines as completed. Carry product_id — it is the catalogue
|
|
62
|
+
* key Meta and TikTok match on, and the flattened order items may not
|
|
63
|
+
* have it. */
|
|
64
|
+
items: CartLineItem[]
|
|
65
|
+
/** The store's tracking config. Google Ads fires only when it carries
|
|
66
|
+
* both the account id and the purchase label. */
|
|
67
|
+
config?: TrackingConfig
|
|
68
|
+
}) {
|
|
69
|
+
const firedRef = useRef(false)
|
|
70
|
+
|
|
71
|
+
useEffect(() => {
|
|
72
|
+
const displayId = order.display_id
|
|
73
|
+
// No display id means no dedup key, and an event that cannot dedupe
|
|
74
|
+
// against the server's is worse than no event: it double-counts.
|
|
75
|
+
if (displayId === undefined || displayId === null) return
|
|
76
|
+
|
|
77
|
+
const key = `${FIRED_KEY_PREFIX}${displayId}`
|
|
78
|
+
if (firedRef.current || alreadyFired(key)) return
|
|
79
|
+
firedRef.current = true
|
|
80
|
+
markFired(key)
|
|
81
|
+
|
|
82
|
+
const lines: TrackedLine[] = items.map((item) => ({
|
|
83
|
+
productId: item.product_id || item.variant_id || item.id,
|
|
84
|
+
variantId: item.variant_id ?? undefined,
|
|
85
|
+
title: item.product_title || item.title || "",
|
|
86
|
+
quantity: Number(item.quantity) || 1,
|
|
87
|
+
price: Number(item.unit_price) || 0,
|
|
88
|
+
}))
|
|
89
|
+
|
|
90
|
+
const summary = (Array.isArray(order.summary)
|
|
91
|
+
? order.summary[0]
|
|
92
|
+
: order.summary) as Record<string, unknown> | null
|
|
93
|
+
const totals = (summary?.totals ?? summary ?? {}) as Record<string, unknown>
|
|
94
|
+
const num = (v: unknown): number | undefined =>
|
|
95
|
+
typeof v === "number" ? v : undefined
|
|
96
|
+
|
|
97
|
+
const value =
|
|
98
|
+
num(totals.total) ??
|
|
99
|
+
lines.reduce((sum, line) => sum + line.price * line.quantity, 0)
|
|
100
|
+
|
|
101
|
+
const metadata = (order.metadata ?? {}) as Record<string, unknown>
|
|
102
|
+
const customerType =
|
|
103
|
+
metadata.customer_type === "new" || metadata.customer_type === "returning"
|
|
104
|
+
? metadata.customer_type
|
|
105
|
+
: undefined
|
|
106
|
+
|
|
107
|
+
trackOrderPurchase(
|
|
108
|
+
{
|
|
109
|
+
displayId,
|
|
110
|
+
currency: (order.currency_code || "eur").toUpperCase(),
|
|
111
|
+
value,
|
|
112
|
+
tax: num(totals.tax_total),
|
|
113
|
+
shipping: num(totals.shipping_total),
|
|
114
|
+
lines,
|
|
115
|
+
customerType,
|
|
116
|
+
},
|
|
117
|
+
config
|
|
118
|
+
)
|
|
119
|
+
}, [order, items, config])
|
|
120
|
+
|
|
121
|
+
return null
|
|
122
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Typed wrappers around the global `ttq` from the TikTok Pixel — the
|
|
5
|
+
* TikTok twin of ./fbq.ts, and deliberately the same shape so a surface
|
|
6
|
+
* that fires one can fire the other on the line below.
|
|
7
|
+
*
|
|
8
|
+
* Every helper no-ops when `window.ttq` is absent (pixel not configured,
|
|
9
|
+
* server render, script blocked), so callers need no guards.
|
|
10
|
+
*
|
|
11
|
+
* Event names are case-sensitive and taken from TikTok's supported pixel
|
|
12
|
+
* events table:
|
|
13
|
+
* https://business-api.tiktok.com/portal/docs/supported-pixel-events/v1.3
|
|
14
|
+
* `Purchase` is the current name; `CompletePayment` and `PlaceAnOrder` do
|
|
15
|
+
* not appear in the current tables at all.
|
|
16
|
+
*
|
|
17
|
+
* `event_id` is the THIRD argument, a separate object after the
|
|
18
|
+
* properties, per TikTok's own implementation guide:
|
|
19
|
+
*
|
|
20
|
+
* ttq.track('Purchase', { ...properties }, { event_id: 'tt_purchase_1044' })
|
|
21
|
+
*
|
|
22
|
+
* TikTok deduplicates on event_source_id + event + event_id and discards
|
|
23
|
+
* duplicates for 48 hours from the first event, which is how the browser
|
|
24
|
+
* Purchase and the server-side Events API Purchase collapse into one.
|
|
25
|
+
*
|
|
26
|
+
* `content_id` must be the SAME identifier the product catalogue uses,
|
|
27
|
+
* which on Cartbase is the PRODUCT id — the value the feed emits as
|
|
28
|
+
* <g:id> and the value Meta already receives. A variant id here matches
|
|
29
|
+
* no catalogue entry at all.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** One product line inside `contents`. */
|
|
33
|
+
export type TikTokContentItem = {
|
|
34
|
+
content_id: string
|
|
35
|
+
content_name?: string
|
|
36
|
+
content_category?: string
|
|
37
|
+
brand?: string
|
|
38
|
+
quantity?: number
|
|
39
|
+
price?: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type TikTokProperties = {
|
|
43
|
+
contents?: TikTokContentItem[]
|
|
44
|
+
content_id?: string
|
|
45
|
+
content_name?: string
|
|
46
|
+
content_type?: "product" | "product_group"
|
|
47
|
+
currency?: string
|
|
48
|
+
value?: number
|
|
49
|
+
quantity?: number
|
|
50
|
+
description?: string
|
|
51
|
+
order_id?: string
|
|
52
|
+
/** TikTok's new-versus-returning signal. Same computed fact the backend
|
|
53
|
+
* persists on the order and sends to Google Ads as `new_customer`. */
|
|
54
|
+
customer_type?: "new" | "returning"
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type TtqFn = {
|
|
58
|
+
track: (
|
|
59
|
+
event: string,
|
|
60
|
+
properties?: TikTokProperties,
|
|
61
|
+
options?: { event_id?: string }
|
|
62
|
+
) => void
|
|
63
|
+
page: () => void
|
|
64
|
+
identify: (data: Record<string, unknown>) => void
|
|
65
|
+
grantConsent: () => void
|
|
66
|
+
revokeConsent: () => void
|
|
67
|
+
holdConsent: () => void
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function safeTtq(): TtqFn | null {
|
|
71
|
+
if (typeof window === "undefined") return null
|
|
72
|
+
const ttq = (window as unknown as { ttq?: Partial<TtqFn> }).ttq
|
|
73
|
+
if (!ttq || typeof ttq.track !== "function") return null
|
|
74
|
+
return ttq as TtqFn
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* THE purchase dedup key — must equal what the backend forwarder sends
|
|
79
|
+
* (`tiktokPurchaseEventId` in src/lib/tracking/constants.ts). Built from
|
|
80
|
+
* display_id here so the format cannot drift between the two sides, the
|
|
81
|
+
* same guarantee `trackPurchase` gives for Meta.
|
|
82
|
+
*/
|
|
83
|
+
export function tiktokPurchaseEventId(displayId: string | number): string {
|
|
84
|
+
return `tt_purchase_${displayId}`
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function trackTikTokViewContent(data: {
|
|
88
|
+
contentId: string
|
|
89
|
+
contentName?: string
|
|
90
|
+
currency: string
|
|
91
|
+
value: number
|
|
92
|
+
}): void {
|
|
93
|
+
const ttq = safeTtq()
|
|
94
|
+
if (!ttq) return
|
|
95
|
+
ttq.track("ViewContent", {
|
|
96
|
+
content_id: data.contentId,
|
|
97
|
+
content_type: "product",
|
|
98
|
+
content_name: data.contentName,
|
|
99
|
+
currency: data.currency,
|
|
100
|
+
value: data.value,
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function trackTikTokAddToCart(data: {
|
|
105
|
+
contentId: string
|
|
106
|
+
contentName?: string
|
|
107
|
+
quantity: number
|
|
108
|
+
price: number
|
|
109
|
+
currency: string
|
|
110
|
+
value: number
|
|
111
|
+
}): void {
|
|
112
|
+
const ttq = safeTtq()
|
|
113
|
+
if (!ttq) return
|
|
114
|
+
ttq.track("AddToCart", {
|
|
115
|
+
contents: [
|
|
116
|
+
{
|
|
117
|
+
content_id: data.contentId,
|
|
118
|
+
content_name: data.contentName,
|
|
119
|
+
quantity: data.quantity,
|
|
120
|
+
price: data.price,
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
content_type: "product",
|
|
124
|
+
currency: data.currency,
|
|
125
|
+
value: data.value,
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function trackTikTokInitiateCheckout(data: {
|
|
130
|
+
contents: TikTokContentItem[]
|
|
131
|
+
currency: string
|
|
132
|
+
value: number
|
|
133
|
+
}): void {
|
|
134
|
+
const ttq = safeTtq()
|
|
135
|
+
if (!ttq) return
|
|
136
|
+
ttq.track("InitiateCheckout", {
|
|
137
|
+
contents: data.contents,
|
|
138
|
+
content_type: "product",
|
|
139
|
+
currency: data.currency,
|
|
140
|
+
value: data.value,
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function trackTikTokPurchase(data: {
|
|
145
|
+
contents: TikTokContentItem[]
|
|
146
|
+
currency: string
|
|
147
|
+
value: number
|
|
148
|
+
/** The order's display id — the dedup key and the order_id TikTok shows. */
|
|
149
|
+
displayId: string | number
|
|
150
|
+
customerType?: "new" | "returning"
|
|
151
|
+
}): void {
|
|
152
|
+
const ttq = safeTtq()
|
|
153
|
+
if (!ttq) return
|
|
154
|
+
ttq.track(
|
|
155
|
+
"Purchase",
|
|
156
|
+
{
|
|
157
|
+
contents: data.contents,
|
|
158
|
+
content_type: "product",
|
|
159
|
+
currency: data.currency,
|
|
160
|
+
value: data.value,
|
|
161
|
+
order_id: String(data.displayId),
|
|
162
|
+
...(data.customerType ? { customer_type: data.customerType } : {}),
|
|
163
|
+
},
|
|
164
|
+
{ event_id: tiktokPurchaseEventId(data.displayId) }
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Push a live consent decision to the pixel.
|
|
170
|
+
*
|
|
171
|
+
* Normally you do NOT call this: `applyConsent()` in ./consent.ts already
|
|
172
|
+
* relays every decision to gtag, fbq and ttq together. It is exported for
|
|
173
|
+
* a host app driving the pixel from a consent layer of its own.
|
|
174
|
+
*/
|
|
175
|
+
export function applyTikTokConsent(adsGranted: boolean): void {
|
|
176
|
+
const ttq = safeTtq()
|
|
177
|
+
if (!ttq) return
|
|
178
|
+
if (adsGranted) ttq.grantConsent()
|
|
179
|
+
else ttq.revokeConsent()
|
|
180
|
+
}
|
package/src/tracking/types.ts
CHANGED
|
@@ -40,6 +40,10 @@ export type TrackingConfig = {
|
|
|
40
40
|
/** Cartbase extension over the @1click TrackingConfig — explicit Google
|
|
41
41
|
* Ads tag config (the @1click engine wired Ads through GTM). */
|
|
42
42
|
googleAds?: { conversionId: string; conversionLabel?: string }
|
|
43
|
+
/** Pixel id ONLY. The Events API token stays on the platform and is
|
|
44
|
+
* read by the order.placed forwarder, exactly like Meta's CAPI token,
|
|
45
|
+
* which has never traversed this surface. */
|
|
46
|
+
tiktok?: { pixelId: string }
|
|
43
47
|
/** True when the store's consent CMP is enabled — client tags must
|
|
44
48
|
* mount through the consent gate (`_1c_consent` / Consent Mode v2). */
|
|
45
49
|
consent_required?: boolean
|
|
@@ -171,6 +175,25 @@ export type TrackingAttribution = {
|
|
|
171
175
|
utm_last_term?: string
|
|
172
176
|
utm_last_content?: string
|
|
173
177
|
utm_last_captured_at?: number
|
|
178
|
+
|
|
179
|
+
// ── Ad-click identifiers ───────────────────────────────────────────
|
|
180
|
+
// Captured by browser-side `captureClickIdsFromUrl()` into `_1c_`
|
|
181
|
+
// cookies and read here at checkout. Meta's fbclid needs no entry: it
|
|
182
|
+
// is folded into `fb_fbc` by Meta's own cookie format.
|
|
183
|
+
|
|
184
|
+
/** TikTok's click id. Without it TikTok cannot attribute a conversion
|
|
185
|
+
* back to the click that caused it. Sent as `user.ttclid`. */
|
|
186
|
+
tt_ttclid?: string
|
|
187
|
+
/** The `_ttp` cookie TikTok's own pixel writes when first-party
|
|
188
|
+
* cookies are enabled. Read only; sent as `user.ttp`. */
|
|
189
|
+
tt_ttp?: string
|
|
190
|
+
/** Google's standard click id. */
|
|
191
|
+
google_gclid?: string
|
|
192
|
+
/** iOS app-to-web click id. A campaign can deliver this instead of
|
|
193
|
+
* gclid, so capturing gclid alone loses that traffic silently. */
|
|
194
|
+
google_gbraid?: string
|
|
195
|
+
/** iOS web-to-web click id, same reasoning as gbraid. */
|
|
196
|
+
google_wbraid?: string
|
|
174
197
|
}
|
|
175
198
|
|
|
176
199
|
/**
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { useEffect, useState } from "react"
|
|
4
|
+
|
|
5
|
+
import type { StorefrontClient } from "../api/http"
|
|
6
|
+
import { getTrackingConfig } from "./get-tracking-config"
|
|
7
|
+
import type { TrackingConfig } from "./types"
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The store's public tag config, from a client component.
|
|
11
|
+
*
|
|
12
|
+
* `<StorefrontTags>` reads the same config on the SERVER, which is right
|
|
13
|
+
* for mounting tags in a layout. This hook exists for the one place that
|
|
14
|
+
* genuinely cannot: a client page that needs the config to decide what to
|
|
15
|
+
* send, the order confirmation being the case that matters, because
|
|
16
|
+
* Google Ads needs the account id and the purchase label to build a valid
|
|
17
|
+
* `send_to`.
|
|
18
|
+
*
|
|
19
|
+
* Cached per browser session in module scope: the config changes only
|
|
20
|
+
* when a merchant edits Settings → Integrations, and re-fetching it on
|
|
21
|
+
* every mount would put a request in front of the purchase event.
|
|
22
|
+
*
|
|
23
|
+
* Returns undefined until the fetch resolves, and `{}` if it fails, so a
|
|
24
|
+
* caller renders and fires the vendors that need no config either way.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
let cached: TrackingConfig | undefined
|
|
28
|
+
let inFlight: Promise<TrackingConfig> | undefined
|
|
29
|
+
|
|
30
|
+
export function useTrackingConfig(
|
|
31
|
+
client: StorefrontClient
|
|
32
|
+
): TrackingConfig | undefined {
|
|
33
|
+
const [config, setConfig] = useState<TrackingConfig | undefined>(cached)
|
|
34
|
+
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (cached) return
|
|
37
|
+
let active = true
|
|
38
|
+
inFlight =
|
|
39
|
+
inFlight ??
|
|
40
|
+
getTrackingConfig(client).then((value) => {
|
|
41
|
+
cached = value
|
|
42
|
+
inFlight = undefined
|
|
43
|
+
return value
|
|
44
|
+
})
|
|
45
|
+
inFlight.then((value) => {
|
|
46
|
+
if (active) setConfig(value)
|
|
47
|
+
})
|
|
48
|
+
return () => {
|
|
49
|
+
active = false
|
|
50
|
+
}
|
|
51
|
+
}, [client])
|
|
52
|
+
|
|
53
|
+
return config
|
|
54
|
+
}
|