How do Lightning Components interact with Salesforce?

Source: How do Lightning Components interact with Salesforce?


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:

Open a record create or edit page, or navigate to a record in salesforce lightning


 To create a new record:
createRecord : function (component, event, helper) {
    var createRecordEvent = $A.get("e.force:createRecord");
        "entityApiName": "Contact"


To Edit a existing record:

editRecord : function(component, event, helper) 
    var editRecordEvent = $A.get("e.force:editRecord");
      "recordId": component.get("")


To navigate to a list view, set the list view ID on the listViewId attribute and fire the event.

gotoList : function (component, event, helper) {
    var action = component.get("c.getListViews");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            var listviews = response.getReturnValue();
            var navEvent = $A.get("e.force:navigateToList");
                "listViewId": listviews.Id,
                "listViewName": null,
                "scope": "Contact";

This Apex controller returns all list views for the contact object

public static List&lt;ListView&gt; getListViews() {
    List<ListView> listviews = 
        [SELECT Id, Name FROM ListView WHERE SobjectType = 'Contact'];
     // Perform isAccessible() check here
    return listviews;


Navigates to the object home specified by the scope attribute.

navHome : function (component, event, helper) {
    var homeEvent = $A.get("e.force:navigateToObjectHome");
        "scope": "myNamespace__myObject__c"


 Navigates to the related list specified by parentRecordId.
gotoRelatedList : function (component, event, helper) {
    var relatedListEvent = $A.get("e.force:navigateToRelatedList");
        "relatedListId": "Cases",
        "parentRecordId": component.get("")


Navigates to an sObject record specified by recordId.

createRecord : function (component, event, helper) {
    var navEvt = $A.get("e.force:navigateToSObject");
      "recordId": "00QB0000000ybNX",
      "slideDevName": "related"


 Navigates to the specified URL.

1)   Using a relative URL.

gotoURL : function (component, event, helper) {
    var urlEvent = $A.get("e.force:navigateToURL");
      "url": "/006/o"

2)   Using external website when the link is clicked.

navigate : function(component, event, helper) {
    //Find the text value of the component with aura:id set to "address"
    var address = component.find("address").get("v.value");
    var urlEvent = $A.get("e.force:navigateToURL");
      "url": '' + address