Salesforce to Google Drive Integration

Google drive 

Google Drive is a cloud storage platform developed by Google to store all your files be it doc, video, images, reports, leads, accounts or any form of content. It enables you to access these files from any device and also a great medium to collaborate on any files. Files storage, sharing, and collaboration can benefit your business with increased productivity. 

Google drive integration with Salesforce 

This blog is based on folder Creation in Google drive. Let suppose if an organization is dependent on applications like Salesforce.com and Google Drive and wants to use the functionality of both the application. This can be achieved easily by Salesforce to Google drive Integration

It makes the sharing of data between these two applications much easier and optimizes the business complex processes. When you integrate Google drive with Salesforce, you can be assured of data security and backup. 

Benefits of Google Drive integration with Salesforce 

  • Real-time synchronization, as you made any changes in the doc it will get reflected on both Google drive doc as well as Salesforce without any delay. 
  • Two-way synchronization, changes can be made from both platforms, changes will get updated immediately and can be seen from both the platforms. 
  • High data security, it provides multi-level security to your data and keeps it confidential. There is a specially designed feature to protect your files and backed up.
  • For adding a file to Salesforce you don’t need to access Salesforce, you can add files to Google Drive and it will get reflected your Salesforce account. You can access it from Salesforce as well as Google drive. 

Step by step guide to Integrate Google Drive with Salesforce.

  •     Search URL https://console.developers.google.com/project on Google.
  •     Create a “New Project”.

You Can Create “New Project” in Google in two different ways –

 

  1. First way-
  •     Click on Select a project.
  •     Click on NEW PROJECT.
  •     Give the Project name.
  •     Click on Create.
  1. Second way-
  •     Click on Create.
  •     Give the Project name.
  •     Click on Create.

  •     From the top of the page, select the project you Create.
  •     Click on ENABLE APIS AND SERVICES / Library.

  •      Search box for APIs & Services, Search Drive / Google Drive.

  •     Click ENABLE Button APIs.

  •     From the left menu on the ‘Google Drive API’ page, click on ‘CREATE CREDENTIALS’.

  •     After click Create Credentials a page will open, then click on the ‘Cancel button’ on that page.

  •     Click on the ‘Create Credentials’ Button. Select OAuth client ID.

   

  • Click On Configure consent screen.

 

Custom setting Name – GoogleDrive

 

Six Fields With field label.

  1.     Access token (text type)
  2.     Client Id (text type)
  3.     Client secret (text type)
  4.     Refresh Token (text type)
  5.     GoogleAccountDomain (text type)
  6.     Redirect Url (URL type)

  • Open Developer console.
  • Create Visual Force Page and Apex Class for getting Access token and Refresh Token, and store in Custom setting use for Authentication for Google drive.

 

Vf page 

 

<apex:page action=”{!init}” controller=”GoogleDriveController” showHeader=”false” standardStylesheets=”false” lightningStyleSheets=”true”>  

   <style type=”text/css”>  

     .exactCenter {  

     width: 60%;  

     height: 300px;  

     position: absolute;  

     background-color: #F0F0F0;  

     left: 50%;  

     top: 50%;  

     transform: translate(-50%, -50%);  

     }  

   </style>  

   <apex:slds />  

   <div class=”slds-scope”>   

     <apex:form >  

         <b><center><font size=”4″ color=”blue”>Click on button to Save token!</font></center></b><br/>  

         <b><center><apex:commandButton value=”Save token” action=”{!SaveToken}” styleclass=”slds-button slds-button_brand” /></center></b>  

     </apex:form>  

   </div>  

 </apex:page> 

 

Apex Class

 

public class GoogleDriveController  

 {  

   //Fetched from URL  

   public String accessToken;  

   public String refreshToken;  

   private String code ;  

   private string key ;  

   private string secret ;  

   private string redirect_uri ;  

   GoogleDrive__c googleCusSetting = new GoogleDrive__c();  

   public void SaveToken()  

   {  

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

     //Get the access token once we have code  

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

     { system.debug(‘Get the access token once we have code’);  

      getToken() ;  

     }  

   }  

   public PageReference init()  

   { //Authenticating  

     googleCusSetting = [Select id,Client_Id__c,Client_secret__c,Refresh_Token__c,Access_token__c,GoogleAccountDomain__c,Redirect_Url__c from GoogleDrive__c limit 1];  

     key = googleCusSetting.Client_Id__c;  

     secret = googleCusSetting.Client_secret__c;  

     redirect_uri = googleCusSetting.Redirect_Url__c;  

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

     //Get the access token once we have code  

     PageReference pg;  

     if(code == ” || code == null){  

       pg = new PageReference(GoogleDriveAuthUri (key , redirect_uri)) ;  

     }  

     return pg ;  

   }  

   public String GoogleDriveAuthUri(String Clientkey,String redirect_uri)  

   {  

     String key = EncodingUtil.urlEncode(Clientkey,’UTF-8′);  

     String uri = EncodingUtil.urlEncode(redirect_uri,’UTF-8′);  

     String authuri = ”;  

     authuri = ‘https://accounts.google.com/o/oauth2/auth?’+  

       ‘client_id=’+key+  

       ‘&response_type=code’+  

       ‘&scope=https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.file’+  

       ‘&redirect_uri=’+uri+  

       ‘&state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&’+  

       ‘&login_hint=jsmith@example.com&’+  

       ‘access_type=offline’;  

     return authuri;  

   }  

   public void getToken()  

   {  

     //Getting access token from google  

     HttpRequest req = new HttpRequest();  

     req.setMethod(‘POST’);  

     req.setEndpoint(‘https://accounts.google.com/o/oauth2/token’);  

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

     String messageBody = ‘code=’+code+’&client_id=’+key+’&client_secret=’+secret+’&redirect_uri=’+redirect_uri+’&grant_type=authorization_code’;  

     req.setHeader(‘Content-length’, String.valueOf(messageBody.length()));  

     req.setBody(messageBody);  

     req.setTimeout(60*1000);  

     Http h = new Http();  

     String resp;  

     HttpResponse res = h.send(req);  

     resp = res.getBody();  

     if(res.getBody() != null && res.getStatusCode()==200){  

       //You can parse the response to get the Access token and Refresh token  

       Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());  

       //Access Token   

       if(results.get(‘access_token’) != null){  

         accessToken=string.valueOf(results.get(‘access_token’));   

         googleCusSetting.Access_token__c = accessToken;  

       }  

       //Refresh Token  

       if(results.get(‘refresh_token’) != null){  

         refreshToken=string.valueOf(results.get(‘refresh_token’));  

         googleCusSetting.Refresh_Token__c = refreshToken;   

       }  

       update googleCusSetting;  

     }  

   }  

 }  

 

  • After Creating vf Page and Apex Class.

 

  •     Click on the CONFIGURE CONSENT SCREEN / OAuth consent screen tab. Enter the Application name, valid Email id in the Support email field and In Authorised domains add Salesforce Domain and Vf page domain, then click Save.

 

  •     Click ‘Create Credentials’, then select OAuth client ID from the ‘Create Credentials’ picklist.
  •     On the ‘Create OAuth Client ID’ page, In Application type, select Web Application and add URL of Visualforce Page in Authorised redirect URIs then Click on Create.
  •     Note the Client ID and Client Secret from the popup window. You will use these values when you create an Authentication Provider in Salesforce.

  • Click on web Application Name.

  • Copy the ‘’Client Id” and “Client Secret” and Visualforce Redirect URL save in Google Drive Custom Setting of Salesforce.

  • Preview the VisualForce page, it will redirect to choose Google Account login page Choose the account which you Want to integrate. Allow all the permission.
  • Then Click the “Save token” button on the vf page, it will update the custom setting with Refresh and Access token.

How to get Access Token Using Refresh Token?

Http h = new Http();  

  HttpRequest req = new HttpRequest();  

  req.setEndpoint(‘https://accounts.google.com/o/oauth2/token’);  

  String bodyRequest = ‘client_id=’+ClientId+’&client_secret=’+ Clientsecret+’&refresh_token=’+RefreshToken+’&grant_type=refresh_token’;  

  req.setBody(bodyRequest);       

  req.setHeader(‘Content-length’, string.ValueOf(bodyRequest.length()));   

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

  req.setMethod(‘POST’);  

  req.setTimeout(10000);  

  HttpResponse res = h.send(req);    

 System.debug(‘Response Value:’+res.getBody());  

 if(res.getBody() != null && res.getStatusCode()==200){  

  Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());  

  System.debug(‘ ===You can parse the response to get the access token ===’ + results);   

  accessToken=string.valueOf(results.get(‘access_token’));  

  system.debug(‘====accessToken===’+accessToken);  

 } 

How to Create a Folder in the Google Drive?

 HttpRequest req = new HttpRequest();   

  req.setMethod(‘POST’);  

  req.setEndpoint(‘https://www.googleapis.com/drive/v3/files’);   

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

  req.setHeader(‘content-type’, ‘application/json’);  

  String body = ‘{“name” : “‘+FolderName+'”,”mimeType” : “application/vnd.google-apps.folder”}’;  

  req.setTimeout(60*1000);   

  req.setBody(body);  

  Http http = new Http();  

  HttpResponse res = http.send(req);    

  System.debug(‘===== Response===’+ res.getBody());  

 

How to Create Child Folder in Parent Folder of Google Drive?

 

HttpRequest req = new HttpRequest();   

  req.setMethod(‘POST’);   

  req.setEndpoint(‘https://www.googleapis.com/drive/v2/files’);   

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

  req.setHeader(‘content-type’, ‘application/json’);  

 String body = ‘{“title”:”‘+ChildfolderName+'”,”mimeType”:”application/vnd.google-apps.folder”,”parents”: [{“kind”: “drive#fileLink”,”id”: “‘+ParentFolderId+'”}]}’;  

  req.setTimeout(60*1000);   

  req.setBody(body);  

  Http http = new Http();  

  HttpResponse res = http.send(req);    

  System.debug(‘=====the resp===’+ res.getBody());  

 

Upload a Different type of File (.docx, pdf, jpg /png/jpeg) form the Component in Record Page of Salesforce Object to Google DriveFolder.

 

  • In this, I am using the Opportunity object and Aura Component is added to the Opportunity record page.
  • A custom field Client_Collateral_Folder_Id__c type text is created in Opportunity object. Store the folder Id of Google Drive Folder in which File is to upload.
  • Google Drive Custom Setting is also Used for Auth Which created previously.

 

FileUpload.cmp  

 

 <aura:component implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction” access=”global” controller=”FileUploadController” >  

   <aura:attribute name=”accept” type=”List” default=”[‘.jpg’, ‘.jpeg’,’.pdf’,’.docx’]”/>  

   <aura:attribute name=”multiple” type=”Boolean” default=”true”/>  

   <aura:attribute name=”disabled” type=”Boolean” default=”false”/>  

   <div id=”div1″>  

   <lightning:fileUpload name=”fileUploader”  

               label= “Client Collateral folder”  

               multiple=”{!v.multiple}”  

               accept=”{!v.accept}”  

               disabled=”{!v.disabled}”  

               recordId=”{!v.recordId}”  

               onuploadfinished=”{! c.handleUploadFinished }”/><br/>  

   </div>  

 </aura:component> 

 

FileUploadController.js  

 ({  

   handleUploadFinished : function (cmp, event){  

     var uploadedFiles = event.getParam(“files”);  

     var action = cmp.get(“c.getClient”);  

     action.setParams({ oppId : cmp.get(“v.recordId”) });  

     action.setCallback(this, function(response) {  

       var state = response.getState();  

       if (state === “SUCCESS”) {  

       }  

     });  

     $A.enqueueAction(action);  

     alert(“Files uploaded Client : ” + uploadedFiles.length);  

   }  

 })  

 </aura:component>

 

FileUpload.css  

 

 .THIS#div1{  

   background-color: white;  

   border-radius:5px;  

   max-height:200px;  

 }  

 .THIS .slds-form-element__label{  

   margin-left:23px;  

 }  

 .THIS .slds-file-selector__dropzone{  

   margin-left:23px;  

 } 

 

Apex Class

 

public class FileUploadController {  

   @AuraEnabled  

   public static void getClient(string oppid){  

     //set<Id> idset = new set<Id>();  

     String idTest;  

     Opportunity opp =[Select id,Name,OPP_0000__c,Client_Collateral_Folder_Id__c from Opportunity where id =: oppid limit 1];  

     List<ContentDocumentLink> conlink = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =: oppid];  

     for(ContentDocumentLink conids : conlink){  

       //idset.add(conids.ContentDocumentId);  

       idTest = conids.ContentDocumentId;  

     }  

     ContentDocument contDoc = [Select Id ,Title from ContentDocument Where Id =: idTest];  

     ContentVersion conver = [SELECT VersionData,FileType FROM ContentVersion WHERE ContentDocumentId = :contDoc.Id];  

     system.debug(‘===============conver===============’+conver.VersionData);  

     GoogleDrive__c googleCusSetting = new GoogleDrive__c();  

     googleCusSetting = [Select id,Client_Id__c,Client_secret__c,Refresh_Token__c from GoogleDrive__c limit 1];  

     system.debug(‘===Client_Id__c===’+googleCusSetting.Client_Id__c);  

 

//this code is For Access Token from Refresh token

 

     String accessToken;  

     Http h = new Http();  

     HttpRequest req = new HttpRequest();  

     string endPointValue = ‘https://accounts.google.com/o/oauth2/token’;    

     req.setEndpoint(endPointValue);  

     string bodyRequest = ‘client_id=’+googleCusSetting.Client_Id__c+’&client_secret=’+googleCusSetting.Client_secret__c+’&refresh_token=’+googleCusSetting.Refresh_Token__c+’&grant_type=refresh_token’;  

     system.debug(‘===bodyRequest===’+bodyRequest);  

     req.setBody(bodyRequest);       

     req.setHeader(‘Content-length’, string.ValueOf(bodyRequest.length()));   

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

     req.setMethod(‘POST’);  

     req.setTimeout(10000);  

     HttpResponse res = h.send(req);    

     System.debug(‘Response Value:’+res.getBody());  

     if(res.getBody() != null && res.getStatusCode()==200){  

       Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());  

       System.debug(‘ ====You can parse the response to get the access token ==== ‘ + results);  

       accessToken=string.valueOf(results.get(‘access_token’));  

       system.debug(‘====accessToken===’+accessToken);  

     }  

     //this code is for pdf upload  

 

     if(conver.FileType == ‘PDF’){  

       String boundary = ‘———-9889464542212’;  

       String delimiter = ‘\r\n–‘ + boundary + ‘\r\n’;  

       String close_delim = ‘\r\n–‘ + boundary + ‘–‘;  

       system.debug(‘===================conver.VersionData=======================’+conver.VersionData);  

       String bodyEncoded = EncodingUtil.base64Encode( conver.VersionData);  

       String body = delimiter + ‘Content-Type: application/json\r\n\r\n’ + ‘{ “title” : “‘ + contDoc.Title + ‘”,’ + ‘ “mimeType” : “application/’ + conver.FileType + ‘”,”parents” :[{“id”:”‘+opp.Client_Collateral_Folder_Id__c+'”}]}’ + delimiter + ‘Content-Type: application/’ + conver.FileType + ‘\r\n’ + ‘Content-Transfer-Encoding: base64\r\n’ + ‘\r\n’ + bodyEncoded + close_delim;  

       system.debug(‘==================body======================’+body);  

       Http http = new Http();  

       HttpRequest req1 = new HttpRequest();  

       req1.setEndpoint(‘https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart’);  

       req1.setHeader(‘Authorization’, ‘Bearer ‘ + accessToken);  

       req1.setHeader(‘Content-Type’, ‘multipart/mixed; boundary=”‘ + boundary + ‘”‘);  

       req1.setHeader(‘Content-length’, String.valueOf(body.length()));  

       req1.setBody(body);  

       req1.setMethod(‘POST’);  

       req1.setTimeout(60 * 1000);  

       HttpResponse resp = http.send(req1);  

       system.debug(‘==============response================’+resp);  

     }  

     //this code is to upload image  

 

     if(conver.FileType == ‘JPG’ || conver.FileType == ‘JPEG’ || conver.FileType == ‘PNG’){  

       String boundary2 = ‘———-9889464542212’;  

       String delimiter2 = ‘\r\n–‘ + boundary2 + ‘\r\n’;  

       String close_delim2 = ‘\r\n–‘ + boundary2 + ‘–‘;  

       system.debug(‘===================conver.VersionData=======================’+conver.VersionData);  

       String bodyEncoded2 = EncodingUtil.base64Encode( conver.VersionData);  

       String body2 = delimiter2 + ‘Content-Type: application/json\r\n\r\n’ + ‘{ “title” : “‘ + contDoc.Title + ‘”,’ + ‘ “mimeType” : “image/’ + conver.FileType + ‘”,”parents” :[{“id”:”‘+opp.Client_Collateral_Folder_Id__c+'”}]}’ + delimiter2 + ‘Content-Type: imager/’ + conver.FileType + ‘\r\n’ + ‘Content-Transfer-Encoding: base64\r\n’ + ‘\r\n’ + bodyEncoded2 + close_delim2;  

       system.debug(‘==================body======================’+body2);  

       Http http2 = new Http();  

       HttpRequest req2 = new HttpRequest();  

       req2.setEndpoint(‘https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart’);  

       req2.setHeader(‘Authorization’, ‘Bearer ‘ + accessToken);  

       req2.setHeader(‘Content-Type’, ‘multipart/mixed; boundary=”‘ + boundary2 + ‘”‘);  

       req2.setHeader(‘Content-length’, String.valueOf(body2.length()));  

       req2.setBody(body2);  

       req2.setMethod(‘POST’);  

       req2.setTimeout(60 * 1000);  

       HttpResponse resp2 = http2.send(req2);  

       system.debug(‘==============response================’+resp2);  

     }  

     //this code is for .docx upload  

 

     if(conver.FileType == ‘WORD_X’){  

       String boundary3 = ‘———-9889464542212’;  

       String delimiter3 = ‘\r\n–‘ + boundary3 + ‘\r\n’;  

       String close_delim3 = ‘\r\n–‘ + boundary3 + ‘–‘;  

       system.debug(‘===================conver.VersionData=======================’+conver.VersionData);  

       String bodyEncoded3 = EncodingUtil.base64Encode( conver.VersionData);  

       String body3 = delimiter3 + ‘Content-Type: application/json\r\n\r\n’ + ‘{ “title” : “‘ + contDoc.Title + ‘”,’ + ‘ “mimeType” : “application/vnd.openxmlformats-officedocument.wordprocessingml.document”,”parents” :[{“id”:”‘+opp.Client_Collateral_Folder_Id__c+'”}]}’ + delimiter3 + ‘Content-Type: application/’ + conver.FileType + ‘\r\n’ + ‘Content-Transfer-Encoding: base64\r\n’ + ‘\r\n’ + bodyEncoded3 + close_delim3;  

       system.debug(‘==================body======================’+body3);  

       Http http3 = new Http();  

       HttpRequest req3 = new HttpRequest();  

       req3.setEndpoint(‘https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart’);  

       req3.setHeader(‘Authorization’, ‘Bearer ‘ + accessToken);  

       req3.setHeader(‘Content-Type’, ‘multipart/mixed; boundary=”‘ + boundary3 + ‘”‘);  

       req3.setHeader(‘Content-length’, String.valueOf(body3.length()));  

       req3.setBody(body3);  

       req3.setMethod(‘POST’);  

       req3.setTimeout(60 * 1000);  

       HttpResponse resp3 = http3.send(req3);  

       system.debug(‘==============response================’+resp3);  

     }  

   }  

 }

 

Let me conclude here

Every business needs its data to secure at a reliable place where there is no risk of data loss. Google Drive is a cloud-based platform that stores, shares and manages files. Google drive is a trustable data storage platform that also allows you easy collaboration and makes the workflow smooth. 

Comments: 5

Leave a reply to Duke Cancel reply