Hello friends, In this post, I will show you how you can integrate Salesforce with Google Calendar so that Salesforce user could aware of all upcoming events and tasks!
Below is the list of all the tasks that we will do in this post to do Integrate Google Calendar with Salesforce.
- Create a public List type Custom Setting “GoogleCalenderInfo” to store the access/refresh token and expiry time (in Seconds).
- Enable Google Calendar API and create an App to get the Consumer Key and Consumer Secret
- Create VF page Apex Class to make the callout and store Access/Refresh Token into Custom Setting.
- Create Another VF page which will fetch all the List of Calendar Available into your Calendar and create a new Calendar From Salesforce.
Create New Custom Setting: –
Login into Your Salesforce Org and go to Setup -> Develop -> Custom Settings -> New
See below image for the field names and data types
Create Required VF pages and Apex Classes: –
- Open Developer Console and Create 2 Apex Classes GoogleCalenderApi and GoogleCalendarActionsController.
- Now, Create 2 VF pages “GoogleCalendarActions” and “GoogleCalenderoAuth”
- You will get the Complete code for All the pages and Apec Classes From Here copy the code and paste in your pages/classes.
Do Enable Google Calendar API and Settings: –
Go to Using OAuth 2.0 to Access Google APIs and you will get Detailed Information about authentication process.
Go to Google API Console, Credentials -> Create Credentials -> oAuth Client Id
Application Type -> WEB
Authorized redirect URIs -> URL To Your VF page “You already have created the VF page if not follow the above steps and create both the pages with classes”
Open “GoogleCalenderoAuth” VF page, Click Preview and Copy the URL that URL is the Redirect URI paste that URL here.
Note: – You also need to replace “redirect_uri” variable in GoogleCalendarAPI class with your VF page URL.
Now, Click Create, a Pop up with Client Id and Client Secret will open
Copy both Client Id and Client Secret in any text Editor like notepad++, notepad, or any editor.
Now, Open GoogleCalenderApi class replace consumerKey with your Client Id and clientSecret with your Client Secret.
Now, as we have done all the necessary steps and it’s show time.
Open “GoogleCalenderoAuth” VF page, preview it Page will look like below
Click “Connect With Calendar” you will be redirected to Gmail Login, Login with your Gmail, Grant Access to Application. You will get back to the same Page and Now Click “Get Access Token” a new Page “GoogleCalendarActions” will open.
First, we will create a New Calendar, Enter “Testing Google API ” and then Create New Calendar. You will get a Success Message with the response.
Now, List All Calendars will list all the calendars that are available to your Account.
Note: – Using the Above Code of “GoogleCalenderoAuth” Page and “GoogleCalenderApi” Apex Class you can integrate with Any Google API. You only need to make a minor change which is the value of the calendar_Scope variable in GoogleCalenderApi class, use the scope of the API that you want to Connect. You will get the scope of all the APIs OAuth 2.0 Scopes for Google APIs.
Any Queries come in the comment section.
Hi amit could you post the vf page code as well please thank you.
LikeLike
Hi Amit,
Can you please tell me how to add event dynamically based on your given code.
LikeLike
Working on that will post the same.
LikeLike
Any updates regarding this query?It will be of a great help!
LikeLike
Hey, Which query you are referring ?
LikeLike
Sorry, but now that I have more of this setup I was wondering if you found the format for sending multiple events to the google calendar in one call?
LikeLike
Found this with the use of Batch calling. (Sorry to be blowing up the blog comments.)
My last issue pertains to Events and their Start/End Times when syncing them one way or the other. I seem to not be able to get them to create in the other place for the same time.
I know I must have to do something with the usage of timezones but not sure exactly the best way to handle.. Currently both the SF and Google side are in the same time zone but when parsing the data from or to I must not be doing something quite right..
I was hoping you or someone else may have a good example for this?
LikeLike
Hey Amit,
I am trying to implement this but keep hitting Status Forbidden and Code 403
is there a step I am missing to give access? (I can’t even get it to create a new Calendar)
Do I need to link to the same Gmail account? (I wouldn’t assume so)
LikeLike
I found my issue. I needed to grant calendar permissions to the new API Account email. Working so far tho!
LikeLike
Hi Amit, Can I have the code for GoogleCalendarActionsController and GoogleCalenderApi
LikeLike
Yes of course here are both
public class GoogleCalendarActionsController {
public static String Summary { get; set; }
Public Static String allCalendars { get; set; }
public Static Boolean isListCalendars { get; set; }
}
public class GoogleCalenderApi {
LikeLike
Thanks Amit this looks amazing!!
One question I have is if this would work to have it link to Community Users Gmail accounts.
So we would have a Business Account as the API and App account but then have “Users” as portal users linking their personal Gmail Accounts to pull and sync their Events.
I want to assume it will work but figured I would ask before trying.
LikeLike
Yes. It will work. The only thing you need to do is to provide the access to Page/Class and Objects where you are storing the tokens.
LikeLike
Hi Amit,
thanks for the article, it has been very helpful.
When the access token is not working anymore, I would like to use the GoogleCalenderApi.doRefreshToken() method in order to get a valid access token.
It is not easy since in order to do this, you need to chain 2 http requests which are asynchronous.
Any idea about how to do this?
LikeLike
Thanks for the complement,
Will post a block of code soon for the same.
LikeLike
Thanks Amit, that would be awesome.
LikeLike
*I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!?
LikeLike
Can we integrate google calender in lightning using components?
LikeLike
Yes, we definitely can. You can try any problem I will help you
LikeLike
Do you have any reference?Can u post here…
LikeLike
At present, I don’t have but I will post ASAP :). in the mean time you can try by yourself 🙂
LikeLike
Can u tell how to send google calender invitation through apex code?
LikeLike
Hi Megha,
While creating the Event you can specify the email of the attendees see my previous comment. If you want to add attendee in existing event then you need to perform update on event which will need event Id.
See the link for reference – https://developers.google.com/google-apps/calendar/v3/reference/events/insert
LikeLike
Hii Amith,
While creating an event that attendies should also get an invitation email,it will create an event in attendies calender but is there anyway to send event invitation email.
LikeLike
Hi Megha,
Let me check for this and I will get back to you ASAP 🙂
LikeLike
Hi Megha,
Use sendNotifications parameter as true into your end point to send the notifications. Your endpoint will look like below
https://www.googleapis.com/calendar/v3/calendars/calendarId/events?sendNotifications=true
Where calendarId is your/organizer email Id.
Thanks,
Amit Singh
LikeLike
Thanks Amith.It works….
LikeLike
Great happy to help you 🙂
LikeLike
Can u tell how to create an calendar event??
LikeLike
Hi Pavan,
Yes, Please use the below code for Creating a new Event into Google Calendar. For testing purpose I have hardcoded the Event body make sure you are passing the dynamic body as per your requirement.
Find new Apex Class method
public static void doCreateNewCalendarEvent(){
List googleSettingInfoList = new List();
googleSettingInfoList = GoogleCalenderInfo__c.getAll().values();
String accessToken = googleSettingInfoList[0].Access_Token__c;
String createEventEndPoint = ‘https://www.googleapis.com/calendar/v3/calendars/’+ calendarIdHere (Your/Organizer Email here) +’/events’;
String createEventBody = ‘{‘ +
‘”attendees”: [‘+
‘{‘+
‘”email”: “cse.amitallenhouse@gmail.com”‘+
‘},’+
‘{‘+
‘”email”: “cse.amitallenhouse@gmail.com”‘+
‘}’+
‘],’+
‘”attachments”: [‘+
‘{‘+
‘”fileUrl”: “”‘+
‘}’+
‘],’+
‘”end”: {‘+
‘”dateTime”: “2017-11-11T03:30:00-07:00″‘+
‘},’+
‘”reminders”: {‘+
‘”useDefault”: true’+
‘},’+
‘”start”: {‘+
‘”dateTime”: “2017-11-11T03:30:00-06:00″‘+
‘},’+
‘”summary”: “This is Test Event Using Calendar API “,’+
‘”location”: “B 24 Noida Sec 65″‘+
‘}’;
System.debug(‘#### createEventBody ‘+createEventBody );
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse HttpRes = new HttpResponse();
httpReq.setEndpoint(createEventEndPoint);
httpReq.setMethod(‘POST’);
httpReq.setBody(createEventBody );
httpReq.setHeader(‘Content-Type’, ‘application/json’);
httpReq.setHeader(‘Authorization’,’Bearer ‘+accessToken);
try{
HttpRes = http.send(httpReq);
if(HttpRes.getStatusCode() == 200){
ApexPages.addmessage(new ApexPages.message(
ApexPages.severity.CONFIRM,’Calendar Event Successfully ‘+’\n’+’ ‘+
HttpRes.getBody()));
}else{
String errorMessage = ‘Unexpected Error while communicating with Google Calendar API. ‘
+’Status ‘+HttpRes.getStatus()+’ and Status Code ‘+HttpRes.getStatuscode();
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,errorMessage));
}
}catch(System.Exception e){
System.debug(‘#### Exception Executed : ‘+e.getMessage() + ‘ ‘+e.getStackTraceString() + ‘ ‘+e.getLineNumber());
}
}
Below is Apex page code to call the method
Keep learning 🙂
Let me know if you have any issue 🙂
LikeLike
++ You can get a list of all the operation here and can try the same by your self
https://developers.google.com/google-apps/calendar/v3/reference/events/insert
LikeLike
tq amit. It works
LikeLike
hii amith,
Instead of hard coding values,if I bind a variable a status 400 error is throwing,can u give an example to one of event attributes(In createeventbody) to bind a variable.
LikeLike
What code are you using for dynamic binding please post your VF and controller code here
LikeLike
Prasad were you able to resolve the same?
LikeLike
Hi Amit,
How to add attachments to this event?
What does fileurl mean?
LikeLike
Will post the code for the soon ASAP.
LikeLike
Hi Amit,
Can you please tell us how to make dynamic event Body
LikeLike
Hi Amit,
I am facing the error while executing the code Error Name is “Invalid Credential”
but when i am connecting through your Visualforce page GoogleCalenderOauth that time i am able to connecting with my Google calender.
Please help me out to find the Solution.
LikeLike
Invalid credentials mean that either your google credentials are wrong or API Key and API Secret or wrong. Also, I will suggest creating the App in your google console because it requires the redirect URL.
LikeLike