DevCEDTeam / CED

0 stars 0 forks source link

Step 3: Configure Google Analytics for tracking #3

Open DevCEDTeam opened 1 year ago

DevCEDTeam commented 1 year ago

Task # 1

Set up a Google Analytics account if you don't have one already. Create a new property to track the email events. Add custom dimensions to track additional information like device and browser details.

  1. Set up tags, triggers, and variables in Google Tag Manager to capture events like email opens and webhook unsubscriptions. You can use the unique tracking pixel URL as the trigger for email opens.
DevCEDTeam commented 1 year ago

Task # 2

Apologies for the confusion in my previous responses. Let's go through the revised approach to meet the assignment objectives:

Step 1: Set up a Google Cloud Project and Google Analytics Property

Step 2: Add Custom Dimensions to Google Analytics

Step 3: Create a Cloud Function to generate tracking pixel Here's an example implementation using Node.js:

const { createCanvas, loadImage } = require('canvas');
const crypto = require('crypto');

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;
}

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

  const canvas = createCanvas(1, 1);
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, 1, 1);

  const buffer = canvas.toBuffer('image/png');
  res.set('Content-Type', 'image/png');
  res.send(buffer);

  // Store the trackingCode or use it to associate information with the email address
  console.log(`Generated tracking code: ${trackingCode}`);
};

Step 4: Configure Google Analytics for tracking

Step 5: Deploy the Cloud Function

gcloud functions deploy generateTrackingPixel --runtime nodejs14 --trigger-http

Step 6: Use the tracking pixel in emails

Step 7: Test and track email events

I hope this revised approach meets the assignment requirements. Let me know if you have any further questions or need additional assistance!

DevCEDTeam commented 1 year ago

Task # 3

Certainly! Configuring the pixel data script involves setting up Google Analytics to capture the required information when the tracking pixel is loaded. Here's a step-by-step guide to configure the pixel data script:

  1. Set up Google Analytics:

    • Sign in to your Google Analytics account or create a new one.
    • Create a new property specifically for tracking email events.
    • Obtain the tracking ID associated with the property.
  2. Add Custom Dimensions:

    • In your Google Analytics property settings, navigate to "Custom Definitions" and click on "Custom Dimensions".
    • Click on "New Custom Dimension" and define the dimensions you want to track, such as device and browser information.
    • Make note of the index assigned to each custom dimension. You will need these indices later.
  3. Configure Google Tag Manager:

    • Sign in to your Google Tag Manager account or create a new one.
    • Create a new Tag in your desired container to capture the email open event.
    • Select the appropriate trigger for the Tag, which could be the URL of the tracking pixel.
    • Set up variables to capture the necessary information, such as the tracking code and custom dimensions.
    • Configure the Tag to send the event data to Google Analytics.
    • Save and publish your changes in Google Tag Manager.
  4. Modify the Cloud Function:

    • Update the generateTrackingPixel Cloud Function to include the necessary information in the tracking pixel response.
    • To capture custom dimensions, you need to modify the Cloud Function to send measurement protocol requests to Google Analytics.
    • Install the axios library (using npm install axios) to make HTTP requests from the Cloud Function.

Here's an example of how to modify the generateTrackingPixel Cloud Function to include custom dimensions:

const axios = require('axios');

exports.generateTrackingPixel = async (req, res) => {
  const trackingCode = generateTrackingCode();
  const trackingUrl = `https://www.google-analytics.com/collect?v=1&t=event&tid=[YOUR_TRACKING_ID]&cid=${trackingCode}&ec=email&ea=open`;

  try {
    await axios.post(trackingUrl);
  } catch (error) {
    console.error('Failed to send event data to Google Analytics:', error);
  }

  const canvas = createCanvas(1, 1);
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, 1, 1);

  const buffer = canvas.toBuffer('image/png');
  res.set('Content-Type', 'image/png');
  res.send(buffer);

  console.log(`Generated tracking code: ${trackingCode}`);
};

Make sure to replace [YOUR_TRACKING_ID] in the trackingUrl variable with the actual Google Analytics tracking ID obtained in step 1.

In the modified Cloud Function, the axios.post() call sends a measurement protocol request to Google Analytics to track the email open event. You can customize this request to include additional information like custom dimensions. For example, to include the device and browser dimensions, you would modify the trackingUrl as follows:

const trackingUrl = `https://www.google-analytics.com/collect?v=1&t=event&tid=[YOUR_TRACKING_ID]&cid=${trackingCode}&ec=email&ea=open&cd1=${deviceInfo}&cd2=${browserInfo}`;

In this example, cd1 and cd2 are placeholders for custom dimension indices 1 and 2, respectively. Replace deviceInfo and browserInfo with the actual values obtained from the email client's user-agent.

Remember to redeploy the Cloud Function after making these modifications.

That's how you configure the pixel

DevCEDTeam commented 1 year ago

Task # 4

To track additional information like device and browser details, and unsubscription HTML link from a Google Cloud SQL database list, you can modify the Cloud Function code as follows:

const { createCanvas } = require('canvas');
const crypto = require('crypto');
const { Pool } = require('pg');

const pool = new Pool({
  // Configure your Google Cloud SQL database connection details
  user: '[DB_USER]',
  password: '[DB_PASSWORD]',
  host: '[DB_HOST]',
  database: '[DB_NAME]',
  port: '[DB_PORT]'
});

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;
}

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

  const device = req.headers['user-agent'];
  const browser = req.query.browser || '';
  const unsubscriptionLink = req.query.unsublink || '';

  const canvas = createCanvas(1, 1);
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, 1, 1);

  const buffer = canvas.toBuffer('image/png');
  res.set('Content-Type', 'image/png');
  res.send(buffer);

  const insertQuery = 'INSERT INTO email_tracking (tracking_code, device, browser, unsubscription_link) VALUES ($1, $2, $3, $4)';
  const insertValues = [trackingCode, device, browser, unsubscriptionLink];

  try {
    await pool.query(insertQuery, insertValues);
  } catch (error) {
    console.error('Failed to insert tracking data:', error);
  }

  console.log(`Generated tracking code: ${trackingCode}`);
};

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

  1. Added the necessary imports and configured the PostgreSQL connection using pg.Pool to interact with the Google Cloud SQL database.
  2. Extracted the device and browser information from the request headers.
  3. Extracted the unsubscriptionLink from the query parameters.
  4. Modified the INSERT query to include the new custom dimensions (device, browser, unsubscription_link) and their corresponding values.
  5. Executed the INSERT query to store the tracking data in the Google Cloud SQL database.

Make sure to replace the placeholder values ([DB_USER], [DB_PASSWORD], [DB_HOST], [DB_NAME], [DB_PORT]) with your actual database connection details.

By implementing these changes, you can track the device, browser, and unsubscription link information along with the email tracking code in the Google Cloud SQL database for further analysis and reporting.

Remember to deploy the updated Cloud Function to apply these changes.

DevCEDTeam commented 1 year ago

Task # 5

Pixel manipulation with canvas