Integrating Salesforce with Google Drive for File Uploads

   Integrating Salesforce with Google Drive for File Uploads

In this blog, we will walk through the steps required to integrate Salesforce with Google Drive for uploading files. We'll cover the necessary setup on Google Cloud, obtaining the required credentials, and the Salesforce Apex code to facilitate the integration.




Step 1: Create a Project in Google Cloud

Go to the Google Cloud Console.

Create a new project by clicking on the project dropdown and selecting "New Project".

Name your project and click "Create".

Step 2: Enable Google Drive API

In your new project, go to the "APIs & Services" dashboard.

Click "Enable APIs and Services".

Search for "Google Drive API" and click on it.

Click "Enable" to enable the API for your project.

Step 3: Create OAuth Credentials

In the "APIs & Services" dashboard, click on "Credentials".

Click "Create Credentials" and select "OAuth 2.0 Client ID".

Configure the consent screen by providing the required information.

Select "Web application" as the application type.

Enter the authorized redirect URIs, such as https://developers.google.com/oauthplayground.

Step 4: Complete OAuth Consent Screen Steps

Provide the necessary details on the OAuth consent screen, including the application name and support email.

Add the necessary scopes required for Google Drive API.

Step 5: Get Client ID and Secret

After creating the OAuth credentials, you will get a Client ID and Client Secret.

Note down these credentials as they will be used in your Salesforce Apex code.

Step 6: Get Refresh Token

Go to the OAuth 2.0 Playground.

Select the required Google Drive API scopes.

Authorize the APIs and exchange the authorization code for a refresh token.

Note down the refresh token.

Step 7: Get Access Token Using Refresh Token in Apex Code

Now, we will use the refresh token to get an access token via Apex code in Salesforce. Here is the Apex code to handle the OAuth token exchange and file upload.


Step 8: Upload File

apex


public class ContentVersionTriggerHandler {

    @future(callout=true)

    public static void callGoogleDrive(String cvId) {

        String key = 'YOUR_CLIENT_ID';

        String secret = 'YOUR_CLIENT_SECRET';

        String redirectUri = 'https://developers.google.com/oauthplayground';

        String refreshToken = 'YOUR_REFRESH_TOKEN';

        String accessToken;


        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=' + redirectUri + '&grant_type=refresh_token';

        req2.setBody(messageBody);


        Http http = new Http();

        HttpResponse res2 = http.send(req2);


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

            Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(res2.getBody());

            accessToken = (String) responseMap.get('access_token');

        } else {

            System.debug('Failed to get access token');

            return;

        }


        ContentVersion cv = [SELECT Id, Title, ContentDocumentId, VersionData FROM ContentVersion WHERE Id = :cvId];

        Blob myBlob = cv.VersionData;


        HttpRequest req1 = new HttpRequest();

        req1.setHeader('Authorization', 'Bearer ' + accessToken);

        req1.setHeader('Content-Length', String.valueOf(myBlob.size()));

        req1.setHeader('Content-Type', 'application/octet-stream');

        req1.setMethod('POST');

        req1.setEndpoint('https://www.googleapis.com/upload/drive/v2/files?uploadType=media');

        req1.setBodyAsBlob(myBlob);


        HttpResponse resp1 = new Http().send(req1);

        System.debug('Response: ' + resp1.getBody());

    }

}


trigger ContentVersionTrigger on ContentVersion (after insert) {

    for (ContentVersion cv : Trigger.new) {

        ContentVersionTriggerHandler.callGoogleDrive(cv.Id);

    }

}

Lightning Web Component for File Upload

To handle file uploads in Salesforce Lightning Experience, use the following Lightning Web Component (LWC):


HTML:


html


<template>

    <lightning-button label="Attach Receipt" onclick={handleButtonClick}></lightning-button>

    <template if:true={showFileUpload}>

        <lightning-file-upload

            label="Attach Receipt"

            name="fileUploader"

            accept={acceptedFormats}

            record-id={myRecordId}

            onuploadfinished={handleUploadFinished}

            multiple

        ></lightning-file-upload>

    </template>

</template>

JavaScript:


javascript

import { LightningElement, api, track } from 'lwc';


export default class FileUploadExample extends LightningElement {

    @api myRecordId;

    @track showFileUpload = false;


    get acceptedFormats() {

        return ['.pdf', '.png'];

    }


    handleButtonClick() {

        this.showFileUpload = true;

    }


    handleUploadFinished(event) {

        const uploadedFiles = event.detail.files;

        let message = 'No. of files uploaded: ' + uploadedFiles.length + '\n';

        uploadedFiles.forEach(file => {

            message += 'File Name: ' + file.name + ', Document Id: ' + file.documentId + '\n';

        });

        alert(message);

        this.showFileUpload = false;

    }

}

Conclusion

By following these steps, you can successfully integrate Salesforce with Google Drive to upload files. This integration uses the OAuth 2.0 protocol for secure authentication and authorization. Ensure you replace placeholders like YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, and YOUR_REFRESH_TOKEN with actual values from your Google Cloud project.


Happy coding!

Comments

Popular posts from this blog

A Step-by-Step Guide to Inserting an Account Record Using Apex in Salesforce Lightning Web Components (LWC)

Building a Real-Time Train Status Tracker with Salesforce LWC and Apex