How to use Nested Components in Lightning Component Using Salesforce Lightning Design System

Hi Guys,

In my last post I showed how to use SVG Icon in Lightning Component. In this post, I will be showing you how to build a Nested component in Lightning Component using Salesforce Lightning Design System. In this you can see Tree view of Accounts and its related contacts like:

Screenshot_2015-11-04-20-23-16

Screenshot_2015-11-04-20-23-30
Let’s walk through code by few steps:

Screenshot_2015-11-04-20-22-58

Step-1: AccConListController.apxc

public class AccConListController {
    @AuraEnabled
    public static List<Account> getAccounts() {
        List<Account> accounts=[SELECT Id, Name, (select name, Phone, Email FROM Contacts) FROM Account limit 1000];
        return accounts;
    }
}

In this class we create a funtion which is used for getting accounts and its related contacts.

Step-2: AccountRow.cmp

<aura:component >
    <aura:attribute name="acc" type="Account" />
    <aura:attribute name="ext" type ="String" default="plus"/>
    <li  id="tree0-node0" class="slds-tree__branch slds-is-open" role="treeitem" aria-level="1" aria-expanded="true">
        <div class="slds-tree__item">
            <aura:if isTrue="{!v.acc.Contacts[0] != null}">
                <aura:if isTrue="{!v.ext=='plus'}">
                    <div id="plus" >➕</div>
                    <aura:set attribute="else">
                        <div id="minus">➖</div>
                    </aura:set>
                </aura:if> 
                &nbsp;
                <aura:set attribute="else">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </aura:set>
            </aura:if> 
            <a id="tree0-node0-0-link"  tabindex="-1" onclick="{!c.showHidePanel}" role="presentation">{!v.acc.Name}</a>
        </div>
        
        <ul aura:id="{!v.acc.Id}" id="{!v.acc.Id}" style="display:none;" class="slds-tree__group slds-nested" role="group" aria-labelledby="tree0-node0-link">
            <aura:iteration items="{!v.acc.Contacts}" var="con">
                <li id="tree0-node0-1" class="slds-tree__item" role="treeitem" aria-level="2" style="margin-left: 20px;">
                    <a href="#" role="presentation" class="slds-truncate" style="color: darkgoldenrod;">{!con.Name}</a>    	
                </li>
            </aura:iteration>
        </ul>
    </li>
</aura:component>

This is a Child component and it is used for show an account name and its related contacts.

Step-3: AccountRowController.js

({
	showHidePanel : function(component, event, helper) {
        var id=component.get("v.acc.Id");        
        var e=document.getElementById(id);      
        if (e.style.display == 'block' || e.style.display==''){
            e.style.display = 'none';
            component.set("v.ext","plus");
        }else{
            e.style.display = 'block';
            component.set("v.ext","minus");
        } 
	},
})

This is controller of AccountRow Component.

Step-4: AccountTree.cmp

<aura:component controller="AccConListController" implements="force:appHostable">
    <ltng:require styles="/resource/SLDS/assets/styles/salesforce-lightning-design-system-vf.css" 
                  scripts="/resource/jquerymin" 
                  afterScriptsLoaded="{!c.doInit}" />    
    <aura:attribute name="Accounts" type="Account[]" />
    <div class="slds">
        <div class="slds-page-header">
            <div class="slds-grid">
                <div class="slds-col slds-has-flexi-truncate">
                    <div class="slds-media">
                        <div class="slds-media__figure">
                            <c:svgIcon svgPath="/resource/SLDS/assets/icons/standard-sprite/svg/symbols.svg#process" category="standard" size="large" name="user" />
                        </div>
                        <div class="slds-media__body">
                            <p class="slds-text-heading--label">Tree View</p>
                            <div class="slds-grid">
                                <h1 class="slds-text-heading--medium slds-m-right--small slds-truncate slds-align-middle">Account -> Contact</h1>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /slds-col-->                        
            </div>   
            <!-- /slds-grid-->                 
        </div>
        <!-- /slds-page-header-->
        <div class="slds-tree-container" role="application">
            <ul class="slds-tree" role="tree" aria-labelledby="treeheading" aria-activedescendant="tree0-node0">
                <aura:iteration items="{!v.Accounts}" var="acc">        	
                    <c:AccountRow acc="{!acc}" />
                </aura:iteration>
            </ul>
        </div>
    </div>
</aura:component>

This is parent component that holds AccountRow component as a nested component. And also i am using here SVG Icon in header. For more detail about SVG Icon see in my previous post or click here.

Step-5: AccountTreeController.js

({
	doInit : function(component, event, helper) {          
        helper.getAccounts(component);          
    },
    
    showPanel : function(component, event, helper){        
        helper.onLoadPage(component); 
	},
    
})

This is controller of AccountTree Component.

Step-6: AccountTreeHelper.js

({
	//Fetch the Accounts from the Apex controller
    getAccounts: function(component) {        
        var action = component.get("c.getAccounts");
        //Set up the callback
        var self = this;
        action.setCallback(this, function(actionResult) {
            component.set("v.Accounts", actionResult.getReturnValue());            
        });        
        $A.enqueueAction(action);                
    },        
})

This is helper of AccountTree Component. Its getAccounts() function calls getAccounts() method of AccConListController.apxc class

Advertisements

How to use SVG Icon in Lightning Component Using Salesforce Lightning Design System

Step 1: Create the Lightning Component

Log into your org, and open the Developer Console. Create a new Lightning component from the menu: File > New > Lightning Component

Name your component: svgIcon

Step 2: Write code in svgIcon.cmp using Component tab

<aura:component>
	<aura:attribute name="svgPath" default="" type="String" description="the path for the icon in the static resource, this will be use in a SVG use tag" />
	<aura:attribute name="name" default="" type="String" description="Symbol name of icon" />
	<aura:attribute name="class" default="" type="String" description="the class of this SVG tag, can be use for CSS purpose" />
	<aura:attribute name="containerClass" default="" type="String" description="Container class name for span container of icon" />
	<aura:attribute name="category" default="" type="String" description="Category of icon- action, standard, utility etc." />
	<aura:attribute name="size" default="" type="String" description="Size of icon-- small, medium, large" />
	<aura:attribute name="assistiveText" default="" type="String" description="Description name of icon" />
	<span aura:id="container" class="{!v.containerClass}">
		<span aura:id="assistiveText" class="slds-assistive-text">{!v.assistiveText}</span>
	</span>
</aura:component>

Step 3: Write code in svgIconHelper.js using Helper tab

({
	renderIcon: function(component) {
		var prefix = "slds-";
		var svgns = "http://www.w3.org/2000/svg";
		var xlinkns = "http://www.w3.org/1999/xlink";
		var size = component.get("v.size");
		var name = component.get("v.name");
		var classname = component.get("v.class");
		var category = component.get("v.category");

		var containerClassName = [
			prefix+"icon__container",
			prefix+"icon-"+category+"-"+name,
			classname
		].join(' ');
		var iconClassName = prefix+"icon "+prefix+"icon--" + size;
		component.set("v.containerClass", containerClassName);

		var svgroot = document.createElementNS(svgns, "svg");
		svgroot.setAttribute("aria-hidden", "true");
		svgroot.setAttribute("class", iconClassName);
		svgroot.setAttribute("name", name);

		// Add an "href" attribute (using the "xlink" namespace)
		var shape = document.createElementNS(svgns, "use");
		shape.setAttributeNS(xlinkns, "href", component.get("v.svgPath"));
		svgroot.appendChild(shape);

		var container = component.find("container").getElement();
		container.insertBefore(svgroot, container.firstChild);
	}
})

Step 4: Write code in svgIconRenderer.js using Renderer tab

({
	render: function(component, helper) {
		// By default, after the component finished loading data/handling events,
		// it will call this render function this.superRender() will call the
		// render function in the parent component.
		var ret = this.superRender();

		// Calls the helper function to append the SVG icon
		helper.renderIcon(component);
		return ret;
	}
})

Step 5: Use the New Component

Now we create new Lightning Component and paste svg component like as below image:

svgicon2

And Now write below code in component:

<aura:component>
    <ltng:require styles="/resource/SLDS/assets/styles/salesforce-lightning-design-system-vf.css"/>
    <div class="slds">
        <div class="slds-page-header">
            <div class="slds-grid">
                <div class="slds-col slds-has-flexi-truncate">
                    <div class="slds-media">
                        <div class="slds-media__figure">
                            <c:svgIcon svgPath="/resource/SLDS/assets/icons/standard-sprite/svg/symbols.svg#process" category="standard" size="large" name="user" />
                        </div>
                        <div class="slds-media__body">
                            <p class="slds-text-heading--label">SVG Icon</p>
                            <div class="slds-grid">
                                <h1 class="slds-text-heading--medium slds-m-right--small slds-truncate slds-align-middle">Set your SVG</h1>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /slds-col-->                        
            </div>   
            <!-- /slds-grid-->                 
        </div>
        <!-- /slds-page-header-->
	</div>    
	<!-- /slds-->
</aura:component>

After the above step, now its time to show preview using Application and this preview is viewing like below image:

svgicon

Note: Here Static Resource is named SLDS.

Thanks.

Create e-Signature with Salesforce Lightning Design System

Hi All,
In my previous post I have shown you how we can Meta data Api using Oauth 2.0 workflow.
Today I will tell you how we can use canvas to draw your signature and how we can attach this signature with your information in Salesforce lightning Design System.

When insert new contact it will look like this :
new

And when update existing contact it will look like this (using contact id in url with conId parameter):
update

Let’s walk through code:

Create ContactWithSignatureController class:

global with sharing class ContactWithSignatureController {
    public contact con {get;set;}
    public boolean flag {get;set;}
    public string attId {get;set;}
    public ContactWithSignatureController() {
        String conId = apexPages.CurrentPage().getParameters().get('conId');
        con = new contact();
        flag = true;
        attId = '';
        if (conId != null && conId.trim() != '') {
            con = [select id, firstname, lastname, name, phone from contact where id = : conId];
            flag = false;
            list < attachment > attIds = [select id from Attachment where name = 'Signature Image'
                and parentId = : conId
            ];
            if (attIds.size() > 0) {
                attId = attIds[0].id;
            }
        }
    }
    public void saveCon() {
        upsert con;
    }

    @RemoteAction
    global static String saveSignature(String imageUrl, String pId) {
        try {
            delete[select id from Attachment where name = 'Signature Image'
                and parentId = : pId];
            Attachment accSign = new Attachment();
            accSign.ParentID = pId;
            accSign.Body = EncodingUtil.base64Decode(imageUrl);
            accSign.contentType = 'image/png';
            accSign.Name = 'Signature Image';
            accSign.OwnerId = UserInfo.getUserId();
            insert accSign;
            return 'success';

        } catch (Exception e) {
            system.debug('---------- ' + e.getMessage());
            return JSON.serialize(e.getMessage());
        }
        return null;
    }
}

Create page with “ContactWithSignature” name

<apex:page id="pg" controller="ContactWithSignatureController" showHeader="false" sidebar="false" standardStylesheets="false">
    <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

    <head>
        <apex:stylesheet value="{!URLFOR($Resource.SLDS080, 'assets/styles/salesforce-lightning-design-system-vf.css')}" />
        <STYLE TYPE="text/css">
            ::-webkit-scrollbar {
                width: 8px;
                height: 8px;
            }
            
            ::-webkit-scrollbar-track-piece {
                background-color: #a8b7c7;
                border-radius: 20px;
            }
            
            ::-webkit-scrollbar-thumb:vertical {
                height: 30px;
                background-color: #e0e5ee;
                border-radius: 20px;
            }
        </STYLE>

    </head>
    <apex:form id="mainForm">
        <apex:outputPanel id="rnd">
            <script>
                function SaveSign() {
                    window.frames[0].frameElement.contentWindow.saveSignature("{!con.id}");
                }
            </script>
        </apex:outputPanel>

        <apex:actionFunction action="{!saveCon}" name="saveCon" reRender="rnd" oncomplete="SaveSign();return false;" />
        <div class="slds">
            <div class="slds-page-header">
                <div class="slds-grid">
                    <div class="slds-col slds-has-flexi-truncate">
                        <div class="slds-media">
                            <div class="slds-media__figure">
                                <svg aria-hidden="true" class="slds-icon slds-icon--large slds-icon-standard-user">
                                    <use xlink:href="{!URLFOR($Resource.SLDS080, 'assets/icons/standard-sprite/svg/symbols.svg#contact')}"></use>
                                </svg>
                            </div>
                            <div class="slds-media__body">
                                <p class="slds-text-heading--label">Contact</p>
                                <div class="slds-grid">
                                    <h1 class="slds-text-heading--medium slds-m-right--small slds-truncate slds-align-middle">
                                        <apex:outputPanel rendered="{!flag}">
                                            New Contact
                                        </apex:outputPanel>
                                        <apex:outputPanel rendered="{!!flag}">
                                            Update Contact
                                        </apex:outputPanel>
                                    </h1>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- /slds-col-->
                </div>
                <!-- /slds-grid-->
            </div>
            <!-- /slds-page-header-->
            <div class="container">
                <div class="slds-form--horizontal slds-m-right--xx-large slds-m-top--xx-large slds-p-right--xx-large">
                    <div class="slds-form-element">
                        <label class="slds-form-element__label" for="sample1">First Name</label>
                        <div class="slds-form-element__control">
                            <apex:inputField value="{!con.firstname}" styleClass="slds-input" html-placeholder="First Name" />
                        </div>
                    </div>
                    <div class="slds-form-element">
                        <label class="slds-form-element__label" for="sample1">Last Name</label>
                        <div class="slds-form-element__control">
                            <apex:inputField value="{!con.lastname}" styleClass="slds-input" html-placeholder="Last Name" />
                        </div>
                    </div>
                    <div class="slds-form-element">
                        <label class="slds-form-element__label" for="sample1">Phone</label>
                        <div class="slds-form-element__control">
                            <apex:inputField value="{!con.phone}" styleClass="slds-input" html-placeholder="Phone" />
                        </div>
                    </div>
                    <div class="slds-form-element">
                        <span class="slds-form-element__label">Signature </span>
                        <div class="slds-form-element__control">
                            <iframe src="/apex/ContactWithSignatureComponent?conId={!con.id}" style="border:none; width:360px; height:125px"></iframe>
                        </div>
                        <apex:outputPanel rendered="{!if(!flag && attId!='',true,false)}">
                            <br/>
                            <span class="slds-form-element__label">Current Signature </span>
                            <div class="slds-form-element__control">
                                <apex:image url="/servlet/servlet.FileDownload?file={!attId}" />
                            </div>
                        </apex:outputPanel>
                    </div>
                    <div class="slds-form-element">
                        <div class="slds-button-group slds-float--right" role="group">
                            <apex:commandButton value="Submit" onclick="saveCon();return false;" styleClass="slds-button slds-button--neutral" />
                            <apex:commandButton value="Clear" onclick="window.frames[0].frameElement.contentWindow.clearSign();return false;" styleClass="slds-button slds-button--neutral" />
                        </div>
                    </div>
                </div>
            </div>
			<!-- /container-->
		</div>
    </apex:form>

    </html>
</apex:page>

Create another page with “ContactWithSignatureComponent” name

<apex:page controller="ContactWithSignatureController" standardStylesheets="false" sidebar="false" showHeader="false">
    <apex:includeScript value="/soap/ajax/28.0/connection.js" />
    <apex:form id="pbform">
        <div>
            <canvas id="signatureCanvas" height="100px" width="350px" style="    border: 1px solid #d8dde6; border-radius: 8px;"></canvas>
        </div>
    </apex:form>
    <script>
        var canvas;
        var context;
        var drawingUtil;
        var isDrawing = false;
        var pId = '';
        var prevX, prevY, currX, currY = 0;
        var pId;

        function DrawingUtil() {
            isDrawing = false;
            canvas.addEventListener("mousedown", start, false);
            canvas.addEventListener("mousemove", draw, false);
            canvas.addEventListener("mouseup", stop, false);
            canvas.addEventListener("mouseout", stop, false);
            canvas.addEventListener("touchstart", start, false);
            canvas.addEventListener("touchmove", draw, false);
            canvas.addEventListener("touchend", stop, false);
            w = canvas.width;
            h = canvas.height;
        }

        function start(event) {
            event.preventDefault();

            isDrawing = true;
            prevX = currX;
            prevX = currY;
            currX = event.clientX - canvas.offsetLeft;
            currY = event.clientY - canvas.offsetTop;

            context.beginPath();
            context.fillStyle = "cadetblue";
            context.fillRect(currX, currY, 2, 2);
            context.closePath();

        }

        function draw(event) {
            event.preventDefault();
            if (isDrawing) {
                prevX = currX;
                prevY = currY;
                currX = event.clientX - canvas.offsetLeft;
                currY = event.clientY - canvas.offsetTop;
                context.beginPath();
                context.moveTo(prevX, prevY);
                context.lineTo(currX, currY);
                context.strokeStyle = "cadetblue";
                context.lineWidth = "2";
                context.stroke();
                context.closePath();
            }
        }

        function stop(event) {
            if (isDrawing) {
                context.stroke();
                context.closePath();
                isDrawing = false;
            }
        }

        function clearSign() {
            context.clearRect(0, 0, w, h);
        }

        canvas = document.getElementById("signatureCanvas");
        context = canvas.getContext("2d");
        context.strokeStyle = "black";
        context.lineWidth = "2";
        drawingUtil = new DrawingUtil(canvas);

        function saveSignature(conId) {
            var strDataURI = canvas.toDataURL();
            strDataURI = strDataURI.replace(/^data:image\/(png|jpg);base64,/, "");
            pId = conId;
            var result = ContactWithSignatureController.saveSignature(strDataURI, conId, processResult);

        }

        function processResult(result) {
            window.parent.location.href = '/apex/ContactWithSignature?conId=' + pId;
        }
    </script>
</apex:page>

Now its time to preview the ContactWithSignature page and fill contact information with e-Signature. And When you click on “Submit” button it will redirect to detail page of contact.

For more information mail me on this Email Address: sushil.verma1988@gmail.com

Thanks

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.
remoteaccess_oauth_web_flow

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">
</apex:page>

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:
site

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.
connectedApp
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:
connectedApp2

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( 'https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=' + 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;}
    //constructor
    public CallBackURLController(){
        string vrsn=[select name from version__c].name;
        string Accesscode=ApexPages.currentPage().getParameters().get('code');
        Accesscode=Accesscode.replace('=','%3D').trim();
        cd=Accesscode;
        string clientId='XXXXXXXXXXXXXXXXXXXXXX';
        String clientSecret='XXXXXXXXXXXXXXXXXXXXXX';
        String redireUri='https://forcedroid-developer-edition.ap2.force.com/callbackurl';
        string loginUri='https://login.salesforce.com';
        string ContentType = 'application/json';
 
        ///// Get Access Token
        HttpRequest req = new HttpRequest();  
        req.setMethod('POST');
        string reqbody='grant_type=authorization_code' +
            '&client_id=' + clientId +
            '&client_secret=' + clientSecret +
            '&code=' + Accesscode +
            '&redirect_uri=' + redireUri;
        req.setEndpoint(loginUri+'/services/oauth2/token?'+reqbody);
        Http http = new Http();  
        HTTPResponse res = http.send(req);
        bodyCode=res.getBody();
        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'));
        hd=header;        
        
        ///// Get User Info
        HttpRequest reqInfo = new HttpRequest();  
        reqInfo.setMethod('POST');
        reqInfo.setEndpoint(loginUri+'/services/oauth2/userinfo');
        reqInfo.setHeader('Content-Type', ContentType);
        reqInfo.setHeader('Authorization', header);
        Http httpInfo = new Http();  
        HTTPResponse resInfo = httpInfo.send(reqInfo);
        bodyInfo=resInfo.getBody();
        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);
        queryUri=queryUri+'?q=select+id,name,phone+from+contact+where+phone+!=null+limit+1000';  
        HttpRequest reqQry = new HttpRequest();
        reqQry.setEndpoint(queryUri);
        reqQry.setMethod('GET');        
        reqQry.setHeader('Authorization', header);
        reqQry.setHeader('Content-Type', ContentType);
        Http httpQry = new Http();
        HTTPResponse resQry = httpQry.send(reqQry);
        bodyInfo=resQry.getBody();
        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": "https://login.salesforce.com/id/00D28000000c5B3EAI/00528000000GPjpAAG",
    "issued_at": "xxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer",
    "instance_url": "https://ap2.salesforce.com",
    "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:

{"sub":"http://login.salesforce.com/id/00Dx000.../005x000...",
"user_id":"005x000...","organization_id":"00Dx000...",
"preferred_username":"user1@1135222488950007.com",
"nickname":"user1.3860098879512678E12",
"name":"na1 LastName",
"email":"user1@1135222488950007.com",
"email_verified":true,"given_name":"na1","family_name":"LastName",
"zoneinfo":"America/Los_Angeles",
"photos":{"picture":"http://na1.salesforce.com/profilephoto/005/F","thumbnail":"http://na1.salesforce.com/profilephoto/005/T"},
"profile":"http://na1.salesforce.com/005x000...",
"picture":"http://na1.salesforce.com/profilephoto/005/F",
"address":{"country":"us"},
"urls":{"enterprise":"http://na1.salesforce.com/services/Soap/c/{version}/00Dx00...",
"
"partner":"http://na1.salesforce.com/services/Soap/u/{version}/00Dx00...",
"rest":"http://na1.salesforce.com/services/data/v{version}/",
"sobjects":"http://na1.salesforce.com/services/data/v{version}/sobjects/",
"search":"http://na1.salesforce.com/services/data/v{version}/search/",
"query":"http://na1.salesforce.com/services/data/v{version}/query/",
"recent":"http://na1.salesforce.com/services/data/v{version}/recent/",
"profile":"http://na1.salesforce.com/005x000...",
"feeds":"http://na1.salesforce.com/services/data/v{version}/chatter/feeds",
"groups":"http://na1.salesforce.com/services/data/v{version}/chatter/groups",
"users":"http://na1.salesforce.com/services/data/v{version}/chatter/users",
"feed_items":"http://na1.salesforce.com/services/data/v{version}/chatter/feed-items"},
"active":true,"user_type":"STANDARD","language":"en_US","locale":"en_US","utcOffset":-28800000,"updated_at":"2013-12-02T18:46:42.000+0000"
}

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="{!con.name}"/>
             <apex:column value="{!con.phone}"/>
         </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

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}"/>
  </apex:form>
</apex:page>

Step-6:Now it’s time to testing
Now we have to click preview button of AuthCall page and then we found that screen:

test

After that we have to click on Test button and then we will seeing login screen:

login

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:
output

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

force:createRecord:

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

force:editRecord

To Edit a existing record:

editRecord : function(component, event, helper) 
    var editRecordEvent = $A.get("e.force:editRecord");
    editRecordEvent.setParams({
      "recordId": component.get("v.contact.Id")
   });
    editRecordEvent.fire();
}

force:navigateToList

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");
            navEvent.setParams({
                "listViewId": listviews.Id,
                "listViewName": null,
                "scope": "Contact";
            });
            navEvent.fire();
        }
    });
    $A.enqueueAction(action);
}

This Apex controller returns all list views for the contact object

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

force:navigateToObjectHome

Navigates to the object home specified by the scope attribute.

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

force:navigateToRelatedList

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

force:navigateToSObject

Navigates to an sObject record specified by recordId.

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

force:navigateToURL

 Navigates to the specified URL.

1)   Using a relative URL.

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

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");
    urlEvent.setParams({
      "url": 'https://www.google.com/maps/place/' + address
    });
    urlEvent.fire();
}