Salesforce and Google Drive: Seamless Integration Guide
In today’s interconnected world, the seamless integration of different platforms is crucial for businesses looking to optimize their workflows and increase productivity. Salesforce, as a leading CRM platform, offers a wide range of integration possibilities, and one of the most popular integrations is with Google Drive. This integration allows users to easily store and manage documents related to their Salesforce records directly in Google Drive.
In this blog post, we’ll walk through the process of setting up and implementing Salesforce Google Drive integration, focusing on a specific use case: uploading files under Salesforce Accounts or Contacts and organizing them into folders based on Account and Contact names.
Important Links –
Create an App in the Google Cloud Console – https://console.cloud.google.com/
OAuth Playground Link – https://developers.google.com/oauthplayground/
Step 1: Setting up Google Cloud Console
- Create a Project: Navigate to the Google Cloud Console and create a new project dedicated to your integration.
- Enable Google Drive API: Within your project, enable the Google Drive API to allow access to Google Drive services.
- Generate Credentials: Generate a Client ID and Secret Key for your application. These credentials will be used to authenticate your application with Google services.
Step 2: Obtain a Refresh Token
To access Google Drive on behalf of users, your application needs to be authorized using OAuth 2.0. Follow these steps to obtain a refresh token:
- Use OAuth Playground: Utilize Google’s OAuth Playground to generate a refresh token. This token will enable your application to access Google Drive APIs on behalf of users without requiring them to authenticate every time.
- Enable Use your own OAuth credentials – Then Put your Client Id and Client Secret copied from the App.
- Then Select & Authorize API – Select Drive API v3.
- Then hit – Exchange authorization code for tokens button
Step 3: Code to Handle Google Drive Integration
Now that you have the necessary credentials and authorization, it’s time to write the code to integrate Salesforce with Google Drive.
trigger ContentVersionTrigger on ContentVersion (after insert) {
for(ContentVersion cv: trigger.new){
ContentVersionTriggerHandler.callGoogleDrive(cv.Id);
}
}
public class ContentVersionTriggerHandler {
@future(callout=true)
public static void callGoogleDrive(String cvId) {
String key = '391363682460-ddje8obj1apaf6fc222qjhft14tiatno.apps.googleusercontent.com';
String secret = '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';
String redirect_uri = 'https://developers.google.com/oauthplayground';
String accessToken;
String refreshToken = '1//04E55ZJIIkHG9CgYIARAAGAQSNwF-L9Ir1dlAKlaBL8RaCgf3DKPIKNSY_60c9Brp1OBpDEOdG2NJd7vohl0W-1nXGhtiFof_lsY';
// Fetch access token from refresh token
accessToken = getGoogleDriveAccessToken(refreshToken, key, secret, redirect_uri);
// Fetch ContentVersion record
ContentVersion cv = [SELECT Id, FirstPublishLocation.Name, Title, ContentDocumentId, VersionData FROM ContentVersion WHERE Id = :cvId];
System.debug('FirstPublishLocationId ' + cv.FirstPublishLocationId);
System.debug('Name ' + cv.FirstPublishLocation.Name);
String folderId = createGoogleDriveFolder(cv.FirstPublishLocation.Name, accessToken); // Create 'New Docs' folder
ContentDocument document = [SELECT Title FROM ContentDocument WHERE Id IN (SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cvId)];
String fileName = document.Title;
System.debug('file Name '+ fileName);
// Prepare the metadata for the file, including the name and parent folder ID
String metadata = JSON.serialize(new Map<String, Object>{
'name' => fileName,
'parents' => new List<String>{folderId}
});
String boundary = '-------314159265358979323846';
String delimiter = '\r\n--' + boundary + '\r\n';
String close_delim = '\r\n--' + boundary + '--';
// Adjust contentType based on file type
String contentType = '';
if (fileName.toLowerCase().endsWith('.pdf')) {
contentType = 'application/pdf';
} else if (fileName.toLowerCase().endsWith('.jpg')) {
contentType = 'image/jpeg';
} else if (fileName.toLowerCase().endsWith('.png')) {
contentType = 'image/png';
} else {
// Default to application/octet-stream for unknown file types
contentType = 'application/octet-stream';
}
String requestBody = delimiter +
'Content-Type: application/json\r\n\r\n' +
metadata + '\r\n' +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n\r\n' +
EncodingUtil.base64Encode(cv.VersionData) +
close_delim;
// Prepare the HttpRequest
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + accessToken);
req.setHeader('Content-Type', 'multipart/related; boundary="' + boundary + '"');
req.setMethod('POST');
req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
req.setHeader('Content-Length', String.valueOf(requestBody.length()));
req.setBody(requestBody);
// Send the request
Http http = new Http();
HttpResponse response = http.send(req);
System.debug(response.getBody());
}
// Method to create folder in Google Drive
public static String createGoogleDriveFolder(String folderName, String accessToken) {
String folderId = null;
try {
String url = 'https://www.googleapis.com/drive/v3/files';
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setHeader('Authorization', 'Bearer ' + accessToken);
req.setHeader('Content-Type', 'application/json');
req.setMethod('POST');
Map<String, Object> requestBody = new Map<String, Object>();
requestBody.put('name', folderName);
requestBody.put('mimeType', 'application/vnd.google-apps.folder');
req.setBody(JSON.serialize(requestBody));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> jsonResponse = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
folderId = (String)jsonResponse.get('id');
}
} catch (Exception e) {
// Handle exception
}
return folderId;
}
// Method to fetch access token from refresh token
public static String getGoogleDriveAccessToken(String refreshToken, String key, String secret, String redirect_uri) {
String accessToken = '';
try {
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=' + secret + '&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);
HttpResponse res2 = new Http().send(req2);
String 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();
}
}
}
} catch (Exception e) {
// Handle exception
}
return accessToken;
}
}
Step 4: Uploading Files to Google Drive from Salesforce
With the integration code in place, you can now easily upload files from Salesforce to Google Drive. Here’s how the process works:
- Select Account or Contact: Choose the Salesforce Account or Contact record under which you want to upload the file.
- Create Folder: Automatically create a folder in Google Drive named after the selected Account or Contact.
- Upload File: The file gets uploaded to the respective folder of the account name in Google Drive.
Step 5: Organizing Files in Google Drive
By organizing files into folders based on Salesforce Account and Contact names, you can maintain a structured hierarchy in Google Drive that mirrors your Salesforce records. This makes it easy to find and manage files associated with specific accounts or contacts.
Integrating Salesforce with Google Drive opens up a world of possibilities for streamlining document management and collaboration. By following the steps outlined in this guide, you can seamlessly upload files from Salesforce to Google Drive and organize them in a way that aligns with your business processes.
Also Checkout – Salesforce Roadmap for Beginners
Discover more from FOSS HUT - All Open Source
Subscribe to get the latest posts sent to your email.