0

I'm new to integration. I want to post a field value to other external application. So, the third party is using OAuth 2.0 Security.

I'm going to generate access token through client key.

They share following sample code to generate the Access key. But it is in javascript format. I don't have an idea to convert in apex with JSON.

Sample Code

var result = {};
var application = "SuperWidgets";
var vendor = "WidgetsInc.com";
var applicationId = "ZWJkNWM0MzNiODQ5NDAyYmIyZGFhNDg3ZDEzZgJkYzc=";
var authCode = window.btoa(application + "@" + vendor + ":" + applicationId);
$.ajax({
    "url": 'https://api.incontact.com/InContactAuthorizationServer/Token',
    "type": 'post',
    "contentType": 'application/json',
    "dataType": 'json',
    "headers": {
        'Authorization': 'basic ' + authCode
    },
    "data": JSON.stringify({
        "grant_type": 'client_credentials',
        "scope": 'PatronApi'
    }),
    "success": function (resp) {
        result.access_token = resp.access_token;
        result.token_type = resp.token_type;
        result.resource_server_base_uri = resp.resource_server_base_uri;
    },
    "error": function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Failed to retrieve token.\n" + XMLHttpRequest.status + ' ' 
            + XMLHttpRequest.statusText);
    }
});

For window.btoa function, I changed it to EncodingUtil.base64Encode

closed as off-topic by glls, battery.cord, Raul, DavidSchach, Mohith Shrivastava Aug 9 '18 at 4:51

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on problems in code you've written must describe the specific problem and include valid code to reproduce it. For help writing short, self-contained syntactically-valid examples, see: SSCCE.org" – glls, battery.cord, Raul, DavidSchach, Mohith Shrivastava
If this question can be reworded to fit the rules in the help center, please edit the question.

1

Break it down into pieces, and it should be easier to translate into Apex.

You've already started by determining that btoa => EncodingUtil.base64Encode().

Next up, it helps to understand what each part of the AJAX request means.

  • "url" is the "endpoint", the destination of your request
  • "type" is the HTTP method (also called the http "verb") being used. GET and POST are the most common, but there are others (PATCH, DELETE, HEAD, etc...) You're making a POST request here
  • "contenttype", an HTTP header, tells the receiving server what kind of data it should expect in the body of the request
  • "headers", as the name might suggest, these are more headers to be included in the request
  • "data" is the "body" of the request

With that information in hand, your next step should be to look over the Http, HttpRequest, and HttpResponse class documentation. These are what we use to make http calls to third parties in apex.

You'll be doing the most work with the HttpRequest class, and if you look at the documentation, you should see that it contains the following methods:

  • setEndpoint()
  • setMethod()
  • setHeader()
  • setBody()

Those line up really nicely with the information that we extracted from the javascript AJAX request.

Finally, a small example to get you going

// A string is probably the simplest way to generate JSON, but it's not the only way.
// A wrapper class + JSON.serialize() is probably the better way to approach this
//   (class variable names become the names of keys in the resulting JSON)
String myBody = '{"someKey":"someValue"}';

HttpRequest req = new HttpRequest();

// Don't forget to add your endpoint to your remote site settings.
// Salesforce will prevent the callout if your endpoint isn't set up as a remote site
req.setEndpoint('https://localhost');
// headers need to be set one at a time (to the best of my knowledge), and these are key-value
//   pairs.
req.setHeader('Content-Type', 'application/json');
req.setMethod('POST');
req.setBody(myBody);

// Actually sending the request requires an instance of the HTTP class.
// You'll want an variable of HttpResponse to capture the response of your callout as well
Http httpCallout = new Http();
HttpResponse res;

// Perform the callout
// Be aware that if this callout exceeds a timeout value, or your total time spent
//   waiting for callouts to return exceeds 120 seconds in a single transaction,
//   you can run into exceptions on this line
res = httpCallout.send(req);
  • Thank you for the detailed explanation. I have a doubt In javascript code sample they are encoding (application + "@" + vendor + ":" + applicationId) and passing through headers.But do I need to pass through the body or i need to build URL – Pavan tej Aug 6 '18 at 14:45
  • 1
    @Pavantej Neither of those. Like your third party's documentation says, you need to send that information in the header (specifically the "Authorization" header, with a value of "basic" + [your identifying values, base64 encoded, here]). Yes, you need the "basic" in there as well, and yes, you need the single whitespace between "basic" and your base64 string. – Derek F Aug 6 '18 at 16:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.