DevCEDTeam / CED

0 stars 0 forks source link

Step 3: Deploy the Cloud Function #4

Open DevCEDTeam opened 1 year ago

DevCEDTeam commented 1 year ago

NA

DevCEDTeam commented 1 year ago

To create an image pixel for email tracking, you can follow these instructions:

Step 1: Set up a Google Cloud Project

Step 2: Enable the necessary APIs

Step 3: Create a Cloud Storage bucket

Step 4: Write the Cloud Function code

const { Storage } = require('@google-cloud/storage');
const crypto = require('crypto');

const storage = new Storage();

exports.trackEmailOpen = (req, res) => {
  const trackingCode = generateTrackingCode();

  const bucketName = 'your-bucket-name'; // Replace with your Cloud Storage bucket name
  const fileName = `${trackingCode}.png`;

  const file = storage.bucket(bucketName).file(fileName);
  const stream = file.createWriteStream({
    resumable: false,
    contentType: 'image/png',
    public: true,
    metadata: {
      metadata: {
        trackingCode: trackingCode
      }
    }
  });

  stream.end(Buffer.from([]));

  res.status(200).send(trackingCode);
};

function generateTrackingCode() {
  const codeLength = 12;
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let code = '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    code += characters.charAt(randomIndex);
  }
  return code;
}

Make sure to replace 'your-bucket-name' with the name of the Cloud Storage bucket you created in Step 3.

Step 5: Deploy the Cloud Function

gcloud functions deploy trackEmailOpen --runtime nodejs14 --trigger-http --allow-unauthenticated

This command deploys the trackEmailOpen function as an HTTP-triggered Cloud Function and allows unauthenticated access to it. Adjust the options as per your requirements.

Step 6: Obtain the tracking URL

Step 7: Insert the tracking pixel in your email template

Step 8: Track email opens

To complete the step of tracking email opens, you can modify the Cloud Function code to integrate with Google Analytics. Here's an example of how you can achieve this:

const { Storage } = require('@google-cloud/storage');
const crypto = require('crypto');
const uaParser = require('ua-parser-js');
const { google } = require('googleapis');

const storage = new Storage();

exports.trackEmailOpen = async (req, res) => {
  const trackingCode = generateTrackingCode();

  const bucketName = 'your-bucket-name'; // Replace with your Cloud Storage bucket name
  const fileName = `${trackingCode}.png`;

  const file = storage.bucket(bucketName).file(fileName);
  const stream = file.createWriteStream({
    resumable: false,
    contentType: 'image/png',
    public: true,
    metadata: {
      metadata: {
        trackingCode: trackingCode
      }
    }
  });

  stream.end(Buffer.from([]));

  // Track the email open event in Google Analytics
  const ua = uaParser(req.headers['user-agent']);
  const client = await google.analytics('v3');

  const analyticsParams = {
    v: '1', // API version
    tid: 'UA-XXXXXXXXX-X', // Replace with your Google Analytics tracking ID
    cid: trackingCode, // Use the tracking code as the client ID
    t: 'event', // Event hit type
    ec: 'Email', // Event category
    ea: 'Open', // Event action
    el: 'Email Open', // Event label
    ua: `${ua.browser.name} ${ua.browser.version}`, // User agent
    dr: req.query.referrer || '', // Referrer
    uip: req.ip // IP address
  };

  await client.data.ga.send(analyticsParams);

  res.status(200).send(trackingCode);
};

function generateTrackingCode() {
  const codeLength = 12;
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let code = '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    code += characters.charAt(randomIndex);
  }
  return code;
}

In the code above, we've made the following changes:

  1. Added the ua-parser-js package to parse the user agent header and extract browser details.
  2. Imported the necessary googleapis package to interact with the Google Analytics API.
  3. Added the trackEmailOpen function to handle email open events.
  4. Integrated the Google Analytics reporting API to send an event hit when an email is opened. Replace 'UA-XXXXXXXXX-X' with your actual Google Analytics tracking ID.
  5. Extracted the referrer from the query parameters (req.query.referrer) if provided.
  6. Included the user agent (ua.browser.name and ua.browser.version) and IP address (req.ip) in the Google Analytics event parameters.

With these modifications, the Cloud Function will not only create the image pixel in Cloud Storage but also track email opens using Google Analytics.

Remember to redeploy the Cloud Function with the updated code using the gcloud functions deploy command.