Have you ever wanted to push your Google Calendar event to Salesforce? Do you want to save at least $10 per user per month on purchasing apps? Here’s the recipe to build a simple solution yourself.
Prerequisite:
- A login to Salesforce org with Admin access privilege. Your profile needs to be API enabled.
- Create a security token to be used in the app. (You can use an existing token if you have one.) Your name > My Settings > Personal > Reset My Security Token.
The tutorial includes 4 steps:
- Create a Google Standalone App Script following. https://developers.google.com/apps-script/guides/standalone
- Connect your script to your Salesforce account.
- You need to configure Connected apps in setup menu to create a new remote access application. ( See details in tutorial below.)
- OAuth (Username and Password Flow) will be implemented for API authorization. Keep in mind that embed your username and password in application is not a good practice. OAuth(Refresh Token Flow) is more secure. We are not able to demonstrate this in the tutorial because, refresh token flow will prompt a page for user to approve Google accessing Salesforce Data. Google Standalone App Script doesn’t allow prompting a dialog/page.
- Pull calendar event from Google Calendar via Calendar API.
- Create event record in Salesforce via REST API.
Tutorial:
1. Create a standalone app script with a simple hello world function. Publish to web app. Copy the “Current Web App URL”. We will paste this to Salesforce later.
2. Now we want to whitelist the app you just created and let Salesforce know where to make callback to. Create a new Connected App from Salesforce > Setup > Connected Apps. Paste the “Current Web App URL” in OAuth “Callback URL” section. Configure Selected OAuth Scopes according to your own need.
Wait for 2-10 mins, go back to the app you just created. You will find “Consumer Key” (client_id) and “Consumer Secret” (client_secret). They will later be embeded in your request to Salesforce.
Manage OAuth policies of this app. Set “Relaxation” to “Relax IP Restrictions”.
Then copy and paste the source code to your own project. Put your User Settings in.
SalesforceConnectUtil.gs handles authorization with Salesforce.
//Salesforce Authorizatin Endpoint
var AUTHORIZE_URL = 'https://login.salesforce.com/services/oauth2/token';
//PUT YOUR USER SETTINGS HERE
var CLIENT_ID = 'REPLACE_WITH_YOUR_CLIENT_ID';//Consumer Key
var CLIENT_SECRET='REPLACE_WITH_YOUR_CLIENT_SECRET';//Consumer Secret
var USERNAME = 'REPLACE_WITH_YOUR_USERNAME';
var PASSWORD = 'REPLACE_WITH_YOUR_PASSWORD_SECURITY_TOKEN';//password+securitytoken
function loginToSalesforce(){
var token = PropertiesService.getScriptProperties().getProperty('token');
//If user doesn't have a token
if(!token){
//Request access token using username and password
var response = requestService().getContentText();
//Parse and store access token, instance_url
parseResponse(response);
}
}
function requestService(){
var payload = {
"grant_type" : "password",
"client_id" : CLIENT_ID,
"client_secret" : CLIENT_SECRET,
"username" : USERNAME,
"password": PASSWORD
};
var options = {
"method": "post",
"payload": payload
};
return postToURL(AUTHORIZE_URL, options);
}
function parseResponse(r){
//Parse Response
var tokenResponse = JSON.parse(r);
//store token and instsanceURL
PropertiesService.getUserProperties().setProperty( 'instance_url', tokenResponse.instance_url);
PropertiesService.getUserProperties().setProperty( 'token', tokenResponse.access_token);
}
3. Retrieve calendar event from Google Calendar using Calendar API. Note that to keep it simple, the sample code only fetches 1 calendar event.(The 1st event in the future) It’s a simple modification to retrieve multiple events at a time. Be aware if you want to send multiple records to Salesforce, REST API will not be the best choice. Consider using SOAP API or Bulk API in step 4.
//Google Calendar API: https://developers.google.com/google-apps/calendar/v3/reference/events/list
function retrieveCalendarEventFromGoogle() {
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),//Lower bound (inclusive) for an event's end time to filter by.
showDeleted: false,
singleEvents: true,
maxResults: 1,//Maximum number of events returned on one result page.
orderBy: 'startTime'
};
var eventList = Calendar.Events.list(calendarId, optionalArgs).items;
if(eventList.length > 0 ){
return eventList[0];
}
}
4. Now, it’s time to create Event in Salesforce with REST API.
function sendEventToSalesforce(event){
var url = getRestAPIEndpoint()+'/sobjects/Event/';
var payload = {
"Subject" : event.summary,
"Location" : event.location,
"Description" : event.description,
"StartDateTime" : Utilities.formatDate(new Date(), "GMT", "yyyy-mm-dd'T'hh:mm:ss'Z'"),
"EndDateTime" : Utilities.formatDate(new Date(), "GMT", "yyyy-mm-dd'T'hh:mm:ss'Z'")
};
var options = {
"method": "post",
"contentType" : "application/json",
"headers" : {
"Authorization" : "Bearer " + PropertiesService.getUserProperties().getProperty('token')
},
"payload" : JSON.stringify(payload)
};
var res = postToURL(url, options);
Logger.log(res.getContentText());
}
Finally, it’s time to celebrate your success. Create a future event on your Google Calendar, run the script and go back to Salesforce. Hurrah! A brand new event just get created!
Reference:
https://www.youtube.com/watch?v=9SEAmNDtlcA&list=PL68F511F6E3C122EB