DevCEDTeam / CED

0 stars 0 forks source link

Description #29

Open DevCEDTeam opened 1 year ago

DevCEDTeam commented 1 year ago

Email Tracking Events

Proxy Server

Step-by-step guide on how to enable the Cloud Functions API, set up the local development environment, write the entire index.js file, deploy the Cloud Function to Google Cloud, set up Mautic Form event tracking, set up email open pixel tracking, set up a Google Analytics Dashboard, and test the tracking with sample codes. This guide includes the use of a proxy server to track data from email leads to Google Tag Manager. Please note that there may be cases where Google restricts certain scripts from loading, which could affect the appearance or behavior of the embedded form. In such cases, you can try using the manual copy method for the form JavaScript code provided by Mautic, instead of relying on the automatic copy.

Step 1: Enable the Cloud Functions API

  1. Open the Cloud Console: https://console.cloud.google.com/.
  2. Select your project or create a new one.
  3. In the sidebar, click on "APIs & Services" > "Library".
  4. Search for "Cloud Functions API".
  5. Click on "Cloud Functions API" from the results.
  6. Click on the "Enable" button.

Step 2: Set up the local development environment

  1. Install Node.js and npm (Node Package Manager) if you haven't already.
  2. Create a new directory for your project.
  3. Open a terminal or command prompt and navigate to the project directory.
  4. Run the following command to initialize a new Node.js project:
    npm init -y
  5. Install the required dependencies by running the following command:
    npm install axios

Step 3: Write the entire index.js file in the project directory

  1. Create a new file named index.js in your project directory and add the following code:
const { google } = require('googleapis');
exports.sendEmail = async(req,res)=>{
var body = req.body[0]
  var to = body.to[0];
  var arrayBody = to.replace('[','');
  arrayBody = arrayBody.replace(']','');
  arrayBody = arrayBody.split(',');
  var entryArray = []
  arrayBody.forEach(elm =>{
    if(elm.indexOf(']') >-1){
      elm = elm.replace(']','')
    }
    entryArray.push((JSON.parse(elm)).email)
  })

  const oAuth2Client = new google.auth.OAuth2(
    process.env.CLIENT_ID,
    process.env.CLIENT_SECRET,
    process.env.REDIRECT_URI
  );
  const auth = await oAuth2Client.setCredentials({ refresh_token: process.env.REFRESH_TOKEN});
  var gmail = google.gmail({version : 'v1', auth : oAuth2Client})

  if(entryArray.length >24999){
    //split up into smaller tasks and time out for another task in a few minutes to avoid passing the Gmail quota limits
  }
  else{
     //begin email body construction. Feel free to change out the subject directly in the code or by sending a different "Subject" request body parameter from the source (Integromat, Zapier, Etc.)
     const subject = body.Subject;
     const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;

     //send to every email in the list  
    for(i=0;i<entryArray.length;i++){
      try{
        const messageParts = [
          'From: ' + process.env.FROM_EMAIL,
          'To: ' + entryArray[i],
          'Content-Type: text/html; charset=utf-8',
          'MIME-Version: 1.0',
          `Subject: ${utf8Subject}`,
          '',
          body.Body //this is assuming you're sending some html code as a string from your API (Integromat, Zapier Etc). If you want to just write the HTML code directly in here you can do so by wrapping the entire html code as a string
        ];
        const message = messageParts.join('\n');

        // The body needs to be base64url encoded.
        const encodedMessage = Buffer.from(message)
          .toString('base64')
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=+$/, '');

      const response = await gmail.users.messages.send({
        userId: 'me',
        requestBody: {
          raw: encodedMessage,
        },
      });
      console.log(response.data);
      }
      catch(err){
        console.log(err);
      }
    }
  }

  res.sendStatus(200)
}

package.json

{
  "name": "gmail-cloud-func",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "DevCED",
  "license": "ISC",
  "dependencies": {
    "googleapis": "^95.0.0"
  }
}

Note: Replace the placeholders ACTID, EVENTKEY, APIURL, and APIKEY with your actual values.

Step 4: Deploy the Cloud Function to Google Cloud

  1. Open a terminal or command prompt and navigate to your project directory.
  2. Authenticate with Google Cloud by running the following command and following the instructions:
    gcloud auth login
  3. Set your project by running the following command and replacing YOUR_PROJECT_ID with your actual project ID:
    gcloud config set project YOUR_PROJECT_ID
  4. Deploy the Cloud Function by running the following command:
    gcloud functions deploy mauticProxy --runtime nodejs14 --trigger-http --allow-unauthenticated
  5. Once the deployment is successful, note down the URL of the deployed Cloud Function.

Step 5: Set up Mautic Form event tracking

  1. Open Mautic and navigate to the form you want to track.
  2. Go to the "Actions" tab of the form editor.
  3. Add a new action of type "Send HTTP Request".
  4. Set the URL to the URL of your Cloud Function, appended with the following query parameters:
    ?action=trackEvent&email={contactfield=email}&eventName=FormSubmit&eventData=formId:{formid},formName:{formname}
  5. Save the form.

Step 6: Set up email open pixel tracking

  1. In your email template, add an image element with the following source URL:
    https://<your-cloud-function-url>?action=trackEvent&email={contactfield=email}&eventName=EmailOpen&eventData=emailId:{emailid},emailName:{emailname}

    Note: Replace <your-cloud-function-url> with the URL of your Cloud Function.

  2. Set the image dimensions to 1x1 pixel or any desired size.
  3. Save the email template.

Step 7: Set up Google Analytics Dashboard

  1. Open Google Analytics and navigate to your property.
  2. Go to "Customization" > "Dashboards".
  3. Click on "Create" > "Blank Canvas".
  4. Add widgets to your dashboard to visualize the data you want to track.
  5. Save the dashboard.

Step 8: Test the tracking with sample codes

You can test the tracking using the following sample codes and UTM query strings:

Sample code for Mautic form event:

<form action="https://

<your-cloud-function-url>?action=trackEvent" method="GET">
  <input type="hidden" name="eventName" value="FormSubmit">
  <input type="hidden" name="eventData" value="formId:123,formName:ContactForm">
  <!-- Add form fields here -->
  <button type="submit">Submit</button>
</form>

Sample code for email open pixel:

<img src="https://<your-cloud-function-url>?action=trackEvent&eventName=EmailOpen&eventData=emailId:123,emailName:WelcomeEmail" width="1" height="1" alt="Email Open Pixel">

Note: Replace <your-cloud-function-url> with the URL of your Cloud Function.

That's it! You have now set up Mautic Form event tracking, email open pixel tracking, and a Google Analytics Dashboard using Google Cloud Functions with a proxy server. You can further customize and expand the tracking functionality as needed.

DevCEDTeam commented 1 year ago

Mautic Pixel Tracking, Mautic Webhook Transcript, and UTM Transcript

How to install Mautic Pixel Tracking, Mautic Webhook Transcript, and UTM Transcript manually using CLI commands and sample code references:

Please note that these instructions assume you have access to a command-line interface (CLI) and are comfortable running commands and editing files.

  1. Pixel Transcript

To install Mautic Pixel Tracking, follow these steps:

  1. Webhook Transcript

To install Mautic Webhook Transcript, follow these steps:

  1. UTM Transcript

To install Mautic UTM Transcript, follow these steps:

Please note that the above commands assume you are in the root directory of your Mautic installation. Modify the commands accordingly if your installation is located in a different directory.

Remember to customize the settings and configurations based on your specific requirements. The provided CLI commands will assist you in creating the necessary components for Mautic Pixel Tracking, Webhook Transcript, and UTM Transcript within your Mautic installation.