Integrating Salesforce with Google Drive: A Complete Guide

Integrating Salesforce with Google Drive: A Complete Guide 

Introduction 

Salesforce to Google Drive integration is essential for many businesses. It enhances team collaboration by enabling real-time synchronization of Google Sheets, Docs, Slides, and Forms with Salesforce records like opportunities, accounts, or customer contacts. 

If you’re looking to integrate Salesforce with Google Drive, follow these steps to achieve a seamless integration experience. 

    

Step 1: Create an Authentication Provider for Google Drive 

To use Google Drive as an external data source, you need to create an authentication provider in Salesforce. This process begins with creating a related project in the Google Developers Console. 

Creating a Project in Google Developers Console 

  1. Log in to Google Cloud Console. 
  1. Click on Select Project and then Create Project. 
  1. Enter a project name and location, then click Create. 
  1. Navigate to the APIs & Services section from the menu. 
  1. In the API manager, go to the Library tab and search for “Google Drive API”. 
  1. Select Google Drive API and click Enable API. 
  1. In the left menu, go to Credentials. 
  1. Under the OAuth Consent Screen tab, enter a valid email address and application name, then click Save. 
  1. In the Credentials tab, click Add Credentials and choose OAuth client ID. 
  1. Select Web Application and click Create. 
  1. Copy the Client ID and Client Secret values for later use. 

 

Step 2: Create an Authentication Provider in Salesforce 

  1. In Salesforce Setup, search for Auth. Providers and click New. 
  1. For Provider Type, select OpenID Connect. 
  1. Configure the following settings: 
  • Name: Enter a name (e.g., GoogleAuth). 
  • URL Suffix: Define a suffix (e.g., MyGoogleProvider). 
  • Consumer Key: Paste the Client ID copied from Google. 
  • Consumer Secret: Paste the Client Secret copied from Google. 
  • Authorize Endpoint URL: https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force 
  • Token Endpoint URL: https://accounts.google.com/o/oauth2/token 
  • Default Scopes: openid email profile https://www.googleapis.com/auth/drive 
  1. Click Save, then copy the Callback URL from the Auth. Provider detail page. 
  1. Go back to the Google Developer Console, edit the OAuth Credentials, and add the copied Callback URL under Authorized Redirect URIs. 

 

Step 3: Create a Named Credential in Salesforce 

  1. In Salesforce Setup, search for Named Credentials and click New. 
  1. Configure the following settings: 
  • Label: GoogleDrive 
  • URL: https://www.googleapis.com/drive/v2 
  • Identity Type: Named Principal 
  • Authentication Protocol: OAuth 2.0 
  • Authentication Provider: Select the Auth. Provider created in Step 2. 
  1. Check Start Authentication Flow on Save and click Save. 
  1. After saving, log in to your Google account when prompted. 
  1. Grant permission for Google Drive access. 
  1. Once authenticated, the Named Credential detail page will display Authentication Status: Authenticated. 

 

Step 4: Implement Apex Code for File Upload to Google Drive 

To upload files from Salesforce to Google Drive, implement the following Apex Trigger and Class: 

Trigger: ContentVersionTrigger 

trigger ContentVersionTrigger on ContentVersion (after insert) { 

    for (ContentVersion cv: trigger.new){ 

        ContentVersionTriggerHandler.callGoogleDrive(cv.Id); 

    } 

} 

 

Apex Class: ContentVersionTriggerHandler 

 

public class ContentVersionTriggerHandler { 

    @future(callout=true) 

    public static void callGoogleDrive(String cvId){ 

        String key = ‘Use Your Key’; 

        String secert = ‘GOCSPX-E6KFKF90DyRghFLbsI0-7P’; 

        String redirect_uri = ‘https://developers.google.com/oauthplayground’; 

         

        String accesstoken; 

        String refreshToken = ‘1//04OxOrPu78cF6CgYIARAAGAQSNgF-L9IrFJ45CBuduExRL3vjlBKQZOH_N58zki85uHTeiQ’; 

        HttpRequest req2 = new HttpRequest(); 

        req2.setMethod(‘POST’); 

        req2.setEndpoint(‘https://www.googleapis.com/oauth2/v4/token’); 

         

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

        String messageBody = ‘client_id=’ + key + ‘&client_secret=’ + secert + ‘&refresh_token=’+refreshtoken+’&redirect_uri=’ + redirect_uri + ‘&grant_type=refresh_token’; 

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

        req2.setBody(messageBody); 

        req2.setTimeout(60 * 1000); 

        Http h2 = new Http(); 

        String resp2; 

        HttpResponse res2 = h2.send(req2); 

        resp2 = res2.getBody(); 

        System.debug(‘resp2–>>’+resp2); 

        JSONParser parser = JSON.createParser(resp2); 

        while (parser.nextToken() != null) { 

            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)) { 

                String fieldName = parser.getText(); 

                parser.nextToken(); 

                if (fieldName == ‘access_token’) { 

                    accesstoken = parser.getText(); 

                } else if (fieldName == ‘expires_in’) { 

                    Integer expiresIn = parser.getIntegerValue(); 

                } else if (fieldname == ‘token_type’) { 

                    String tokentype = parser.getText(); 

                } 

            } 

        } 

         

        ContentVersion cv=[select id,title,ContentDocumentId,versiondata from Contentversion where Id =: cvId ]; 

         

        Blob myBlob = cv.versiondata; 

        String url = ‘https://www.googleapis.com/upload/drive/v2/files?uploadType=media’; 

         

        string authorizationHeader = ‘Bearer ‘ + accesstoken;  

        Integer contentSize = myBlob.size(); 

        HttpRequest req1 = new HttpRequest(); 

        req1.setheader(‘Authorization’,authorizationHeader); 

        req1.setheader(‘Content-Length’,String.valueOf(contentSize)); 

        req1.setheader(‘Content-Type’,’image/’+’PNG’); 

        req1.setheader(‘Content-Type’,’application/’+’pdf’); 

        req1.setMethod(‘POST’);  

        req1.setEndpoint(url);  

        req1.setBodyAsBlob(myBlob);  

        Http h1 = new Http();  

         

        Httpresponse resp1 = h1.send(req1); 

    } 

} 

Leave a Comment

Your email address will not be published. Required fields are marked *