I am using Google Tag Manager Server Container.
I am trying to make a POST API call to
https://api.hubapi.com/events/v3/send?hapikey={{hubspot api key}}
The parts in between {{ }} are variables taken and set within google tag manager. They are populating properly.
The purpose of this API call is to send a custom behaviour event (similar to google analytics event) to Hubspot - custom behaviour events manual tracking
For these events, you can send in properties like page url, google cid, file type, page title etc.
These properties are added to the request body, so they are included in the setBody in the following request
sendHttpRequest(url, (statusCode, headers, body) => {
if (statusCode >= 200 && statusCode <300) {
data.gtmOnSuccess();
} else {
data.gtmOnFailure();
}
setResponseStatus(statusCode);
setResponseHeader('cache-control', headers['cache-control']);
setResponseBody(body);
},{headers: postHeaders, method: 'POST', timeout: 3000}, setBody);
setBody is set with the following code:
if (data.additionalProperties) {
for (let key in data.additionalProperties) {
postPropertiesData = ["{",postPropertiesData, data.additionalProperties[key].property,":",data.additionalProperties[key].value,"}"].join('');
}
}
const postProperties = JSON.stringify(postPropertiesData);
const setProperties = JSON.stringify({
utk: data.userToken,
eventName: data.eventName,
ocurredAt: getTimestamp(),
});
const setBody = [setProperties,'properties:',postProperties].join(' ');
the (if (data.additionalProperties)
section takes the properties from an input table like this
.
data.additionalProperties access the table. The left column has the internal name called property and the right column has the internal name called value.
I need it to output as an object to 'properties': {'firstname':'michael','lastname':'stone','email':'michael.stone@gmail.com'} and then stringified using JSON.stringify() function
I used the code above to try prepare to be part of the request body.
I have also tried.
let postPropertiesData = {};
if (data.additionalProperties) {
for (let key in data.additionalProperties) {
postPropertiesData[data.additionalProperties[key].property =data.additionalProperties[key].value,"};
}
}
const setBody = JSON.stringify({
utk: data.userToken,
eventName: data.eventName,
properties: postPropertiesData,
ocurredAt: getTimestamp(),
});
either way I get the same result
the properties part is empty.
How do I resolve this?
in the end, I found the answer. I had to use the makeTableMap API
so I did const makeTableMap = require('makeTableMap');
and then instead of the if statements and the for, I used a ternary within the object itself.
const setBody = JSON.stringify({
'portalId':data.portalID,
'utk': data.userToken,
'eventName': data.eventName,
'properties': (data.additionalProperties) ? makeTableMap(data.additionalProperties,'property','value'):{},
'ocurredAt': getTimestamp(),
});
and that worked.