Concepts or coding lessons of Salesforce that you can implement easily

7 Easy Steps to Call Connected App From Salesforce

In this blog, I am going to talk about How we can call Connected App from Salesforce itself and invoke one of the REST web service after successful authentication.

1. Create Connected App: Populated below data into Connected App setup page:

Few things which are important in this step
    • Set Callback URL to your custom Visualforce page link(Step 3).
    • Selected OAuth Scopes : All Available OAuth Scopes
Connected App Configuration


2. Copy below highlighted Consumer Key and Consumer Secret:




3. Create Visualforce Page : oAuth_Test

<apex:page controller="oAuthTokenController" action="{!startOAuth_step_2}">
  <apex:form >
  <apex:commandButton action="{!startOAuth}" value="Start oAuth Code" rerender="msgs"/>
  <apex:commandButton action="{!getNewAccessToken}" value="Get New Access Token" rerender="msgs"/>
  <apex:commandButton action="{!methodGet}" value="Call Webservice" rerender="msgs"/>
  </apex:form>
  <apex:outPutPanel id="msgs">
      Authorize code => {!authCode}<br/>
      Access Token => {!accToken}<br/>
      Refresh Token => {!refToken}<br/>
      Instance URL => {!insURL}<br/><br/><br/><br/>
      Web Service Response URL => {!wsResponce}<br/>
  </apex:outPutPanel>
</apex:page>

4. Create Apex class : oAuthTokenController

public class oAuthTokenController{
private auth_response objAutoRes;
public String consumerKey = 'YOUR CONSUMER KEY';
   public String consumerSecret = 'YOUR CONSUMER SECRET';

public String authCode {get; set;}
public String accToken {get; set;}
public String refToken {get; set;}
public String insURL {get; set;}
public String wsResponce {get; set;}

// BELOW METHOD FETH AUTHRIZATION CODE
public pagereference startOAuth(){
String auth_url = 'https://test.salesforce.com/services/oauth2/authorize';
String params = 
'?response_type=code' +
'&client_id=' + encodingUtil.urlencode(consumerKey,'UTF-8') +
'&redirect_uri=https://test.salesforce.com/apex/oAuth_Test' +
'&prompt=consent' +
'&scope=' + encodingUtil.URLEncode('full refresh_token','UTF-8') +
'&state=step2';
pageReference pr = New PageReference(auth_url + params);
return pr;
}

// GET ACCESS TOKEN AND REFRESH TOKEN
public pagereference startOAuth_step_2(){
System.debug('state=> '+apexPages.currentPage().getParameters().get('state'));
if(apexPages.currentPage().getParameters().get('state') != 'step2')
return null;

authCode = apexPages.currentPage().getParameters().get('code');

HttpRequest req = new HttpRequest();
Http http = new Http();
String auth_url = 'https://test.salesforce.com/services/oauth2/token';
String params = 
'?code=' + apexPages.currentPage().getParameters().get('code') +
'&grant_type=authorization_code' +
'&client_id=' + encodingUtil.urlencode(consumerKey,'UTF-8') +
'&client_secret=' + consumerSecret +
'&redirect_uri=https://test.salesforce.com/apex/oAuth_Test';
req.setMethod('POST');
req.setEndpoint(auth_url + params);
HTTPResponse resp = http.send(req);
objAutoRes = (auth_response)json.deserialize(resp.getBody(),auth_response.class);

accToken = objAutoRes.access_token;
refToken = objAutoRes.refresh_token;
insURL = objAutoRes.instance_url;

return null;
}

// GET NEW ACCESS TOKEN AFTER EXPIRY OF OLD ACCESS TOKEN
public void getNewAccessToken(){
// First revoke current Access token before requesting new token
String URL = objAutoRes.instance_url;
String urlRevoke = '/services/oauth2/revoke?token=';
String tokenEncode = EncodingUtil.URLENCODE(objAutoRes.access_token,'UTF-8');
URL += urlRevoke += tokenEncode;

HttpRequest req = new HttpRequest();
req.setEndpoint(URL);
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setMethod('GET');
 
Http http = new Http();
HttpResponse res = http.send(req);
system.debug('CR=response= '+res);

// Now request for new access token using refresh token

HttpRequest refreshRequest = new HttpRequest();
Http refreshHttp = new Http();
String auth_url = 'https://test.salesforce.com/services/oauth2/token';
String params = 
'?grant_type=refresh_token' +
'&client_id=' + encodingUtil.urlencode(consumerKey,'UTF-8') +
'&client_secret=' + consumerSecret +
'&refresh_token=' + encodingUtil.URLEncode(objAutoRes.refresh_token,'UTF-8');
refreshRequest.setMethod('POST');
refreshRequest.setEndpoint(auth_url + params);
HTTPResponse refreshResp = refreshHttp.send(refreshRequest);

objAutoRes= (auth_response)json.deserialize(refreshResp.getBody(),auth_response.class);

accToken = objAutoRes.access_token;
insURL = objAutoRes.instance_url;
}

// Retrieve the Accounts from the Salesforce org.
    public void methodGet(){       
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
       
        req.setEndpoint(objAutoRes.instance_url+'/services/apexrest/WebServiceTestingTool');
        req.setHeader('Authorization', 'OAuth '+objAutoRes.access_token);
        req.setHeader('Content-Type', 'application/json');
        Http http = new Http();
        HTTPResponse res = http.send(req);
       
        System.debug('***methodGet Response***** ' + res.getBody());
wsResponce = res.getBody();
    }
private class auth_response{
public string refresh_token;
public string access_token;
public string instance_url;
}
}

5: Create Apex class which acts as REST webservice namely TestRestWebservice and copy below code:

@RestResource(urlMapping='/WebServiceTestingTool/*')
global class TestRestWebservice {
    @httpGet                     
    global static void WSPolicyData (){
        RestRequest req = RestContext.request;
       
        try{
            List<Account> result = [SELECT Name FROM Account LIMIT 1];
            RestContext.response.responseBody = Blob.valueOf(JSON.serializePretty(result));
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
        }
    }
}

6: Create TWO remote site setting like below:

7: Go to oAuth_Test Visualforce page we have created in step 3 and click on button.

    Click on Start oAuth Code button and authorize the App. After successful authorization you will get below details:



Thats It.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 

Latest Salesforce Interview Questions and Answers:
loading...

1 comment: