0

I'm trying to use SSJS in a Script Activity inside Marketing Cloud Automation Studio to retrieve lead data from Salesforce using the REST API. I've confirmed that the credentials and API call work perfectly in Postman, but this script throws errors in Automation Studio.

Here is the full script I’m using (clientId, clientSecret, etc. are obfuscated for this post):

    <script runat="server">

Platform.Load("Core", "1");

var clientId = 'YOUR_CLIENT_ID';

var clientSecret = 'YOUR_CLIENT_SECRET';

var username = 'YOUR_USERNAME';

var password = 'YOUR_PASSWORD' + 'YOUR_SECURITY_TOKEN';

var authUrl = 'https://test.salesforce.com/services/oauth2/token';

var queryUrl = 'https://YOUR_INSTANCE.salesforce.com/services/data/v59.0/query?q=SELECT+Id,FirstName,LastName,Company,Title,Email,Phone,Lead_Type__c,LeadSource,Lead_Source_Description__c,Region__c,Status,RecordType.Name+FROM+Lead+WHERE+RecordType.Name=\'Membership\'';

var oauthHeaders = {

    "Content-Type": "application/x-www-form-urlencoded"

};

var oauthBody = 'grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password;

var oauthRequest = HTTP.Post(authUrl, oauthHeaders, oauthBody);

var oauthResponse = Platform.Function.ParseJSON(oauthRequest.Response[0].ResponseText);

var accessToken = oauthResponse.access_token;

var queryHeaders = {

    "Authorization": "Bearer " + accessToken

};

var queryRequest = HTTP.Get(queryUrl, queryHeaders);

var queryResponse = Platform.Function.ParseJSON(queryRequest.Response[0].ResponseText);

if (queryResponse.records) {

    for (var i = 0; i < queryResponse.records.length; i++) {

        var lead = queryResponse.records[i];

        var dataExtension = DataExtension.Init("YOUR_DATA_EXTENSION_EXTERNAL_KEY");

        dataExtension.Rows.Add({

            "Id": lead.Id,

            "FirstName": lead.FirstName,

            "LastName": lead.LastName,

            "Company": lead.Company,

            "Email": lead.Email,

            "Phone": lead.Phone,

            "Lead_Type__c": lead.Lead_Type__c,

            "LeadSource": lead.LeadSource,

            "Lead_Source_Description__c": lead.Lead_Source_Description__c,

            "Region__c": lead.Region__c,

            "Status": lead.Status,

            "RecordType_Name": lead.RecordType.Name

        });

    }

} else {

    Write("No records found or error occurred");

}

</script>
2

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.