Lets Start with Salesforce to Salesforce Integration Using REST API and OAuth.
Here I wanted to Access the All contacts for an Account From Target Org(2nd Salesforce Org)
Step-1:
In Source Org Create one Connected App:
Login into Salesforce Sandbox or Salesforce Developer Org
then goto Setup-> App->Connected App
Click New
Change the Oauth CallBack URL according to your instance. Here my instance is "CS30"
https://cs30.salesforce.com/services/oauth2/callback
Then Save it.
After Save you will get Consumer Key & Consumer Secret
After this now we have to Develop one Apex RestService in the Same Source Org.
Step 2: Click on Setup-> Develop->Apex Class
Click New and Save it.
The purpose of this method is to return all contacts related to AccountId
- @RestResource(urlMapping='/v1/getContacts/*')
- global with sharing class getContact {
- @Httpget
- global static list<contact> fetchAccount(){
- RestRequest req = RestContext.request;
- RestResponse res = Restcontext.response;
- Id accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
- list<contact> lstcontact =[Select id , name,Phone,Fax,Email from contact where Accountid=:accId ];
- return lstcontact ;
- }
- }
- Login into Target Org
- Create new Apex Class "SendAccountUsingRESTAPI " see below
- clientId
- clientSecret
- username
- password
req.setEndpoint('https://test.salesforce.com/services/oauth2/token');
Also Change the Endpoint(line no.32) in which org you are trying to access all the Contacts. means where you have developed your Apex RestService
String endPoint = 'https://cs30.salesforce.com/services/apexrest/v1/getContacts/' +accId;
APEX CLASS
*********************************************************************
public class SendAccountUsingRESTAPI {
private final String clientId = 'XXXX1qDQKpai6KLQyEHS3pvpCcteS2b5rWP2A6JpuqP._w2byvgpP8EC56LtyVNOg7.p7';
private final String clientSecret = '17825308XXX';
private final String username = 'abaranwal@kloudrac.com.full';
private final String password = 'XXX';
public class deserializeResponse
{
public String id;
public String access_token;
}
public String ReturnAccessToken (SendAccountUsingRESTAPI acount)
{
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://test.salesforce.com/services/oauth2/token');
HttpResponse res = h.send(req);
deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
system.debug('@@@@access_token@@'+resp1 );
return resp1.access_token;
}
public static list<Contact> callgetContact (String accId)
{
SendAccountUsingRESTAPI acount1 = new SendAccountUsingRESTAPI();
String accessToken;
accessToken = acount1.ReturnAccessToken (acount1);
list<Contact> LstContact=new List<Contact>();
if(accessToken != null){
String endPoint = 'https://cs30.salesforce.com/services/apexrest/v1/getContacts/' +accId;
//String jsonstr = '{"accId" : "' + accId+ '"}';
Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
//req1.setBody(jsonstr);
req1.setMethod('GET');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);
String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
system.debug('@@@RESPONSE@@'+trimmedResponse);
JSONParser parser = JSON.createParser(res1.getBody());
set<Contact> contList=new set<Contact>();
while (parser.nextToken() != null) {
//Id
if((parser.getCurrentToken() == JSONToken.FIELD_NAME) ){
Contact cont;
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Id')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
string sId= parser.getText();
cont=new Contact();
cont.Id=sId;
system.debug('Id@@@' + sId);
parser.nextToken();
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'Name')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
string sName= parser.getText();
cont.LastName=sName;
system.debug('Name@@@' + sName );
}
parser.nextToken();
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'Email')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
string sEmail= parser.getText();
cont.Email=sEmail;
system.debug('Email@@@' + sEmail);
}
}
contList.add(cont);
}
contList.remove(null);
}
LstContact.AddAll(contList);
system.debug('ContList@@@@'+Json.serialize(LstContact));
}
return LstContact;
}
}
*********************************************************************
Yes now we are ALL set, you can call this "callgetContact " in your visualforce Controller Class or in your Apex Trigger wherever you wanted to Show the List of Contacts..from Source Org.
Access List of Contact Using Following Syntax
SendAccountUsingRESTAPI.callgetContact('001n0000007lQ90');
Need help, please call me +91-95823-88885 or email me amulhai@gmail.com
48 Comments
Prefect Solution.
ReplyDeleteIts really good steps to Salesforce to Salesforce Integration Using REST API and OAuth .
ReplyDeleteOwesome solution with step by step description.
ReplyDeleteif i want to integration with legacy systm then.....
ReplyDeletecan u explain integretion with legacy system any one
ReplyDeletewhat legacy system you have. we can integrate with java, .net
DeleteI hope this is the custom REST api, correct me if I'm wrong
ReplyDeleteyes, this is custom rest api
Deletehi salesfroce 2 salesfroce integration is paossibke by using REST API. same as one salesforce Organization data integrate with Other Organization not salesforce is it possible.
ReplyDeleteif Possible how to do.....
I did get your point. If Data Transfer you are looking from org to another Org. use ETL tool or Dataloader CLI.
DeleteThanks for sharing the informative post on salesforce integration.
ReplyDeleteSalesforce Integration Services
This comment has been removed by the author.
ReplyDeleteCan you please share the visual force code too. thanks
ReplyDeletethanks for your information excelllent blog good support for salesforce
ReplyDeletesales force mostly important topices
When we login with user name and password, salesforce also provides a security token string that must be appended to the password. How is that handled here? Should we hardcode that security token in the code? when the password/token changes for the integrated user, the code must be changed??
ReplyDeleteHi,
ReplyDeleteI am trying to learn integration using the code you provided. However when I try to display contact information from source org in my destination org(using vf page) I get the error :
Status Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]
02:06:53.0 (8960006)|CALLOUT_REQUEST|[19]|System.HttpRequest[Endpoint=https://ravideepappbuilder-dev-ed.my.salesforce.com/oauth2/token, Method=POST]
02:06:53.0 (69643751)|CALLOUT_RESPONSE|[19]|System.HttpResponse[Status=Not Found, StatusCode=404]
I think it means my endpoint url is wrong but I did how it was asked and still doesn't work.Here's my endpoint url:
https://ravideepappbuilder-dev-ed.my.salesforce.com/oauth2/token
Can you kindly tell me what is wrong in it or what I am missing.
Hi, hope it's resolved for you. if not, let me tell you, you missed to add '/services'. Use below.
Deletehttps://ravideepappbuilder-dev-ed.my.salesforce.com/services/oauth2/token
Very good and easy understanding, Why cant you add a VF page code as well where all contacts are organized in pageblocktable.
ReplyDeletecan you please provide the trigger code for callout
ReplyDeleteHey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Website. Please feel free to visit our site. Thank you for sharing.
ReplyDeleteSalesforce Services
Keep Posting:)
For every request, it'll take 2 api calls. 1- get access_token and 2 - get contact. Can we store the access_token in somewhere, check the token valid. if not, we'll refresh the token, if token still valid, we can continue use it.
ReplyDeleteMakes sense, if possible.
DeleteSo nice to read.Its very useful for me to get more valuable info about Medical Billing Coding Service.Thanks for it.Keep going.
ReplyDeletehtml training in chennai |
html5 training in chennai |
html5 courses in chennai
Most of the healthcare institutes are procuring the software packages for their coding and billing process from medical
ReplyDeleteSalesforce Training in Chennai |
Salesforce Training |
Salesforce Training Institutes in Chennai
how do i create an email escaltion from one URL of salesforce to another ?
ReplyDeleteHi, I am trying perform the same as per this post, and my code is also similar except the Parser Instance. But I am getting an error when I tried to run the class through Anonymous window. The error is "System.HttpResponse[Status=Bad Request, StatusCode=400]". Any help would be highly appreciated. Thanks!
ReplyDeleteReally nice post, Thanks for sharing such an informative post.
ReplyDeleteTo Create Bulk Fields in Salesforce click this links
I really enjoyed while reading your article and it is good to know the latest updates. Do post more. Please also read my topics about
ReplyDeleteSalesforce Products
Salesforce Consultant
Salesforce Integration Service
ExpressTech Software Solutions is known as best custom Rest API Integration Services in India, USA, has the best in the industry specialization to deliver seamless API integration and development services. Our system integration services make sure that your web application or website is without flawlessly integrated with the standard or custom APIs.
ReplyDeleteHow to write a test class for above class?
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI want to insert those contact records in target org. Please help me out of this.....I need full code for inserting.......
ReplyDeleteI want to insert these contacts in target org. Please help???
ReplyDeletevery nice post. thanks for sharing blog.
ReplyDeletePlease also read my topics about:
Salesforce cpq transformation
Salesforce integration services
Salesforce service cloud integration
salesforce optimization
We have prepared Cloud Consultant Sample Paper
(ADM-201) certification sample questions to make you aware of actual exam properties. http://www.salesforcecertifications.com/ADM201.html
Thanks for the valible information sales force
ReplyDeleteSalesforce Billing training india, Salesforce Online training Contact us@ +91 9550102466.
Techforce services is a Salesforce Consulting Services in Australia Specializing in delivering end to end Salesforce solutions ,Consulting, Implementation DevOps partners in Australia We deliver applications and services more rapidly and reliably, but it’s more than a methodology – it cuts to the very core. Salesforce Data Analytics let us help you become a data driven organization and ensure your data is working hard for your business, This includes implemention
ReplyDeleteSalesforce consulting companies
Salesforce top partners
Staff augmentation companies
Salesforce DevOps services
Salesforce integration companies
Salesforce Implementation services
Salesforce Health Check
Salesforce DevOps
Managed project services
you have written an excellent blog.. keep sharing your knowledge...
ReplyDeleteSelenium with Python Online Training
Python Automation Testing Course
Selenium with Python Training
Selenium with Python Course
Selenium with Java Training
Selenium with Java Course
Selenium with Java Online Training
Learn Selenium with Java Online
Great Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
ReplyDeleteWeb Designing Course In Chennai
Web Designing Course Online
Web Designing Course In Coimbatore
Web Development Training In Chennai
Web Development Course In Chennai
This post is so usefull and informative.keep updating with more information...
ReplyDeleteSwift Developer Course in Mumbai
Swift Developer Course in Ahmedabad
Swift Developer Course in Cochin
Swift Developer Course in Trivandrum
Swift Developer Course in Kolkata
Hello, Amul! Thanks for this helpful article. I also recommend another one: https://skyvia.com/blog/salesforce-to-salesforce-integration, which also talks about Salesforce to Salesforce integration using rest API. I think it complements your guide and shows some other alternative methods.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI appreciate your website. Its really very help full. Thanks for sharing the great information.
ReplyDeleteBiobanks| biorepositories
tissue-bank|human-biospecimens
human-samples|patient-samples
human-tissue-samples
Do you want to know about Nina Marie Daniele Net Worth, early life, biography, age, and relationship status?
ReplyDeleteStreamline operations by integrating two Salesforce instances using REST API and OAuth. Enjoy consistent data, real-time updates, and improved collaboration. how to use watch any nfl game Follow secure authentication steps, map data accurately, and test thoroughly for optimal results. Elevate efficiency and decision-making with this powerful integration
ReplyDeleteEye4Future is the best API Integration Services provider in India. our API Integration Services make sure that your website is without perfectly combined with the standard or custom APIs. https://www.eye4future.com/api-integration-services/
ReplyDeleteGreat 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
Digital Transformation in India: A Landscape of Growth
ReplyDeleteIndia's business landscape is undergoing a rapid digital transformation. Companies are adopting digital transformation services to optimize operations, enhance customer experience and gain a competitive edge. These services encompass a wide range of solutions ranging from cloud migration and data analytics to mobile app development and automation.