Applovin Pixel 自定义代码接入指引(旧版)

一、官方文档

https://developers.applovin.com/zh/

二、兼容版本

主题1.0, 主题2.0, 主题2.1

三、操作流程

1. 在 Shopline使用「自定义代码」应用,点击添加代码

注意:开启前请把原来的多平台Pixel安装助手中Applovin的配置关掉

2. 触发页面全选,将以下代码复制进去

注意:

  1. 代码中 AXON_EVENT_KEY 部分中填入自己的ID

  2. 分类ID,去下面网址找,覆盖代码中 166 的部分(166默认是服饰与饰品)

https://developers.applovin.com/zh/ecommerce/events-and-objects/#category-ids

代码:

<script>

    var AXON_EVENT_KEY="test123123123123123123123123123123";
    var item_category_id = 166;

    !function(e,r){var t=["https://s.axon.ai/pixel.js","https://c.albss.com/p/l/loader.iife.js"];if(!e.axon){var a=e.axon=function(){a.performOperation?a.performOperation.apply(a,arguments):a.operationQueue.push(arguments)};a.operationQueue=[],a.ts=Date.now(),a.eventKey=AXON_EVENT_KEY;for(var n=r.getElementsByTagName("script")[0],o=0;o<t.length;o++){var i=r.createElement("script");i.async=!0,i.src=t[o],n.parentNode.insertBefore(i,n)}}}(window,document);
    axon("init");
    function getCookie(name) {
        var cookieArray = document.cookie.split('; ');
        var cookie = cookieArray.find(function(cookie) {
            var cookieName = cookie.split('=')[0]; 
            return cookieName === name;
        });
        return cookie ? cookie.split('=')[1] : null; 
    }
    function getRootDomain() {
        var url = new URL(window.location.href);
        var hostname = url.hostname;
        var parts = hostname.split('.');
        if (parts.length > 2) {
            if (parts[parts.length - 2] === 'co' && (parts[parts.length - 1] === 'uk' || parts[parts.length - 1] === 'jp')) {
                return parts.slice(-2).join('.');
            } else if (parts[parts.length - 2] === 'com' && parts[parts.length - 1] === 'au') {
                return parts.slice(-2).join('.');
            } else {
                return parts.slice(-2).join('.');
            }
        } else {
            return hostname; 
        }
    }
    if (!getCookie('axwrt') && getCookie('_axwrt')) {
        const now = new Date();
        now.setFullYear(now.getFullYear() + 1)
        document.cookie = "axwrt=" + getCookie('_axwrt') + "; Expires=" + now + "; Domain=." + getRootDomain() + "; Path=/; SameSite=Lax;";
    }

    // page_view
    console.log('axon page_view')
    axon("track", 'page_view');

    // add_to_cart
    // fetch
    (function() {
        const originalFetch = window.fetch;
        window.fetch = function(...args) {
            return new Promise((resolve, reject) => {
                originalFetch.apply(this, args)
                    .then(response => {
                        const clone = response.clone();
                        if (
                            ((args[0] && args[0].url && args[0].url.includes("/cart/add")) || (args[0] && args[0] === "/cart/add")) &&
                            (!args[0].url || !args[0].url.includes("_xcotton"))) {
                            clone.json().then(data => {
                                console.log('axon add_to_cart fetch');
                                axon("track", "add_to_cart", {
                                    "currency": "{{ @root.storeInfo.currency }}",
                                    "items": [
                                        {
                                            "item_id": data.product_id,
                                            "item_name": data.product_title,
                                            "price": data.price,
                                            "quantity": data.quantity,
                                            "item_variant_id": data.variant_id,
                                            "image_url": data.image,
                                            "item_category_id": item_category_id
                                        }
                                    ]
                                });
                            });
                        }
                        
                        resolve(response);
                    })
                    .catch(error => {
                        reject(error);
                    });
            });
        };

        // xhr
        const originalOpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
            this.addEventListener('load', function() {
                if (method === 'POST' && url === '/leproxy/api/carts/cart') {
                    try {
                        const response = JSON.parse(this.responseText);
                        console.log('axon add_to_cart xhr');
                        axon("track", "add_to_cart", {
                            "currency": "{{ @root.storeInfo.currency }}",
                            "items": [
                                {
                                    "item_id": response.data.itemDetail.spuId,
                                    "item_name": response.data.itemDetail.name,
                                    "price": (response.data.itemDetail.price / 100).toFixed(2),
                                    "quantity": response.data.itemDetail.num,
                                    "item_variant_id": response.data.itemDetail.skuId,
                                    "image_url": response.data.itemDetail.image,
                                    "item_category_id": item_category_id
                                }
                            ]
                        });
                    } catch (error) {
                        console.error("Error processing add_to_cart request", error);
                    }
                }
            });
            originalOpen.apply(this, arguments);
        };

        const originalSend = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.send = function(body) {
            const method = this._method;
            const url = this._url;
            if (method === 'POST' && url === '/leproxy/api/carts/cart/batch/add') {
                console.log('axon add_to_cart xhr');
                try {
                    const bodyData = JSON.parse(body);
                    if (bodyData && bodyData.items && Array.isArray(bodyData.items)) {
                        const axonItems = bodyData.items.map(item => ({
                            "item_id": item.productSeq,
                            "item_name": item.productName,
                            "price": (item.productPrice / 100).toFixed(2),
                            "quantity": item.productNum,
                            "item_variant_id": item.productSku,
                            "image_url": "https://img.myshopline.com/image/official/e46e6189dd5641a3b179444cacdcdd2a.png", // No image URL in the provided data
                            "item_category_id": item_category_id
                        }));
                        axon("track", "add_to_cart", {
                            "currency": "{{ @root.storeInfo.currency }}",
                            "items": axonItems
                        });
                    }
                } catch (error) {
                    console.error("Error processing add_to_cart batch request", error);
                }

            }

            return originalSend.apply(this, arguments);
        };
        
    })();
    
    {{#if @root.product}}
        console.log('axon view_item')
        try {
            axon("track", "view_item", {
                "currency": "{{ @root.storeInfo.currency }}",
                "items": [
                    {
                        "item_id": "{{product.id}}",
                        "item_name": "{{product.title}}",
                        "price": {{ divide product.first_available_variant.price 100}},
                        "quantity": 1,
                        "item_variant_id": "{{ product.first_available_variant.id }}",
                        "image_url": "{{ product.featured_image.src }}",
                        "item_category_id": item_category_id
                    }
                ]
            });
        } catch(e){ console.error(e); }
    {{/if}}

    {{#if @root.checkout}}
        console.log('axon checkout')
        try {
            axon("track", "begin_checkout",{
                "currency": "{{ @root.storeInfo.currency }}",
                "value": {{ divide checkout.total_price 100 }},
                "items": [
                            {{#each checkout.productInfos }}
                                {
                                    item_id: "{{ productSeq }}",
                                    item_name: "{{ productName }}",
                                    item_variant_id: "{{ productSku }}",
                                    price: {{ divide finalPrice 100 }},
                                    quantity: {{ productNum }},
                                    image_url: "{{ productImage }}",
                                    item_category_id: item_category_id
                                },
                            {{/each}}
                        ]
            })
        } catch(e){ console.error(e); }
    {{/if}}
    
    {{#if @root.thankyou}}
        console.log('axon purchase')
        document.addEventListener('DOMContentLoaded', function() {
            try {
                axon("track", "purchase", {
                    "currency": "{{ @root.storeInfo.currency }}",
                    "value": {{ divide thankyou.priceInfo.productAmount 100 }},
                    "transaction_id": "{{ thankyou.basicInfo.appOrderSeq }}",
                    "user_id": "{{ thankyou.buyerInfo.buyerId }}",
                    "shipping": {{ divide thankyou.priceInfo.expressAmount 100 }},
                    "tax": {{ divide thankyou.priceInfo.taxAmount 100 }},
                    "items": [
                        {{#each thankyou.orderItemList }}
                            {
                                item_id: "{{ productSeq }}",
                                item_name: "{{ productName }}",
                                item_variant_id: "{{ productSku }}",
                                price: {{ divide finalPrice 100 }},
                                quantity: {{ productNum }},
                                image_url: "{{ productImage }}",
                                item_category_id: item_category_id
                            },
                        {{/each}}
                    ]
                });
            } catch(e){ console.error(e); }
        });
    {{/if}}

</script>