I am trying to make an API request in SFMC to validate email addresses, which requires first to get the Access Token.
I was able to request the access token, but then the next HTTP.Post request I do doesn't work. I have this far:
Platform.Load("core","1.1.5");
var dataRows = Platform.Function.LookupRows('NameofEmailsDE','ColumnName2Check','ValueName');
if(dataRows && dataRows.length > 0) {
for(var i=0; i<dataRows.length; i++) {
var EmailAddress = dataRows[i]["ColumnNameToRetrieve"];
try {
var authEndpoint = "https://uniqueclienturlapi.auth.marketingcloudapis.com";
var client_id = "XXXXXXXXXXX";
var client_secret = "XXXXXXXXXXX";
var account_id = "XXXXXXXXX";
var grant_type = "client_credentials";
// auth
var url = authEndpoint + '/v2/token';
var contentType = 'application/json';
var payload = '{"grant_type":"' + grant_type + '",';
payload += '"client_id":"' + client_id + '",';
payload += '"client_secret":"' + client_secret + '"}';
// create token
var accessTokenResult = HTTP.Post(url, contentType, payload);
var statusCode = result["StatusCode"];
var response = accessTokenResult["Response"][0];
var access_token = Platform.Function.ParseJSON(response).access_token;
/* Until here, the request works, and I get the access_token. The issue comes in this next request when I have to add to the HTTP.Post the headerNames + headerValues */
var restEndpoint = "https://uniqueclienturlapi.rest.marketingcloudapis.com";
restEndpoint += "/address/v1/validateEmail";
var headerNames = ["Authorization"];
var headerValues = ["Bearer " + access_token];
// payload
var restpayload = '{';
restpayload += ' "email": "' + EmailAddress + '",';
restpayload += ' "validators": [ "SyntaxValidator", "MXValidator", "ListDetectiveValidator" ]';
restpayload += '}';
try {
var restresult = HTTP.Post(restEndpoint, contentType, restpayload, headerNames, headerValues);
var reststatusCode = result["StatusCode"];
var response = restresult["Response"][0];
var emailresponse = Platform.Function.ParseJSON(response).email;
var validresponse = Platform.Function.ParseJSON(response).valid;
var failedValidationresponse = Platform.Function.ParseJSON(response).failedValidation;
}
catch (err) {
// error
//Write("error");
}
}
catch (err) {
// error
//Write("error");
}
}
}
I would appreciate any help! Thanks a lot
//Write("error")
and change it toWrite(Stringify(err))
you should be able to get an output on the CloudPage of what the issue is. To move the auth token call outside the loop, just move that above the for loop and remove the try/catch that is around it inside the loop. – Gortonington Oct 7 at 12:57