用於混合實施的 Einstein Activities

借助 報告 & 儀錶板 ,您可以根據自己的 B2C Commerce 數據確定隨時間變化的趨勢並做出更明智的業務決策。

Reports & Dashboards 分析只能從 Web 適配器日誌或 Einstein Activities API 派生。默認情況下,SFRA 和 SiteGenesis 分析數據儲存在 Web 適配器日誌中,而 PWA Kit 將分析數據發送到 Einstein Activities API。

如果您追求 的是混合實現 ,其中某些頁面由 PWA Kit 提供支援,而其他頁面由 SFRA 或 SiteGenesis 提供支援,並且您希望在整個網站中使用報告 & 儀錶板,則必須更新 SFRA 或 SiteGenesis 實現以使用 Einstein Activities API。這可確保 API 捕獲完整的購物者體驗,無論購物者是在 PWA Kit、SFRA 還是 SiteGenesis 中。

只有現有客戶才能存取此頁面上的某些連結。造訪 Salesforce Commerce Cloud GitHub 存放庫和存取,以瞭解有關如何存取 Commerce Cloud 存放庫的資訊。

Tip

本指南向您 展示如何將 Einstein Activities API 與 SFRA 的結帳 集成,以便它發送與 PWA Kit 結帳相同的活動。

如果分階段部署在 SFRA 或 SiteGenesis 上有將分析資料發送到 Web 適配器日誌的其他頁面,則對於這些頁面,您可以遵循類似於本指南中描述的過程。查看 Retail React App 中的相應頁面,並觀察它們發送了哪些活動。然後,您需要在 SFRA 或 SiteGenesis 頁面上發送相同的活動。作為資源,此 Einstein 活動概述 向您展示了這些活動應該在哪裡使用。

不正式支援將 SiteGenesis 與可組合網店結合使用的實施。

Note

關於程式碼範例 

請小心整合此處提供的程式碼範例,請一律先徹底測試您的程式碼,再將其推送至 Production 環境。

要新增至現有程式碼的列會以加號 (+) 標示,要刪除的列則以減號 (-) 標示。

在執行本教學的命令之前,請以實際值取代預留位置。預留位置的格式為:$PLACEHOLDER

步驟 1:更新結帳控制器 

首先請更新結帳控制器,加入目前的購物車 ID。

1res.render('checkout/checkout', {
2+   basketId: currentBasket.UUID,
3    order: orderModel,
4    customer: accountModel,
5    ...
6});

步驟 2:更新結帳範本 

更新用於結帳的 ISML 範本。此變更讓瀏覽器可以使用購物車 ID、商品和總計。

1-    <div id="checkout-main" class="container data-checkout-stage <isif condition="${pdict.order.usingMultiShipping && pdict.order.shipping.length > 1}">multi-ship</isif>" data-customer-type="${pdict.customer.registeredUser ? 'registered' : 'guest'}" data-checkout-stage="${pdict.currentStage}" data-checkout-get-url="${URLUtils.https('CheckoutServices-Get')}">
2+    <div id="checkout-main" class="container data-checkout-stage <isif condition="${pdict.order.usingMultiShipping && pdict.order.shipping.length > 1}">multi-ship</isif>" data-customer-type="${pdict.customer.registeredUser ? 'registered' : 'guest'}" data-checkout-stage="${pdict.currentStage}" data-checkout-get-url="${URLUtils.https('CheckoutServices-Get')}" data-checkout-price-total="${pdict.order.priceTotal}" data-checkout-items="${JSON.stringify(pdict.order.items)}" data-basket-id="${pdict.basketId}">

步驟 3:建立 Helper 

建立一個名為 js/einsteinHelpers.js 的 JavaScript 檔案,當中包含 Helper 函式:

請務必將預留位置 $YOUR_SITE_ID$YOUR_CLIENT_ID 替換為實際值。

Important

1'use strict';
2
3/**
4 * Get the value of a cookie
5 * Source: https://gist.github.com/wpsmith/6cf23551dd140fb72ae7
6 * @param  {string} name  The name of the cookie
7 * @return {string | undefined}       The cookie value
8 */
9function getCookie(name) {
10    var value = '; ' + document.cookie;
11    var parts = value.split('; ' + name + '=');
12    var result;
13
14    if (parts.length === 2) {
15        result = parts.pop().split(';').shift();
16    }
17    return result;
18}
19
20/**
21 * Fire a given Einstein activity with the provided data.
22 *
23 * @param {string} name - The name of the activity.
24 * @param {Object} data - The activity payload.
25 */
26function fireEinsteinActivity(name, data) {
27    // NOTE: These should be placed in the custom preferences of BM. This will help
28    // avoid any code deployments if you need to change these values.
29    // NOTE 2: this is _Einstein_ site id (not the same as SFRA one like RefArch).
30    var SITE_ID = '$YOUR_SITE_ID';
31    var CLIENT_ID = '$YOUR_CLIENT_ID';
32    // Reports & Dashboards will only show data that's been tagged as `prd` (production)
33    var INSTANCE_TYPE = 'prd';
34
35    // Assign the realm to the data.
36    var activityData = Object.assign(data, {
37        realm: SITE_ID.split('-')[0],
38        instanceType: INSTANCE_TYPE
39    });
40
41    var userId = data.userId;
42    var cookieId = data.cookieId;
43
44    // Apply payload information for logged in users.
45    if (userId) {
46        activityData = Object.assign(activityData, {
47            userId: userId
48        });
49    }
50
51    if (cookieId) {
52        activityData = Object.assign(activityData, {
53            cookieId: cookieId
54        });
55    }
56
57    var url =
58            'https://api.cquotient.com/v3/activities' +
59                '/' + SITE_ID +
60                '/' + name;
61
62    try {
63        fetch(url, {
64            headers: {
65                'Content-Type': 'application/json',
66                'x-cq-client-id': CLIENT_ID
67            },
68            method: 'POST',
69            body: JSON.stringify(activityData)
70        });
71    } catch (e) {
72        console.error(e);
73    }
74}
75
76var exports = {
77    fireEinsteinActivity: fireEinsteinActivity,
78    getCookie: getCookie
79};
80
81module.exports = exports;

步驟 4:記錄活動 

更新 checkout.js 指令碼以記錄活動。您必須將此呼叫新增至結帳指令碼頂端的 require(),而且它必須出現在任何現有的匯入之後。

1var einsteinHelpers = require('../einsteinHelpers');

當結帳階段變更時,觸發 checkoutStep 活動。請將以下程式碼附加到 updateUrl 方法:

1/**
2 * @returns {boolean} whether the current customer is registered or not
3 */
4function isRegisteredCustomer() {
5    return $('.data-checkout-stage').data('customer-type') === 'registered';
6}
7
8/**
9 * Get the cookieId, which is a unique identifier used for linking subsequent activities to the same user.
10 * If the cookieId is not defined, then Reports & Dashboards will treat the activity as coming from an anonymous user.
11 * @returns {string | undefined} value of the cookieId param for Einstein Activities API
12 */
13function getCookieId() {
14    var siteId = window.CQuotient && window.CQuotient.siteId;
15    // This usid cookie is set by either PWA or plugin_slas
16    return einsteinHelpers.getCookie('usid_' + siteId) || einsteinHelpers.getCookie('usid') || undefined;
17}
18
19/**
20 * Get the userId, which is for linking registered users across different devices.
21 * @returns {string | undefined} value of the userId param for Einstein Activities API
22 */
23function getUserId() {
24    var siteId = window.CQuotient && window.CQuotient.siteId;
25    // This enc_user_id is set by PWA
26    return window.localStorage.getItem('enc_user_id_' + siteId) || window.localStorage.getItem('enc_user_id') || undefined;
27}
28
29/**
30 * Updates the URL to determine stage
31 * @param {number} currentStage - The current stage the user is currently on in the checkout
32 */
33function updateUrl(currentStage) {
34    // ...
35
36    var cookieId = getCookieId();
37    var userId = isRegisteredCustomer() ? getUserId() : undefined;
38
39    einsteinHelpers.fireEinsteinActivity('checkoutStep', {
40        basketId: $('#checkout-main').data('basket-id'),
41        stepName: checkoutStages[currentStage],
42        stepNumber: currentStage,
43        cookieId: cookieId,
44        userId: userId
45    });
46}

updateUrl 方法中觸發 checkoutStep 活動,可確保從一個結帳階段到下一個 (或上一個) 階段的任何轉換都受到追蹤。

Note

在結帳程式碼的 initialize 函式尾端觸發 beginCheckout 活動:

1//
2// Send Einstein `beginCheckout` activity
3//
4// Parse total amount value
5var amount = $('#checkout-main').data('checkout-price-total');
6amount = Number(amount.replace(/[^0-9.-]+/g, ''));
7
8var products = $('#checkout-main')
9    .data('checkout-items')
10    .items.map(function (item) {
11        return {
12            id: item.id,
13            price: Number(item.priceTotal.price.replace(/[^0-9.-]+/g, '')),
14            quantity: item.quantity
15        };
16    });
17
18var cookieId = getCookieId();
19var userId = isRegisteredCustomer() ? getUserId() : undefined;
20
21einsteinHelpers.fireEinsteinActivity('beginCheckout', {
22    products: products,
23    amount: amount,
24    cookieId: cookieId,
25    userId: userId
26});

beginCheckout 結帳期間,每次頁面載入僅觸發一次活動。活動資料準備會自動處理。

Note

就這樣!您已成功將 Einstein Activities 與 SFRA 的結帳集成。要完成 Reports amp &的設置,請執行以下作:儀錶板,完成 Reports &儀錶板

也請參閱