How to push notification "Firebase Cloud Messaging" for Shopify

At step Install custom app, please contact us before taking the step.

I. Create a Firebase project

1. Create a project

- Log in Firebase and create a new project

- Enter the name of project and click "Continue"

- Accept the privacy and create project

2. Build "Cloud Messaging"

- Click dropdown "Build" and select "Cloud Messaging"

- Add firebase to your web app

- Click "Register app"

- Copy "firebaseConfig" and Click "Continue to console"

- Firebase config:

apiKey: "AIzaSyBUJrgxGjFUWld-q_zr_cVzrN9IaB4KfmE",
  authDomain: "fir-clound-messaging-ab666.firebaseapp.com",
  projectId: "fir-clound-messaging-ab666",
  storageBucket: "fir-clound-messaging-ab666.appspot.com",
  messagingSenderId: "974234323980",
  appId: "1:974234323980:web:03d23bee74ed48eb5c7229",
  measurementId: "G-EE955NEBKJ"

- Click settings icon and select "Project settings"

- Click "Cloud Messaging"

- Enable Cloud Messaging API

- After that, we have the data of Server Key

3. Add script to source code of website

- Copy and paste these scripts into the bottom of your <body> tag

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
<script>
  var _cdpGetCookie = function (cookieName) {
    var cookiePattern = new RegExp("(^|;)[ ]*" + cookieName + "=([^;]*)");
    cookieMatch = cookiePattern.exec(document.cookie);
    return cookieMatch ? window.decodeURIComponent(cookieMatch[2]) : 0;
  };

  var _cdpSetCookie = function (cookieName, value, msToExpire, path, domain, secure) {
    var expiryDate;
    if (msToExpire != undefined) {
      expiryDate = new Date();
      expiryDate.setTime(expiryDate.getTime() + msToExpire);
    }
    var valueData = value + "";
    if (isNaN(value)) {
      valueData = window.encodeURIComponent(value);
    }
    var cookieInfo =
      cookieName +
      "=" +
      valueData +
      (msToExpire ? ";expires=" + expiryDate.toGMTString() : "") +
      ";path=" +
      (path || "/") +
      (domain ? ";domain=" + domain : "") +
      (secure ? ";secure" : "");
    document.cookie = cookieInfo;
  };

  var _cdpGetLeadTime = function () {
    var d = new Date();
    var m = d.getMonth() + 1;
    if (parseInt(m) < 10) {
      m = "0" + m;
    }

    var day = d.getDate();
    if (parseInt(day) < 10) {
      day = "0" + day;
    }

    var hour = d.getHours();
    if (parseInt(hour) < 10) {
      hour = "0" + hour;
    }

    var min = d.getMinutes();
    if (parseInt(min) < 10) {
      min = "0" + min;
    }

    var sec = d.getSeconds();
    if (parseInt(sec) < 10) {
      sec = "0" + sec;
    }

    var leadTime = d.getFullYear() + "-" + m + "-" + day + " " + hour + ":" + min + ":" + sec;

    return leadTime;
  };

  var _cdpTrackFirebaseDetail = function (clientToken) {
    console.log("CDP firebase clientToken : " + clientToken);
    var props = {
      extra: {
        identify_event: "firebase_subscribed",
        uid_firebase: clientToken,
        firebase_time: _cdpGetLeadTime(),
      },
    };

    var expireTime = 60 * 60 * 1000; // 60p
    var cookieName = "_uid_firebase";

    var cookieToken = _cdpGetCookie(cookieName);
    if (!cookieToken) {
      if (typeof web_event.track == "function") {
        web_event.track("firebase", "subscribed", props);
      } else {
        web_event.queue.push(["track", "firebase", "subscribed", props]);
      }
    } else if (cookieToken !== clientToken) {
      props.extra.identify_event = "firebase_refresh";

      if (typeof web_event.track == "function") {
        web_event.track("firebase", "subscribed", props);
      } else {
        web_event.queue.push(["track", "firebase", "subscribed", props]);
      }
    }

    _cdpSetCookie(cookieName, clientToken, expireTime, "/", "", 0);
  };

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  var firebaseConfig = {
    *firebaseConfig*
  };

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
  const messaging = firebase.messaging();
  let enableForegroundNotification = true;

  if ("serviceWorker" in navigator) {
    window.addEventListener("load", () => {
      navigator.serviceWorker
        .register(
          "/apps/firebase-messaging-sw?apiKey=" +
            firebaseConfig.apiKey +
            "&authDomain=" +
            firebaseConfig.authDomain +
            "&projectId=" +
            firebaseConfig.projectId +
            "&storageBucket=" +
            firebaseConfig.storageBucket +
            "&messagingSenderId=" +
            firebaseConfig.messagingSenderId +
            "&appId=" +
            firebaseConfig.appId +
            "&measurementId=" +
            firebaseConfig.measurementId
        )
        .then((register) => {
          messaging.useServiceWorker(register);
          messaging.requestPermission().then(() => {
            messaging.getToken().then((fcmToken) => {
              _cdpTrackFirebaseDetail(fcmToken);

              messaging.onMessage((payload) => {
                console.log("onMessage event fired", payload);
                if (enableForegroundNotification) {
                  console.log(payload);
                  let notification = payload.notification;
                  notification.data = {
                    url: notification.click_action,
                  };
                  navigator.serviceWorker.getRegistrations().then((registration) => {
                    console.log("$$$$,", notification);
                    registration[0].showNotification(notification.title, notification);
                  });
                }
              });
            });
          });
        });
    });
  }
</script>

- *firebaseConfig* is the data of firebase config in section 2

- Install custom app (Contact us before taking this step)

  • At this step, we need you to provide the link of your domain website in Shopify

- We have done with the set up on your website. Next, we will continue with set up in CDP

II. Create destination "Firebase Cloud Messaging"

1. Access the "MARKETING HUB" app and go to the "Destinations" menu

2. Click "+" button and select "Web Push-Notification"

3. Select "Destination catalog": "Firebase Cloud Messaging"

- Get "To Client Tokens"

  • Visit the website, press F12 and go to Console to get "To Client Tokens"

  • Copy "To Client Tokens" and paste to destination setting

  • Click "Save" to save destination

Note: After client finish creating "Firebase Cloud Messaging", Antsomi team will collect the data and update "To Client Tokens" attribute in CDP system.

III. Push "Firebase Cloud Messaging" notification via Journey

1. Access "MARKETING HUB" app and go to "Customer Journey" menu

  • We have 2 channels that supporting to send "Firebase Cloud Messaging". These are "Web Push-Notification" and "Journey Orchestration"

2. Click "+" button to Create Journey, add "Destination" node and select "Firebase Cloud Messaging" destination

  • Fill in the required information

  • Click "Save change" to Save the journey

3. Click Activate to activate the journey

Last updated