Salesforce to Salesforce Integration with Oauth 2.0 and Named Credentials

Salesforce to Salesforce makes it easy for businesses using Salesforce to share records and get updated data on shared records. For example, you can share lead and opportunity data with partners. Salesforce to Salesforce lets your business partners easily integrate your data with their Salesforce records. 
Salesforce to Salesforce Integration with Named Credentials

There are different ways to integrate the two Salesforce instances
  1. Using Auth provider and Named Credentials 
  2. Using Salesforce Connect
In this blog we will be focusing on using Auth provider and Named Credentials. 

Implementation:

Pre-requisites: 
  1. Two Salesforce orgs(Source and Destination)
  2. Dummy records on Account or any other object in Source org.
Steps:
  1. Source Org(amazing-cloudy-68694-dev-ed):
  2. Destination Org(einsteinyogi-dev-ed):
Now let's deep dive into the implementation steps.
  1. Create Connected App in Source Org: First step is to create a connected app at the Source org which is responsible to provide the data to the destination org. To know more on why we need connected app and its usages, please click here.
    • Login into Source Org(amazing-cloudy-68694-dev-ed in our case)
    • Navigate to Setup | Apps | App Manager  and click on New Connected App button.
    • Provide all required details on new Connected App.
    • Check Enable OAuth Settings checkbox to use OAuth
    • In the callback URL, you can provide any valid URL temporarily. We will come back later again to provide the correct callback URL. I have used https://trailhead.salesforce.com/ as a callback URL
    • Select SCOPE as defined below:
      • Manage user data via APIs (api) - Used to query data from Salesforce
      • Perform requests at any time (refresh_token, offline_access) - Used to maintain the refresh token which will be used by authentication provider in order to get new access token automatically when refresh token expire.
    • Leave the rest of the configuration to default. Your new Connected App page will look like below
    • Click Save
    • Once the record is saved and you choose to continue, you will be provided with the Consumer Secret and Consumer Key as shown below.
    • We will be needing both Consumer Key and Consumer Secret in our destination org. So copy and keep them at the safe place.
  2. Create Auth Provider in Destination Org: 
    • Login into Destination Org(einsteinyogi-dev-ed.lightning in our case)
    • Navigate to Setup | Identity | Auth. Provider and click on New
    •  Select Provider Type as Salesforce
    • Provide  all required information
      •  Consumer Key: Consumer Key of connected app from previous step
      • Consumer Secret: Consumer Secret of connected app from previous step
      • Authorize Endpoint URL: Leave it to default for prod, else if using for Sandbox replace the login with test keyword.
      • Token Endpoint URL: Leave it to default for prod, else if using for Sandbox replace the login with test keyword.
      • Default Scopes:  api refresh_token (Both should be separated by Space)
      • Finally Save the record.

        On save of the Auth Provider, you will get the Callback URL. Copy this URL and update in the Callback URL of connected app that we created in Source Org in previous step.

  3. Create Named Credentials in Destination Org: 
    • Login into Destination Org(einsteinyogi-dev-ed.lightning in our case)
    • Navigate to Setup | Security | Named Credentials and click on New Named Credentials
    • Provide the required information
      • Label: Salesforce to Salesforce
      • Name: Salesforce_to_Salesforce
      • URL: provide the URL of Salesforce instance in Classic mode.(Source org in our case, but make sure you add the classic instance and not the Lightning instance. You can get the classic instance by switching in to Classic mode)
      • Identity Type: Named Principal
      • Authentication Protocol: OAuth 2.0
      • Authentication Provider: Select the Auth Provider that you created above.
      • Start Authentication Flow on Save: Checked
    • Save the record.
    • When you save this record for the first time, you'll be taken to a login page where you have to login with the credentials of "Source Org" i.e. the org where you've created your connected app. Make sure that the authentication status is updated to Authenticated as <source org username> as shown below.
  4. Write APEX to test the Integration: You can write your own HTTP Callout class to access the Source org records in your destination org with all possible HTTP methods like GET, POST and others. Here are some basic examples that might help you
    • Get all Salesforce REST APIs: Copy below code and run anonymously in destination org's Developer Console.
      HttpRequest req = new HttpRequest();
      req.setEndpoint('callout:Salesforce_to_Salesforce/services/data/v54.0/');
      req.setMethod('GET');
      Http http = new Http();
      HTTPResponse resp = http.send(req);
      system.debug('Body:'+resp.getBody());
    • Get All Account records from Source org in Destination org: Copy below code and run anonymously in destination org's Developer Console.
      HttpRequest req = new HttpRequest();
      String query='select+Id,Name+from+Account';
      req.setEndpoint('callout:Salesforce_to_Salesforce/services/data/v54.0/query?q='+query);
      req.setMethod('GET');
      Http http = new Http();
      HTTPResponse resp = http.send(req);
      system.debug('Body:'+resp.getBody());
Note: You can consume standard as well custom web-service of other orgs using this approach.

Sometime you might get an error with the status code 302 like System.HttpResponse[Status=Moved Temporarily, StatusCode=302], follow the below steps to overcome this error.

  1. Get the header location using
    System.debug(resp.getHeader('Location'));
  2. Update the URL in the Named Credentials with this new location and Save again.

If you like this blog content and find inciteful, please comment and let me know. 

Comments

  1. how to add bind variable for soql where caluse select+Id,Name+from+Account+Where+id=+'a012239031324343' its just example id .while using above with where caluse getting bind variable error like that

    ReplyDelete
  2. Great insights on Salesforce Platform Events! Clear and helpful breakdown. Excited to apply these tips in my projects. Thanks for sharing


    salesforce time tracking

    salesforce timesheet

    Salesforce Time Tracking Integration

    ReplyDelete
  3. The inception of Messenger fake chatting pranks coincides with the rise of messaging apps as primary modes of communication wegocup lens
    brightening the day of friends, family, & internet users worldwide. However, it's crucial to approach these pranks
    wegocup chatting

    ReplyDelete

Post a Comment