Correctly Tracking Marketing Consent State Changes

@Matthew_Crigger this was fun! Sorry this is so verbose but I wanted to to be clear

1.) Checkbox Changed:

// INPUT CHANGED EVENT
analytics.subscribe('input_changed', (event) => {
    // Access the changed input element and its properties
    const element = event.data.element;
    const elementId = element.id;
    const elementValue = element.value;

    // Check if the marketing opt-in checkbox was changed to true
    if (elementId === "contact_marketing_opt_in" && elementValue === "true") {
        
        (async () => {
            await browser.sessionStorage.setItem('checkout_email_opt', true);
            const emailOptStatus = await browser.sessionStorage.getItem('checkout_email_opt');
            console.log("email_opt_set: ",emailOptStatus);
        })();
    }
});

2.) On checkout_start take a look at current opt-in state and store it in session

analytics.subscribe("checkout_started", (event) => {

    // Store the initial email marketing opt-in status at the start of checkout
    const currentStatus = event.data.checkout.buyerAcceptsEmailMarketing || false;
    browser.sessionStorage.setItem('checkout_start_email_opt', currentStatus);

    (async () => {
        const currentStatus = event.data.checkout.buyerAcceptsEmailMarketing || false;
        await browser.sessionStorage.setItem('checkout_start_email_opt', currentStatus);

        const emailOptStatus = await browser.sessionStorage.getItem('checkout_start_email_opt');
        console.log("email_opt_status: ", emailOptStatus);
    })();
});

3.) when on checkout_complete see what the session storage was before, if it is now updated then they opted in from checkout

// CHECKOUT COMPLETED EVENT
analytics.subscribe("checkout_completed", (event) => {
    console.log("checkout_completed: ", event);

    // Check if the email opt-in status changed during checkout
    if (browser.sessionStorage.getItem('checkout_start_email_opt')) {
 
        (async () => {
            const previousEmailStatus = await browser.sessionStorage.getItem('checkout_start_email_opt');
            const currentEmailStatus = event.data.checkout.buyerAcceptsEmailMarketing.toString();

            if (previousEmailStatus != currentEmailStatus) {
                console.log("email_previous_state: ", previousEmailStatus);
                console.log("email_current_state: ", currentEmailStatus);

                // Now you know they opted-in from checkout
                browser.sessionStorage.clear();
            }
        })();
    }
});
2 Likes