1

Actually I try to get access token of salesforce DC from salesforce MC by SSJS Httppost I need to create a record in salesforce object From Salesforce marketing cloud pages

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script runat="server">

        Platform.Load("Core","1.1.1");
        try {
          </script>
  %%[
    Var @body, @callstatus, @response<br>
     Set @body = '{<br>
 "grant_type":"password",<br>
  "clientId":"Id",<br>
  "clientSecret":"****",<br>
  "username":"test@email",<br>
  "password":"MyPassword12345"<br>
  }'<br>
    HTTPPost2("https://login.salesforce.com/services/oauth2/token", "application/x-www-form-urlencoded", @body, True, @callstatus, @response)<br>
]%% <br>
    <script type="text/javascript" runat="server">
        } catch (e) {
            Write(Stringify(e));
        }
    </script><br>
Call:%%=v(@callstatus)=%%<br>
Res:%%=v(@response)=%%
</head>
<body>
</body>
</html>

Getting Error

{"message":"The function expression is invalid. See inner exception for detail.\r\n <br>
Script: HTTPPost2(\"https://login.salesforce.com/services/oauth2/token\", \"application/x-www-form-urlencoded\", @body, True, @callstatus, @response)\r\n<br>
Index: 1098\r\n<br>  ListID: 0\r\n" ,<br>
"description":"ExactTaOMM.InvalidScriptException: The function expression is invalid. See inner exception for detail.\r\n<br>
Script: HTTPPost2(\"https://login.salesforce.com/services/oauth2/token\", \"application/x-www-form-urlencoded\", @body, True, @callstatus, @response)\r\n
Index: 1098\r\n ListID: 0\r\n <br>
Error Code: OMM_FUNC_EXPR_INVALID\r\n<br>
  - from Jint --> \r\n\r\n<br>
  --- inner exception 1---\r\n\r\nExactTarget.OMM.FunctionExecutionException: An error occurred when attempting to evaluate a HTTPPost2 function call. See inner exception for details.\r\n<br>
  Error Code: OMM_FUNC_EXEC_ERROR\r\n - from OMMCommon --> \r\n\r\n<br>
  --- inner exception 2---\r\n\r\nSystem.Net.WebException: The remote server returned an error: (400) Bad Request. - from System\r\n\r\n\r\n\r\n\r\n\r\n"} <br>
 Call: Res:
1
  • Why are you putting <br> in your Json object?
    – 0xsegfault
    Commented Jul 21, 2018 at 21:07

2 Answers 2

3

To start with:

  1. clientId should be client_id
  2. clientSecret should be client_secret

I would use form-data to post the payload (I've only got this request to work using form-data).

Note, the other issue that you are going to hit is that the response payload is JSON and AMPscript can't parse JSON. Fortunately, Guide Template Language (or GTL) can help you out here.

Here's some working AMPscript and GTL code:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

  %%[
    Var @clientId, @clientSecret, @username, @password, @callstatus, @response
    set @clientId = 'insertCliendIdHere'
    set @clientSecret = 'insertClientSecretHere'
    set @username = 'insertUsernameHere'
    set @password = 'insertPasswordHere'

    Set @payload = Concat('grant_type=password&client_id=', @clientId, '&client_secret=', @clientSecret, '&username=', @username, '&password=', @password)

    HTTPPost("https://login.salesforce.com/services/oauth2/token", "application/x-www-form-urlencoded", @payload, @response)
    /* %%{={{ }}=}%% escape OMM delimiters, do not delete this comment */
  ]%% 

</head>
<body>
{{.datasource response type=variable source=@response}}
   {{.data}}
      {"target":"@response"}
   {{/data}}
%%[
var @accessToken, @instanceURL, @id
set @accessToken = TreatAsContent('%%{={{ }}=}%%{{access_token}}')
set @instanceURL = TreatAsContent('%%{={{ }}=}%%{{instance_url}}')
set @id = TreatAsContent('%%{={{ }}=}%%{{id}}')
]%%
{{/datasource}}

<p>access token is: %%=v(@accessToken)=%%</p>
<p>instance url is: %%=v(@instanceURL)=%%</p>
<p>id is: %%=v(@id)=%%</p>

</body>
</html>

Note: don't delete the %%{={{ }}=}%% pattern (including the one that is commented out) as this is needed to escape OMM delimiters on CloudPages for GTL tags to be interpreted (however you should remove it if using in an email).

AMPscript Alternative

I assume that you are aware that there's also a CreateSalesforceObject AMPscript function that enables you to create records in Sales Cloud objects?

Effectively, it's a wrapper for the the Salesforce REST API method to create a SObject record. This would only work if you have configured Marketing Cloud Connect, but it's certainly more convenient then interacting with the REST API through HTTPPost.

I assume you're aware of this, but thought it would be worth mentioning.

1

Instead of AMPScript + GTL you can also use SSJS to send post API call & Parse the JSON returned. Of course as @Eliot mentioned you would need to use HTTPPost option as the Script.Util.HttpRequest does NOT function for some reason. So below I have used a SSJS wrapper to wrap the AMPScript HTTPPost function, so that you do not have to use multiple languages.

    <script runat="server">

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

        try {  
          var clientId = 'MY_CLIENT_ID';
          var clientSecret = 'MY_CLIENT_SEC';
          var username = 'USERNAME';
          var password = 'PASSWORD'; 

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

          Variable.SetValue('@payload', payload);

          Platform.Function.TreatAsContent('%%[ HTTPPost("https://pmisa--sandbox1.my.salesforce.com/services/oauth2/token", "application/x-www-form-urlencoded", @payload, @response) ]%%');

          var response = Variable.GetValue('@response');    
          response = Platform.Function.ParseJSON(response);
          Write("</br> access_token: " + (response['access_token']));

        } catch (e) {

          Write("<br>e: " + Stringify(e));

        }

    </script>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .