Salesforce to Salesforce Integration using Composite API :
Send Multiple Requests Using Composite
Executes a series of REST API requests in a single call. You can use the output of one request as the input to a subsequent request. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire series of requests counts as a single call toward your API limits.
The requests in a composite call are called subrequests. All subrequests are executed in the context of the same user. In a subrequest’s body, you specify a reference ID that maps to the subrequest’s response. You can then refer to the ID in the url or body fields of later subrequests by using a JavaScript-like reference notation.
For example, the following composite request body includes two subrequests. The first creates an account and designates the output as refAccount. The second creates a contact parented under the new account by referencing refAccount in the subrequest body.
For more Detail Click here:
Apex Trigger:
trigger OnContact on Contact (after update) {
if(trigger.isAfter && Trigger.isUpdate){
for(Contact cont : Trigger.new) {
if(trigger.oldMap.get(cont.id).primary_contact__c!=cont.primary_contact__c && cont.Primary_Contact__c==true){
ConnectToSalesforceRestApi.run(cont.id);
}
}
}
}
Apex class:
public class ConnectToSalesforceRestApi {
@Future(callout=true)
public static void run(string contactid){
String endpoint='https://kreya2-dev-ed.develop.my.salesforce.com/services/oauth2/token';
// or use this endpoint for a sandbox org:
// String endpoint='https://test.salesforce.com/services/oauth2/token';
String username = 'amulhai@dev2.com';
String password = 'reset12QRGoMnURJNigP0m0okBi6K';
String CONSUMER_KEY = '3MVG9fe4g9fhX0E5Ejj.OX6.kBWke.eCBDa8RpIqaJlx.HhxRXUQYtmxJhs0VP6cPtJmXphhKEofq.qSFAyuu';
String CONSUMER_SECRET = '5FC04C75E3C32C3E5F05FB1C661804E70F50D73B48194681BB35D9464D9CF2B3';
Httprequest request = new HttpRequest();
request.setMethod('POST');
request.setHeader('Content-Type','application/x-www-form-urlencoded');
request.setBody(
'grant_type=password' +
'&client_id=' + CONSUMER_KEY +
'&client_secret=' + CONSUMER_SECRET +
'&username=' + username +
'&password=' + password
);
request.setEndpoint(endpoint);
Http http = new Http();
HttpResponse response;
String accessToken;
try {
response = http.send(request);
System.debug('body: ' + response.getBody());
accessToken = parseResponseForAccessToken(response.getBody());
} catch(System.CalloutException error){
System.debug('error: ' + error);
}
System.debug('access token: ' + accessToken);
// be careful as the following line will print sensitive credentials to the logs
// System.debug(UserInfo.getOrganizationId().substring(0, 15) + ' ' + UserInfo.getSessionId().substring(15));
query(accessToken);
PushContactToDev2(contactid,accessToken);
//PushAccountToDev2(contactid,accessToken);
}
private static String parseResponseForAccessToken(String responseBody) {
String accessToken;
JSONParser parser = JSON.createParser(responseBody);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {
parser.nextToken();
accessToken = parser.getText();
}
}
return accessToken;
}
private static void PushContactToDev2(String contactid,String accessToken){
Account acc=new Account();
Contact cont=new Contact();
if(contactid!=''){
list<contact> lstContact=[Select id, firstName, Lastname, Email,Phone,AccountId from contact where id=:contactid];
string accountId='';
if(lstContact.size()>0){
accountId=lstContact[0].AccountId;
cont=lstContact[0];
}
list<Account> lstAccount=[Select id, name, POS__c, Contracted_System__c, Credit_Status__c, AccountNumber from account where id=:accountId];
if(lstAccount.size()>0){
acc=lstAccount[0];
}
}
String endpoint = 'https://kreya2-dev-ed.develop.my.salesforce.com/services/data/v56.0/composite/';
String JsonData='';
string strAccountNumber=acc.AccountNumber;
string POS=acc.POS__c;
string ContractedSystem=acc.Contracted_System__c;
string AccName=acc.Name;
string CreditStatus=acc.Credit_Status__c;
string contfirstName=cont.firstName;
string contLastName=cont.LastName;
string contEmail=cont.Email;
string contPhone=cont.Phone;
Httprequest request = new HttpRequest();
Http http = new Http();
HttpResponse response;
JsonData=JSONBodyData(strAccountNumber,POS,ContractedSystem,CreditStatus,contfirstName,contLastName,contEmail,contPhone,AccName);
request.setEndpoint(endpoint);
request.setMethod('POST');
// we can use either of the two below lines for content Type.
// request.setHeader('Content-Type','application/json');
request.setHeader('Content-Type','application/json');
request.setHeader('Authorization','Bearer ' + accessToken);
request.setBody(JsonData);
response = http.send(request);
System.debug('body: ' + response.getBody());
}
public static string JSONBodyData(string strAccountNumber,string POS, string ContractedSystem
, string CreditStatus
, string contfirstName
, string contLastName
, string contEmail
, string contPhone
, string AccName) {
String json= '{'+
' "allOrNone" : true,'+
' "compositeRequest": [{'+
' "method": "PATCH",'+
' "url": "/services/data/v56.0/sobjects/Account/AccountNumber_External_id__c/' + strAccountNumber + '",' +
' "referenceId": "NewAccount",'+
' "body": {'+
' "POS__c": "'+ POS + '",' +
' "Contracted_System__c": "'+ ContractedSystem + '",' +
' "Name": "'+ AccName + '",' +
' "Credit_Status__c": "'+ CreditStatus + '"' +
' }'+
' },{'+
' "method" : "PATCH",'+
' "url" : "/services/data/v56.0/sobjects/Contact/Email_External_Id__c/' + contEmail + '",'+
' "referenceId" : "newContact",'+
' "body" : {'+
' "firstName" : "'+ contfirstName + '",' +
' "LastName" : "'+ contLastName + '",' +
' "Email" : "'+ contEmail + '",' +
' "Phone" : "'+ contPhone + '",' +
' "AccountId" : "@{NewAccount.id}"'+
' }'+
' }]'+
'}';
return json;
}
/* private static void PushAccountToDev2(String contactid,String accessToken){
String endpoint = 'https://kreya2-dev-ed.develop.my.salesforce.com/services/data/v42.0/query/?q=SELECT+name+from+account+limit+1';
Httprequest request = new HttpRequest();
Http http = new Http();
HttpResponse response;
request.setEndpoint(endpoint);
request.setMethod('GET');
}
*/
private static void query(String accessToken) {
// this endpoint allows us to append a SOQL query to retrieve specific data
// see the documentation for a complete list of endpoints
String endpoint = 'https://kreya2-dev-ed.develop.my.salesforce.com/services/data/v42.0/query/?q=SELECT+name+from+account+limit+1';
Httprequest request = new HttpRequest();
Http http = new Http();
HttpResponse response;
request.setEndpoint(endpoint);
request.setMethod('GET');
// we can use either of the two below lines for content Type.
// request.setHeader('Content-Type','application/json');
request.setHeader('Content-Type','application/x-www-form-urlencoded');
request.setHeader('Authorization','Bearer ' + accessToken);
response = http.send(request);
// => {"totalSize":1,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v20.0/sobjects/Account/0014000000xVKZgAAO"},"Name":"Jane Doe"}]}
System.debug('body: ' + response.getBody());
}
}
2 Comments
Nice Informative Post.
ReplyDeleteClone Flows in Salesforce
Great insights on Salesforce Platform Events! Clear and helpful breakdown. Excited to apply these tips in my projects. Thanks for sharing
ReplyDeletesalesforce time tracking
salesforce timesheet
Salesforce Time Tracking Integration