public class
responseWrapper {
public string id;
public string access_token;
public string instance_url;
}
public string cKey;
public string cSecret;
List < Store_Cred__mdt
> connectionParam = [SELECT Id, MasterLabel, client_id__c, client_secret__c
from Store_Cred__mdt];
if(connectionParam.size() >0){
cKey=connectionParam[0].client_id__c;
cSecret=connectionParam[0].client_secret__c;
}
System.debug('Store_Cred__mdt' +
connectionParam);
String authCode= 'aPrxsh*********************************************8Xg%3D%3D';
// The below URI is the callback URL of ORG A
String
uri='https://myknowndomain-dev-ed.my.salesforce.com/services/oauth2/callback';
String reqBody =
'grant_type=authorization_code&client_id=' + cKey + '&client_secret=' +
cSecret + '&code=' + authCode + '&redirect_uri=' + uri ;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqBody);
req.setMethod('POST');
// Token end point of ORG B
req.setEndpoint('https://farukh-dev-ed.my.salesforce.com/services/oauth2/token');
HttpResponse hresp = h.send(req);
System.debug('hresp is'+hresp);
System.debug('hresp body
is'+hresp.getBody());
responseWrapper wResp =
(responseWrapper) JSON.deserialize(hresp.getBody(), responseWrapper.class);
system.debug('reqBody '+reqBody );
system.debug('wResp'+wResp );
system.debug('Instance url' + wResp.instance_url);
system.debug('session id' +
wResp.access_token);
List<Account> accList = new
List<Account>();
// End point of ORG B where we will send POST request for account record creation
string endPoint =
'https://farukh-dev-ed.my.salesforce.com'+'/services/apexrest/createAccountRecord';
accList=[SELECT
Id,Name,Description,Type,Industry from account Order By createddate DESC Limit
1];
Http h1 = new Http();
HttpRequest req1 = new
HttpRequest();
req1.setHeader('Authorization',
'Bearer ' + wResp.access_token);
req1.setHeader('Content-Type',
'application/json');
req1.setMethod('POST');
req1.setEndpoint(endPoint);
req1.setBody(JSON.serialize(accList));
HttpResponse hresp1 =
h1.send(req1);
system.debug('hresp1'+hresp1 );
system.debug('hresp1.getStatusCode()'+hresp1.getStatusCode());
system.debug('hresp1.getBody()'+hresp1.getBody());
if (hresp1.getStatusCode() == 200)
{
system.debug('Callout
Success');
}