Salesforce to Salesforce Integration using Metadata Api and get contacts from Org

With the use of OAuth 2.0 Web Server Authentication Flow

The Web server authentication flow is used by applications that are hosted on a secure server. A critical aspect of the Web server flow is that the server must be able to protect the consumer secret. You can also use code challenge and verifier values in the flow to prevent authorization code interception.
The following diagram displays the authentication flow steps for Web server clients. The individual step descriptions follow.

Now here some steps of get contacts using Metadata Api

Step-1: Create blank page with “CallBackURL” Name
Initially we will create a blank page like:

<apex:page showHeader="false" sidebar="false" standardStylesheets="false">

Step-2: Create Site
Now we have to create an site for getting access code:
To create a site:

      From Setup, click Develop | Sites.
      In the Sites section, click New.

Enter information to create a site like:

When you’ve finished entering the information, click Save to save.

Step-3: Create Connected App
Create a Connected App
To create a connected app:

      From Setup, click Create | Apps.
      In the Connected Apps section, click New.

Enter information to create a connected app.
When you’ve finished entering the information, click Save to save your new app. You can now publish your app, make further edits, or delete it. If you’re using OAuth, saving your app gives you two new values the app uses to communicate with Salesforce:
Consumer Key: A value used by the consumer to identify itself to Salesforce. Referred to as client_id in OAuth 2.0.
Consumer Secret: A secret used by the consumer to establish ownership of the consumer key. Referred to as client_secret in OAuth 2.0.

See in below image:

Step-4:Now we have to Create Classes
In this class Web server redirects the user to Salesforce to authenticate and authorize the server to access data on their behalf and get access code. we have to create
“authController” class.

public with sharing class authController{    
    public pagereference CallApi(){
        string clientId='XXXXXXXXXXXXXXXXXXXXXX';
        String clientSecret='XXXXXXXXXXXXXXXXXXXXXX'; 
        return new pagereference( '' + clientId + '&redirect_uri=your_global_site/callbackurl&prompt=login&display=popup&state=state' );

Now we have to include a MetadataService class from this GitHub click here

After including of above class we have to create another classes:
MetaController Class:

public with sharing class MetaController {     
     public static MetadataService.MetadataPort createService(string accTkn){
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = accTkn;
        return service;

CallBackURLController Class:

public with sharing class CallBackURLController{
    public string bodyCode{get;set;}
    public string bodyInfo{get;set;}
    public string cd{get;set;}
    public string hd{get;set;}
    public list<contact> lstCon{get;set;}
    public CallBackURLController(){
        string vrsn=[select name from version__c].name;
        string Accesscode=ApexPages.currentPage().getParameters().get('code');
        string clientId='XXXXXXXXXXXXXXXXXXXXXX';
        String clientSecret='XXXXXXXXXXXXXXXXXXXXXX';
        String redireUri='';
        string loginUri='';
        string ContentType = 'application/json';
        ///// Get Access Token
        HttpRequest req = new HttpRequest();  
        string reqbody='grant_type=authorization_code' +
            '&client_id=' + clientId +
            '&client_secret=' + clientSecret +
            '&code=' + Accesscode +
            '&redirect_uri=' + redireUri;
        Http http = new Http();  
        HTTPResponse res = http.send(req);
        Map<String, object> mapReqBody=(Map<String, object>)JSON.deserializeUntyped(res.getBody());
        string header=string.valueOf(mapReqBody.get('token_type'))+' '+string.valueOf(mapReqBody.get('access_token'));
        ///// Get User Info
        HttpRequest reqInfo = new HttpRequest();  
        reqInfo.setHeader('Content-Type', ContentType);
        reqInfo.setHeader('Authorization', header);
        Http httpInfo = new Http();  
        HTTPResponse resInfo = httpInfo.send(reqInfo);
        Map<String, object> mapReqInfoBody=(Map<String, object>)JSON.deserializeUntyped(resInfo.getBody());       
        /////Make Query Request
        Map<String, object> tmp=(Map<String, object>)mapReqInfoBody.get('urls');
        string queryUri=string.valueOf(tmp.get('query')).replace('{version}',vrsn);
        MetadataService.MetadataPort service = MetaController.createService(header);
        HttpRequest reqQry = new HttpRequest();
        reqQry.setHeader('Authorization', header);
        reqQry.setHeader('Content-Type', ContentType);
        Http httpQry = new Http();
        HTTPResponse resQry = httpQry.send(reqQry);
        Map<String, object> mapReqQryBody=(Map<String, object>)JSON.deserializeUntyped(resQry.getBody());
        string strCons =JSON.serialize(mapReqQryBody.get('records'));
        lstCon=(list<contact>) JSON.deserialize(strCons, List<contact>.class);

When we make different-different request we will get different-different JSON responses like:
1) Response of Access Token

    "id": "",
    "issued_at": "xxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer",
    "instance_url": "",
    "signature": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    <strong>"access_token": "xxxxxxxxxxxxxxxxxxx"</strong>

Using this access token we can get User Info .

2) Response of User Info
After making a valid request Salesforce returns the information in JSON format, by default, or whatever is specified in the Format parameter.
The following is a response in JSON format:

"name":"na1 LastName",

3) Response of Query
Using User Info we can get urls for making requests like query which is we want to use for getting contacts.
After making query request we will get contacts in JSON format.

Step-5:Now we have to Create and Upgrade pages

Now we upgrading CallBackURL page.

<apex:page controller="CallBackURLController" showHeader="false" sidebar="false" standardStylesheets="false">
     <apex:pageBlock >
         <apex:pageBlockTable value="{!lstCon}" var="con">
             <apex:column value="{!}"/>
             <apex:column value="{!}"/>

And also create new page for test our integration with the name of “AuthCall”.

<apex:page controller="authController">
  <apex:form >
  <apex:commandButton value="TEST" action="{!CallApi}"/>

Step-6:Now it’s time to testing
Now we have to click preview button of AuthCall page and then we found that screen:


After that we have to click on Test button and then we will seeing login screen:


Now we have to login and after login a dialog box will be appear that access permission dialog box. in this dialog box we have to click in allow that dialog box is appear like that screen:

access allow

And after this dialog box we will get contacts and also we get access code see in url like that:


3 thoughts on “Salesforce to Salesforce Integration using Metadata Api and get contacts from Org

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s