Send an Analytics Event to Segment

Track agent interactions and send to Segment for analysis.
Created By
Zoran Slamkov
Voiceflow Built
INPUT VARIABLES
{
segmentWriteKey
}
Your Segment Write Key
{
goalAchieved
}
The goal the user achieved at this part of the conversation (i.e. Deflected Ticket)
{
userId
}
The unique user ID that is sent to Segment
{
}
{
}
{
}
OUTPUT VARIABLES
{
}
{
}
{
}
{
}
{
}
{
}
PATHS
{
fail
}
{
success
}
{
}
{
}
{
}
{
}

Function Code Snippet


export default async function main(args) {
  const { userId, goalAchieved, segmentWriteKey } = args.inputVars;

  function base64Encode(str) {
    const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    let output = '';

    for (let i = 0; i < str.length; i += 3) {
      const byte1 = str.charCodeAt(i) & 0xFF;
      const byte2 = i + 1 < str.length ? str.charCodeAt(i + 1) & 0xFF : 0;
      const byte3 = i + 2 < str.length ? str.charCodeAt(i + 2) & 0xFF : 0;

      const enc1 = byte1 >> 2;
      const enc2 = ((byte1 & 0x3) << 4) | (byte2 >> 4);
      const enc3 = ((byte2 & 0xF) << 2) | (byte3 >> 6);
      const enc4 = byte3 & 0x3F;

      if (isNaN(byte2)) {
        output += charSet.charAt(enc1) + charSet.charAt(enc2) + '==';
      } else if (isNaN(byte3)) {
        output += charSet.charAt(enc1) + charSet.charAt(enc2) + charSet.charAt(enc3) + '=';
      } else {
        output += charSet.charAt(enc1) + charSet.charAt(enc2) + charSet.charAt(enc3) + charSet.charAt(enc4);
      }
    }

    return output;
  }
  
  // Segment's API endpoint for tracking events
  const segmentUrl = 'https://api.segment.io/v1/track';

  // Prepare the request payload
  const payload = {
    userId: userId,             // Unique identifier for the user
    event: 'Goal Achieved',     // Name of the event
    properties: {
      goal: goalAchieved        // Details of the goal achieved
    }
  };

 const encodedSegmentKey = base64Encode(segmentWriteKey + ':');
  
  // Set up the headers for the Segment API request
  const headers = {
    'Authorization': `Basic ${encodedSegmentKey}`,
    'Content-Type': 'application/json'
  };
  
  try {
    // Send the event to Segment
    const response = await fetch(segmentUrl, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(payload)
    });

    // Check response status to confirm event was sent
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // Return a success message
    return {
      next: {
        path: 'success'
      },
      trace: [{
        type: 'text',
        payload: {
          message: "Goal achievement event successfully sent to Segment."
        }
      }]
    };

  } catch (error) {
    // Handle errors in sending the event
    return {
      next: {
        path: 'fail'
      },
      trace: [{
        type: 'text',
        payload: {
          message: `Failed to send event to Segment: ${error.message}`
        }
      }]
    };
  }
}

Function Walkthrough