Created
June 30, 2021 22:17
-
-
Save kressaty/03ebc218166d431ba39e5851b1b0e6f7 to your computer and use it in GitHub Desktop.
Sends the submitted payload of a Google Form to Segment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Sends the submitted payload of a Google Form to Segment. | |
Steps to install: | |
1. modify the script below to include your base64 encoded write key (with a colon at the end!) per the Segment docs | |
2. set the event name you want | |
3. add as a script to your Google Form (More > Script Editor) | |
4. add "https://www.googleapis.com/auth/script.external_request" & "https://www.googleapis.com/auth/forms" to your oauthScopes key in appscript.json | |
5. set your script trigger to onFormSubmit | |
*/ | |
function onFormSubmit(event) { | |
var payload = {}; | |
// get the response from the event | |
var formResponse = event.response; | |
// get the individual field values from the response | |
var itemResponses = formResponse.getItemResponses(); | |
// build an object of key/value items for your data | |
for (var j = 0; j < itemResponses.length; j++) { | |
var itemResponse = itemResponses[j]; | |
// snake case the key | |
var key = itemResponse | |
.getItem() | |
.getTitle() | |
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) | |
.map(x => x.toLowerCase()) | |
.join('_'); | |
payload[key] = itemResponse.getResponse(); | |
} | |
// Uncomment if you want to see logs of your payload | |
//Logger.log(payload); | |
// Generate a random string for an anonymous ID (required) | |
var result = ''; | |
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
var charactersLength = characters.length; | |
for ( var i = 0; i < 16; i++ ) { | |
result += characters.charAt(Math.floor(Math.random() * charactersLength)); | |
} | |
// build your segment payload | |
var segment_payload = { | |
"anonymousId": result, | |
"event": "YOUR EVENT NAME", | |
"properties": payload | |
}; | |
// make your request to segment | |
UrlFetchApp.fetch('https://api.segment.io/v1/track', { | |
payload: JSON.stringify(segment_payload), | |
method: 'post', | |
headers: { | |
"Authorization": "Basic <BASE 64 ENCODED WRITE KEY CONCATENATED WITH A COLON>", | |
"Content-Type": "application/json" | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment