-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.liquid
More file actions
632 lines (551 loc) · 24.9 KB
/
scripts.liquid
File metadata and controls
632 lines (551 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
<!-- BEGIN: Fueled Supplemental Data Layer & Checkout Script Variables -->
<script>
window.dataLayer = window.dataLayer || [];
var dataLayerObjectName = "fueled"; // Provide a namespace in the data layer object.
var customerData = {};
{% if checkout.customer.id or customer.id %}
customerData.customer_id = {{ checkout.customer.id | default: customer.id | json }};
{% endif %}
{% if checkout.email or customer.email %}
customerData.customer_email = {{ checkout.email | default: customer.email | json }};
{% endif %}
{% if checkout.billing_address.first_name or customer.first_name %}
customerData.customer_first_name = {{ checkout.billing_address.first_name | default: customer.first_name | json }};
{% endif %}
{% if checkout.billing_address.last_name or customer.last_name %}
customerData.customer_last_name = {{ checkout.billing_address.last_name | default: customer.last_name | json }};
{% endif %}
{% if checkout.customer.phone or checkout.billing_address.phone or checkout.shipping_address.phone or customer.phone %}
customerData.customer_phone = {{ checkout.customer.phone | default: checkout.billing_address.phone | json }};
{% endif %}
{% if checkout.billing_address.city or customer.default_address.city %}
customerData.customer_city = {{ checkout.billing_address.city | default: customer.default_address.city | json }};
{% endif %}
{% if checkout.billing_address.zip or customer.default_address.zip %}
customerData.customer_zip = {{ checkout.billing_address.zip | default: customer.default_address.zip | json }};
{% endif %}
{% if checkout.billing_address.address1 or customer.default_address.address1 %}
customerData.customer_address_1 = {{ checkout.billing_address.address1 | default: customer.default_address.address1 | json }};
{% endif %}
{% if checkout.billing_address.address2 or customer.default_address.address2 %}
customerData.customer_address_2 = {{ checkout.billing_address.address2 | default: customer.default_address.address2 | json }};
{% endif %}
{% if checkout.billing_address.country or customer.default_address.country %}
customerData.customer_country = {{ checkout.billing_address.country | default: customer.default_address.country | json }};
{% endif %}
{% if checkout.billing_address.country_code or customer.default_address.country_code %}
customerData.customer_country_code = {{ checkout.billing_address.country_code | default: customer.default_address.country_code | json }};
{% endif %}
{% if checkout.billing_address.province or customer.default_address.province %}
customerData.customer_province = {{ checkout.billing_address.province | default: customer.default_address.province | json }};
{% endif %}
{% if checkout.billing_address.province_code or customer.default_address.province_code %}
customerData.customer_province_code = {{ checkout.billing_address.province_code | default: customer.default_address.province_code | json }};
{% endif %}
{% if checkout.customer.tags or customer.tags %}
customerData.customer_tags = {{ checkout.customer.tags | default: customer.tags | json }};
{% endif %}
{% if customer.orders_count > 0 %}
customerData.total_spend = {{ customer.total_spent | divided_by: 100.0 }};
customerData.orders_count = {{ customer.orders_count }};
{% endif %}
{% if customer %}
var customerType = {% if customer.orders_count > 1 %}"returning"{% else %}"new"{% endif %};
customerData.customer_type = customerType;
{% endif %}
// Function to build and return the order data object
function buildOrderData() {
// Check if any order line items have a subscription attached to them.
var includesSubscription = {% assign subscription_found = false %}{% for line_item in checkout.line_items %}{% if line_item.selling_plan_allocation.selling_plan %}{% assign subscription_found = true %}{% break %}{% endif %}{% endfor %}{{ subscription_found | json }};
// Calculate the total quantity of all line items
var totalQuantity = {% assign total_quantity = 0 %}{% for line_item in checkout.line_items %}{% assign total_quantity = total_quantity | plus: line_item.quantity %}{% endfor %}{{ total_quantity }};
return {
checkout_id: {{ checkout.id | json }},
order_id: {% if checkout.order_id %}{{ checkout.order_id | json }}{% else %}{{ order.id | json }}{% endif %},
order_number: {{ checkout.order_number | json }},
order_name: {% if checkout.order_name %}{{ checkout.order_name | json }}{% else %}"N/A"{% endif %},
shop_name: {{ shop.name | json }},
revenue: {{ checkout.total_price | money_without_currency }},
currency: {{ checkout.currency | json }},
tax: {{ checkout.tax_price | money_without_currency }},
shipping: {{ checkout.shipping_price | money_without_currency }},
order_subtotal: {% if order and order.subtotal_price %}{{ order.subtotal_price | money_without_currency }}{% else %}{{ checkout.line_items_subtotal_price | money_without_currency }}{% endif %},
order_line_items_subtotal: {{ checkout.line_items_subtotal_price | money_without_currency }},
order_total_product_count: totalQuantity,
discount_amount: {{ checkout.discount_applications | map: 'total_allocated_amount' | first | default: 0 | money_without_currency }},
coupon: {% if checkout.discount_applications %}{{ checkout.discount_applications[0].title | json }}{% else %}""{% endif %},
includes_subscription: includesSubscription
};
}
// Function to build and return the items data array
function buildItemsData() {
var items = [];
{% for line_item in checkout.line_items %}
items.push({
name: {{ line_item.product.title | json }},
product_id: {{ line_item.product_id | json }},
variant: {{ line_item.variant.title | json }},
variant_id: {{ line_item.variant_id | json }},
sku: {{ line_item.sku | json }},
brand: {{ line_item.vendor | json }},
category: {{ line_item.product.type | json }},
price: {{ line_item.final_price | money_without_currency }},
line_item_discount: {{ line_item.total_discount | money_without_currency }},
original_price: {{ line_item.original_price | money_without_currency }},
quantity: {{ line_item.quantity | json }},
image: {{ line_item.image | image_url | json }},
subscription_line_item: {% if line_item.selling_plan_allocation.selling_plan %}true{% else %}false{% endif %}
});
{% endfor %}
return items;
}
// Use functions to initialize orderData and itemsData
var orderData = buildOrderData();
var itemsData = buildItemsData();
window.dataLayer.push({
event: 'orderDataLoaded',
[dataLayerObjectName]: {
customer: customerData,
order: orderData,
orderItems: itemsData
}
});
//console.log(window.dataLayer); // Optionally test data layer in Console Log.
</script>
<!-- END: Fueled Supplemental Data Layer & Checkout Script Variables -->
<!-- BEGIN: Add Pixel Variables here. This will conditionally enable their tracking scripts below -->
{% assign gtmContainerId = "GTM-P2NF4FZ" %}
{% assign grinPixelId = "" %}
{% assign criteoPixel = "" %}
{% assign taboolaPixelId = "" %}
{% assign addShoppersPixel = "" %}
{% assign pinterestPixel = "" %}
{% assign attentiveId = "" %}
{% assign tikTokPixelId = "" %}
{% assign bingPixel = "" %}
<!-- BEGIN: Google Tag Manager -->
<script>
var gtmContainerId = "{{ gtmContainerId | default: '' }}" || "";
if(gtmContainerId) { // Check if the gtmContainerId is neither null nor empty
(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
"gtm.start": new Date().getTime(),
event: "gtm.js"
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl; // Dynamically set the GTM ID
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", gtmContainerId); // Use the gtmContainerId variable here
}
</script>
<!-- END: Google Tag Manager -->
<!-- BEGIN: Tracking Pixels that should only fire once for first page load -->
{% if first_time_accessed %}
<!-- BEGIN: Bing Ads UET Code -->
<script>
async function loadAndExecuteBingPixel() {
var bingPixel = "{{ bingPixel | default: '' }}" || "";
if (!bingPixel) return;
// Load the Bing Ads script
await new Promise((resolve, reject) => {
var script = document.createElement("script");
script.src = "//bat.bing.com/bat.js";
script.async = true;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
// Function to check both buildItemsData and buildOrderData availability
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
// Wait for buildItemsData and buildOrderData to be available
let checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
// Initialize Bing UET tracking
window.uetq = window.uetq || [];
var o = { ti: bingPixel, enableAutoSpaTracking: true };
window.uetq = new UET(o);
window.uetq.push("pageLoad");
const orderData = buildOrderData();
window.uetq.push('event', 'purchase', {
"event_category": "checkout",
"revenue_value": orderData.revenue,
"currency": orderData.currency
});
}
}, 100); // Check every 100 milliseconds
}
loadAndExecuteBingPixel();
</script>
<!-- END: Bing Ads UET Code -->
<!-- BEGIN: TikTok Code -->
<script>
async function setupAndTrackTikTok() {
var tikTokPixelId = "{{ tikTokPixelId | default: '' }}";
if (!tikTokPixelId) return;
await loadTikTokPixelScript();
function loadTikTokPixelScript() {
return new Promise((resolve, reject) => {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://analytics.tiktok.com/i18n/pixel/events.js';
s.onload = () => {
if (window.ttq && typeof window.ttq.init === 'function') {
window.ttq.init(tikTokPixelId);
resolve();
} else {
reject(new Error('TikTok Pixel initialization failed.'));
}
};
s.onerror = reject;
document.head.appendChild(s);
});
}
try {
await loadTikTokPixelScript();
if (typeof buildItemsData === 'function' && typeof buildOrderData === 'function') {
const orderData = buildOrderData();
const formattedProducts = buildItemsData().map(item => ({
content_id: item.product_id,
content_type: 'product_group',
content_name: item.name,
content_category: item.category,
quantity: item.quantity,
price: item.price,
}));
window.ttq.track('CompletePayment', {
contents: formattedProducts,
currency: orderData.currency,
value: orderData.revenue,
}, { eventID: orderData.order_id });
} else {
console.error('buildItemsData or buildOrderData functions are not available.');
}
} catch (error) {
console.error('Error loading or initializing TikTok Pixel:', error);
}
}
setupAndTrackTikTok();
</script>
<!-- END: TikTok Code -->
<!-- BEGIN: Attentive Code -->
<script>
async function loadAndExecuteAttentive() {
var attentiveId = "{{ attentiveId | default: '' }}" || "";
if (!attentiveId) return;
// Dynamically load the dtag.js script with the Attentive ID
await new Promise((resolve, reject) => {
var dtagScript = document.createElement('script');
dtagScript.src = "https://cdn.attn.tv/" + attentiveId + "/dtag.js";
dtagScript.onload = resolve;
dtagScript.onerror = reject;
document.head.appendChild(dtagScript);
});
// Function to check both buildItemsData and buildOrderData availability
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
// Wait for buildItemsData and buildOrderData to be defined
let checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
// Both build functions are available, proceed with Attentive tracking
const itemsData = buildItemsData();
const orderData = buildOrderData();
var order = {
"cart": {
"cartId": orderData.checkout_id,
"cartCoupon": orderData.coupon // Ensure there's a default or conditional logic if discounts might be absent
},
"order": {
"orderId": orderData.order_id
},
"user": {
"phone": '{{ customer.phone }}',
"email": '{{ customer.email }}'
},
"items": itemsData.map(function(item) {
return {
"productId": item.productId,
"productVariantId": item.variantId,
"name": item.name,
"productImage": item.image,
"category": item.category,
"price": {
"value": item.price,
"currency": orderData.currency
},
"quantity": item.quantity
};
})
};
if(window.attentive && window.attentive.analytics && window.attentive.analytics.purchase) {
window.attentive.analytics.purchase(order);
}
}
}, 100); // Check every 100 milliseconds
}
loadAndExecuteAttentive();
</script>
<!-- END: Attentive Code -->
<!-- BEGIN: Pinterest Code -->
<script>
async function loadAndTrackWithPinterest() {
var pinterestPixel = "{{ pinterestPixel | default: '' }}" || "";
if (!pinterestPixel) return;
// Attempt to load Pinterest script
await new Promise((resolve, reject) => {
var script = document.createElement("script");
script.src = "https://s.pinimg.com/ct/core.js";
script.async = true;
document.head.appendChild(script);
script.onload = () => {
// Function to check if pintrk is defined
const checkPintrkDefined = () => typeof window.pintrk === 'function';
// Attempt to check if pintrk is defined immediately after script load
if (checkPintrkDefined()) {
resolve();
} else {
// If pintrk is not immediately available, set intervals to check its availability
let attempts = 0;
const intervalId = setInterval(() => {
if (checkPintrkDefined()) {
clearInterval(intervalId);
resolve();
} else if (++attempts >= 10) { // Give up after 10 attempts (approximately 1 second)
clearInterval(intervalId);
reject(new Error('pintrk function not defined after script load and retry attempts.'));
}
}, 100); // Check every 100ms
}
};
script.onerror = () => reject(new Error('Pinterest script failed to load.'));
});
// Initialize Pinterest tracking with pixel ID
window.pintrk('load', pinterestPixel);
window.pintrk('page');
var customerEmail = {{ customer.email | json }};
if (customerEmail) {
window.pintrk('set', { em: customerEmail });
}
// Function to check both buildItemsData and buildOrderData availability
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
// Wait for buildItemsData and buildOrderData to be defined
var checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
const formattedProductsForPinterest = buildItemsData().map(item => ({
product_name: item.name,
product_id: item.product_id,
product_quantity: item.quantity,
product_price: item.price,
product_category: item.category,
}));
const orderData = buildOrderData();
window.pintrk('track', 'purchase', {
order_id: orderData.order_id,
order_subtotal: orderData.order_subtotal,
order_total: orderData.revenue,
currency: orderData.currency,
line_items: formattedProductsForPinterest
});
}
}, 100); // Check every 100ms
}
loadAndTrackWithPinterest();
</script>
<!-- END: Pinterest Code -->
<!-- BEGIN AddShoppers Code -->
<script type="text/javascript">
async function loadAndExecuteAddShoppers() {
var addShoppersPixel = "{{ addShoppersPixel | default: '' }}" || "";
if (!addShoppersPixel) return;
// Load the AddShoppers script
await new Promise((resolve, reject) => {
var script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.id = "AddShoppers";
script.src = `https://shop.pe/widget/widget_async.js#${addShoppersPixel}`;
script.onload = () => {
if (typeof window.AddShoppersWidget !== 'undefined' && window.AddShoppersWidget.track_conv) {
resolve();
} else {
reject(new Error('AddShoppersWidget.track_conv function not available'));
}
};
script.onerror = reject;
document.head.appendChild(script);
});
// Check for availability of buildItemsData and buildOrderData functions
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
// Wait for buildItemsData and buildOrderData to be available
await new Promise(resolve => {
let checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
resolve();
}
}, 100); // Check every 100 milliseconds
});
// Setup and use AddShoppersConversion
const itemsData = buildItemsData();
const orderData = buildOrderData();
// Now define the AddShoppersConversion variable with all required data
window.AddShoppersConversion = {
order_id: orderData.order_id,
value: orderData.revenue,
email: {{ customer.email | json }}
};
// Now call track_conv with the defined AddShoppersConversion variable
if (window.AddShoppersWidget && window.AddShoppersWidget.track_conv) {
window.AddShoppersWidget.track_conv();
} else {
console.error('AddShoppersWidget.track_conv is not available.');
}
}
loadAndExecuteAddShoppers();
</script>
<!-- END AddShoppers Code -->
<!-- BEGIN: Taboola Code -->
<script type='text/javascript'>
async function loadAndExecuteTaboola() {
var taboolaPixelId = "{{ taboolaPixelId | default: '' }}" || "";
if (!taboolaPixelId) return;
// Load the Taboola script
await new Promise((resolve, reject) => {
var script = document.createElement("script");
script.async = true;
script.src = `//cdn.taboola.com/libtrc/unip/${taboolaPixelId}/tfa.js`;
script.id = 'tb_tfa_script';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
// Check for availability of buildItemsData and buildOrderData functions
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
// Wait for buildItemsData and buildOrderData to be available
let checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
// Both build functions are available, proceed with Taboola tracking
const orderData = buildOrderData();
window._tfa = window._tfa || [];
window._tfa.push({notify: 'event', name: 'page_view', id: taboolaPixelId});
window._tfa.push({
notify: 'event',
name: 'Purchase_Event',
id: taboolaPixelId,
revenue: orderData.revenue,
currency: orderData.currency,
orderid: orderData.order_id,
quantity: orderData.order_total_product_count
});
}
}, 100); // Check every 100 milliseconds
}
loadAndExecuteTaboola();
</script>
<!-- END: Taboola Code -->
<!-- BEGIN: Criteo Code -->
<script>
async function loadAndExecuteCriteo() {
var criteoPixel = "{{ criteoPixel | default: '' }}" || "";
if (!criteoPixel) return;
// Dynamically load the Criteo script
await new Promise((resolve, reject) => {
var ldScript = document.createElement('script');
ldScript.type = 'text/javascript';
ldScript.async = true;
ldScript.src = '//static.criteo.net/js/ld/ld.js';
ldScript.onload = resolve;
ldScript.onerror = reject;
document.head.appendChild(ldScript);
});
// Wait for buildItemsData and buildOrderData to be defined
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
let checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
// Now that both functions are available, proceed with building Criteo items
const itemsData = buildItemsData();
const orderData = buildOrderData();
// Construct Criteo items from itemsData
var criteo_items = itemsData.map(item => ({
id: item.product_id,
price: item.price,
quantity: item.quantity
}));
var site_type = /iPad/.test(navigator.userAgent) ? "t" : /Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Silk/.test(navigator.userAgent) ? "m" : "d";
window.criteo_q = window.criteo_q || [];
window.criteo_q.push(
{ event: "setAccount", account: criteoPixel },
{ event: "setSiteType", type: site_type },
{ event: "setEmail", email: "{{ customer.email | remove: ' ' | strip_newlines | downcase | md5 }}" },
{ event: "trackTransaction", ecpplugin: "shopify", id: orderData.order_id, deduplication: 1, new_customer: 1, product: criteo_items }
);
}
}, 100); // Check every 100 milliseconds
}
loadAndExecuteCriteo();
</script>
<!-- END: Criteo Code -->
<!-- BEGIN: Grin Code -->
<script>
async function loadAndTrackGrin() {
var grinPixelId = "{{ grinPixelId | default: '' }}" || "";
if (!grinPixelId) return;
// Load Grin script
await new Promise((resolve, reject) => {
var script = document.createElement('script');
script.src = 'https://' + grinPixelId + '.cloudfront.net/js/grin-sdk.js';
script.async = true;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
// Function to check both buildItemsData and buildOrderData availability
function areBuildFunctionsAvailable() {
return typeof buildItemsData === 'function' && typeof buildOrderData === 'function';
}
// Wait for buildItemsData and buildOrderData to be defined
await new Promise(resolve => {
const checkInterval = setInterval(() => {
if (areBuildFunctionsAvailable()) {
clearInterval(checkInterval);
resolve();
}
}, 100); // Check every 100 milliseconds
});
// Both buildItemsData and buildOrderData functions are now available
const itemsData = buildItemsData();
const orderData = buildOrderData();
// Now, you can use itemsData and orderData to track conversion with Grin
var order_number = orderData.order_id,
order_name = orderData.order_name,
amount = orderData.revenue,
currency = orderData.currency;
if (window.Grin) {
Grin.push(['conversion', amount, {order_number: order_number, name: order_name, currency: currency}]);
}
}
loadAndTrackGrin();
</script>
<!-- END: Grin Code -->
{% endif %}
<!-- END: Tracking Pixels that should only fire once for first page load -->