A Comprehensive Guide To Salesforce And Google Contacts Integration
A Comprehensive Guide To Salesforce

A Comprehensive Guide To Salesforce And Google Contacts Integration

Sharing is caring!

In today’s highly competitive business landscape, every organization wants to implement business process mapping onto a CRM such as Salesforce to boost team productivity and efficiency. 

Businesses of all sizes can reap the benefits by integrating Salesforce with existing systems – both with on-premise and cloud solutions that can dramatically increase team productivity, encourage employee collaboration, and help convert turn leads into clients.

Salesforce, a top-rated customer relationship management tool, can be easily integrated with many third-party tools to empower sales, close more deals, and enhance the overall customer experience. In this blog, we’ll provide a brief introduction to Salesforce and Google Contacts integration.

Before delving deeper into the process of integrating Salesforce with Google Contacts, let’s have a quick introduction to Google Contacts.

What is Google Contacts?

Google Contacts is a powerful tool that you can use to organize, view, and manage your contacts. Google Contacts allows you to manage all your contacts in one place by creating contact groups separated between customers, vendors, prospects, and others. Google Contacts’s capabilities also include creating a personal mailing list and quickly sending messages or invitations from the calendar to a group of people you contact frequently.

Process To Integrate Salesforce With Google Contacts 

Below is the process we followed for Salesforce And Google Contacts Integration:

  • Firstly, we need to create a new project for Google Contacts on the Google Developer Console.
  • Create a VisualForce page and Apex class to get access token and will fetch all contact details.

Create Apex Class and Visualforce Page

  1. Create two apex classes googleAuthContactClass and getContactList.
  2. Create a visualforce page named googleAuthContactPage.

Enabling Google Contacts API Setting On Google Developer Console

Step 1: Click on Enable APIs and Services and go to the Contact API.

Step 2: Create a new project for Contact API

  1. After the above step, click on the create button to create the project.
  1. Configure the OAuth consent screen with User Type external and follow the below steps.

Step 3: Now, we need to create credentials for client ID and client secret.

Step 4: Copy the Client ID and Client Secret for further process.

Note: You need to write the following URL in the picture for Authorized Redirect URL and Consent Screen URL.

After clicking on the preview button on the VF page, we will get this URL.

Now we have to create an apex class and visualforce page.

  • Open Developer console and create 2 apex class named googleAuthContactClass and getContactList
  • Create a VisualForce page named googleAuthContactPage

Apex class:

1. googleAuthContactClass

public  class googleAuthContactClass{

    private String code;

    public string authtoken{get;set;}

    public string bodyprint{get;set;}

    public string phoneNumber{get;set;}

    public List<googleContactInfo> googleContactInfotList {get; set;}

    private string CLIENT_SECRET=’bc06rotrAxxxxxxxxxxxx2sId’;

    //Fill as per your registered app settings in google console

    private string CLIENT_ID=’953886262846-hcjl66i81mbs7vsxxxxxxxxxxxxl84hq.apps.googleusercontent.com’;//Fill as per your registered app settings in google console

    private string REDIRECT_URL=‘https://ajay-cloud-dev-ed–c.visualforce.com/apex/googleAuthContactPage‘;

    private string OAUTH_TOKEN_URL=’https://accounts.google.com/o/oauth2/token’;

    private string OAUTH_CODE_END_POINT_URL=’https://accounts.google.com/o/oauth2/auth’;

    private string GRANT_TYPE=’grant_type=authorization_code’;

    private string SCOPE=’https://www.googleapis.com/auth/contacts.readonly’;

    private string STATE=’/profile’;

    public googleAuthContactClass(){

        code = ApexPages.currentPage().getParameters().get(‘code’);

        //Get the access token once we have code

        if (code != ” && code != null) {

            AccessToken();

        }

    }

    public pagereference connect(){

        String x=OAUTH_CODE_END_POINT_URL+’?scope=’+EncodingUtil.urlEncode(SCOPE,’UTF-8′)+’&state=’+EncodingUtil.urlEncode(STATE,’UTF-8′)+’&redirect_uri=’+EncodingUtil.urlEncode(REDIRECT_URL,’UTF-8′)+’&response_type=code&client_id=’+CLIENT_ID;

        pagereference p=new pagereference(x);

        return p;

    }

    public pagereference AccessToken(){

        string codeparam=apexpages.currentpage().getparameters().get(‘code’);

        Http h = new Http();

        String body=’code=’+codeparam+’&client_id=’+CLIENT_ID+’&client_secret=’+CLIENT_SECRET+’&redirect_uri=’+REDIRECT_URL+’&’+GRANT_TYPE;

        HttpRequest req = new HttpRequest();

        req.setEndpoint(OAUTH_TOKEN_URL);

        req.setHeader(‘Content-Type’,’application/x-www-form-urlencoded’);

        req.setMethod(‘POST’);

        req.setBody(body);

        HttpResponse res = h.send(req);

        getAccessToken getAccessTokenFromGContactApi = (getAccessToken)JSON.deserialize(res.getBody(), getAccessToken.class);

        authtoken = getAccessTokenFromGContactApi.access_token;

        return null;

    } 

    public pagereference getContacts(){

        try{

            Http http = new Http();

            HttpRequest req = new HttpRequest();

            req.setEndpoint(‘https://www.google.com/m8/feeds/contacts/ajay.prasad%40cloudanalogy.com/full?alt=json‘);

//replace the above email with your email.

            req.setHeader(‘Authorization’, ‘Bearer ‘ + authtoken);

            req.setMethod(‘GET’);

            req.setTimeout(60 * 1000);

            HttpResponse response = http.send(req);

            bodyprint= response.getbody().replace(‘$’,’NN’);

            bodyprint = bodyprint.replace(‘id’,’googleId’);

            getContactList result = (getContactList)JSON.deserialize(bodyprint, getContactList.class);

            List<getContactList.entry>  entryList = result.feed.entry;

            googleContactInfotList = new List<googleContactInfo>();

            for(getContactList.entry entryObj: entryList){

                googleContactInfo googleContactInfoObj = new googleContactInfo();

                googleContactInfoObj.name = entryObj.title.NNt.replace(‘googleId’,’id’);

                List<String> emailList = new List<String>();

                for(getContactList.gdNNemail emailObj : entryObj.gdNNemail){

                    String emailAddress = emailObj.address.replace(‘googleId’,’id’);

                    emailList.add(emailAddress);   

                }

                googleContactInfoObj.email = emailList;

                List<String> phoneList = new List<String>();

                if(entryObj.GdNNphoneNumber != null){

                    for(getContactList.GdNNphoneNumber phoneObj : entryObj.GdNNphoneNumber){

                        String phoneNumber = phoneObj.uri;

                        phoneList.add(phoneNumber);   

                    }

                }

                googleContactInfoObj.phone = phoneList;

                String contactId = entryObj.googleId.NNt.replace(‘http://www.google.com/m8/feeds/contacts/ajay.prasad%40cloudanalogy.com/base/’, ”);

//replace the above email with your email.

                Http http1 = new Http();    

                HttpRequest req1 = new HttpRequest();

                req1.setEndpoint(‘https://www.google.com/m8/feeds/photos/media/ajay.prasad%40cloudanalogy.com/’+contactId);

                req1.setHeader(‘Authorization’, ‘OAuth ‘+authtoken);

                req1.setMethod(‘GET’);

                req1.setTimeout(60 * 1000);

                HttpResponse response1 = http1.send(req1);

                if (response1.getStatusCode() == 200) {

                    System.debug(‘The status is ok: ‘ +

                                 response1.getStatusCode() + ‘ ‘ + response1.getStatus());   

                } else {

                    System.debug(‘response1.getBody():::’+response1.getBody());

                }    

                String image = EncodingUtil.base64Encode(response1.getBodyAsBlob());

                googleContactInfoObj.photourl = image;

                googleContactInfotList.add(googleContactInfoObj);

            }

        }catch(Exception e){

            System.debug(‘Exception in message’+e.getMessage()+’Exception in line number’+e.getLineNumber());

        }

        return null;  

    }

    public class getAccessToken {

        public String access_token {get; set;}

        public String token_type {get; set;}

        public String expires_in {get; set;}

        public String scope {get; set;}

        public String jti {get; set;}

    }

    public class googleContactInfo {

        public string name{get; set;}

        public List<String> email{get; set;}

        public List<string> phone{get; set;}

        public String photourl{get; set;}

    }

}

2. getContactList

public class getContactList{

public String encoding{get;set;}

public feed feed{get;set;}

public String version{get;set;}

public class updated{

public String NNt{get;set;}

}

public class title{

public String type{get;set;}

public String NNt{get;set;}

}

public class openSearchNNtotalResults{

public String NNt{get;set;}

}

public class openSearchNNstartIndex{

public String NNt{get;set;}

}

public class openSearchNNitemsPerPage{

public String NNt{get;set;}

}

public class name{

public String NNt{get;set;}

}

public class link{

public String href{get;set;}

public String rel{get;set;}

public String type{get;set;}

}

public class googleId{

public String NNt{get;set;}

}

public class generator{

public String version{get;set;}

public String uri{get;set;}

public String NNt{get;set;}

}

public class gdNNemail{

public String primary{get;set;}

public String rel{get;set;}

public String address{get;set;}

}

    public class GdNNphoneNumber {

public String rel {get;set;} 

public String uri {get;set;} 

public String NNt {get;set;} 

    }

public class feed{

public generator generator{get;set;}

public list<author> author{get;set;}

public openSearchNNtotalResults openSearchNNtotalResults{get;set;}

public list<link> link{get;set;}

public openSearchNNstartIndex openSearchNNstartIndex{get;set;}

public title title{get;set;}

public openSearchNNitemsPerPage openSearchNNitemsPerPage{get;set;}

public list<category> category{get;set;}

public String xmlnsNNgContact{get;set;}

public String xmlnsNNgd{get;set;}

public googleId googleId{get;set;}

public String xmlnsNNbatch{get;set;}

public updated updated{get;set;}

public String xmlnsNNopenSearch{get;set;}

public list<entry> entry{get;set;}

public String xmlns{get;set;}

}

public class entry{

public googleId googleId{get;set;}

public title title{get;set;}

public list<link> link{get;set;}

public list<category> category{get;set;}

public list<gdNNemail> gdNNemail{get;set;}

public updated updated{get;set;}

        public List<GdNNphoneNumber> gdNNphoneNumber {get;set;} 

}

public class email{

public String NNt{get;set;}

}

public class category{

public String scheme{get;set;}

public String term{get;set;}

}

public class author{

public name name{get;set;}

public email email{get;set;}

}

}

VisualForce Page:

1. googleAuthContactPage

<apex:page controller=”googleAuthContactClass”>

    <style>

        .buttonClass {

        color: black !important;

        background: #F08080 !important;

        width: 300px;

        font-size: 20px !important;

        height: 35px;

        }

    </style>

    <apex:form style=”text-align: center;width:100%;”>

        <apex:pageblock >

            <apex:commandButton styleClass=”buttonClass” style=”margin:2%” value=”Google Contacts Authentication” action=”{!connect}”/>

            <apex:commandButton styleClass=”buttonClass” style=”margin:2%” value=”Get Contacts” action=”{!getContacts}”/>

            <apex:outputPanel rendered=”{! IF(ISBLANK(googleContactInfotList), false, true) }”>

                <table border=”2px” style=”margin:5%;border-collapse :collapse” width=90% bgcolor=”#F08080″>

                    <tr> 

                        <th style=”text-align:center” height=”30″>ProfilePicture</th>

                        <th style=”text-align:center”>Name</th>

                        <th style=”text-align:center”>Email Id</th>

                        <th style=”text-align:center”>PhoneNumber</th>

                    </tr>

                    <apex:repeat value=”{! googleContactInfotList }” var=”ct” >

                        <tr>

                            <td align=”center”>

                                <apex:repeat value=”{! ct.photourl }” var=”gci” >

                                    <img src=”data:image/*;base64,{!gci}”/>

                                </apex:repeat>  

                            </td>  

                            <td align=”center”> 

                                <apex:repeat value=”{! ct.name}” var=”ct11″>

                                    {!ct11}

                                </apex:repeat>

                            </td> 

                            <td align=”center”> 

                                <apex:repeat value=”{! ct.email}” var=”ct12″>

                                    {!ct12}

                                </apex:repeat>

                            </td>

                            <td align=”center”>

                                <apex:repeat value=”{! ct.phone}”  var=”ct13″>

                                    {!ct13}

                                </apex:repeat>    

                            </td>  

                        </tr> 

                    </apex:repeat>

                </table>

            </apex:outputPanel>

        </apex:pageblock>

    </apex:form>

</apex:page>

Open “googleAuthContactPage” VF page, preview it; the page will look like below.

Click on the button “Google Contacts Authentication” you will be redirected to Gmail login, login with your Gmail, grant access to the application. You will be back on the same page. Now Click on Get Contacts to retrieve contacts.

Here is a list of contacts related to Gmail ID:

Note:- Using the above code of the Apex controller and VisualForce page, you can get a contact list related to the email ID. To know more, you can go through the Google Contacts API doc and make any changes to the above code according to your requirement.

By integrating Salesforce with other applications, you can seamlessly manage all their customers, partners, and prospects in real-time. You can get easy access to essential data from multiple channels and gain a 360-degree view of your customer information.

Integrations with Salesforce CRM ensure that all of your data is synchronized and provides you with a unified, real-time view of your customers and business processes.

If you need any guidance with Salesforce and Google Cloud Integration or any form of Salesforce Integration, contact Cloud Analogy, one of the world’s leading Salesforce development companies and Salesforce Implementation Partners.

Our certified Salesforce experts would be happy to assist you in transforming your business in countless ways. Whether you’re planning to integrate a new or existing app with Salesforce, you can always count on us.

nitish

Nitish Bhardwaj

Salesforce Principal Consultant | Chief Information Officer
An experienced Salesforce.com professional with 5+ years of experience in consulting on and delivering Salesforce projects for mid size, large and very large customers.

Hire the best Salesforce Implementation Partner. Choose certified Salesforce Implementation Experts from Cloud Analogy now.

Close Menu