I need to write Apex code to connect with Google Drive and create a Spreadsheet and write data into it.
I am done with google Drive Authentication but now i am not getting how to create Spreadsheet and what scope should i give in Auth request so that i can create/ modify Spreadsheet. Below is my code. Can anyone please help -
public class GoogleDriveController {
private String code ;
private string key = '548018328029-3l8hn2ikongosaeudp87he1r6s9rv3jhskl.apps.googleusercontent.com' ;
private string secret = 'PF1yzvAlhlY71cmUFSSQvPoXjA' ;
private string redirect_uri = 'https://c.ap2.visual.force.com/apex/GoogleDrivePage' ;
public GoogleDriveController()
{
code = ApexPages.currentPage().getParameters().get('code') ;
System.debug('codesdd:::' + code);
if(code != '' && code != null)
{
System.debug('code:::' + code);
AccessToken() ;
}
}
public PageReference DriveAuth()
{
PageReference pg = new PageReference(GoogleDriveAuthUri (key , redirect_uri)) ;
return pg ;
}
public String GoogleDriveAuthUri(String Clientkey,String redirect_uri)
{
String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
String authuri = '';
authuri = 'https://accounts.google.com/o/oauth2/v2/auth?'+
'scope=https://spreadsheets.google.com/feeds&'+
'state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
'redirect_uri=' +uri+
'&response_type=code&'+
'client_id='+key+
'&access_type=offline';
return authuri;
}
public void AccessToken()
{
//Getting access token from google
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://accounts.google.com/o/oauth2/token');
req.setHeader('content-type', 'application/x-www-form-urlencoded');
String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
req.setHeader('Content-length', String.valueOf(messageBody.length()));
req.setBody(messageBody);
req.setTimeout(60*1000);
Http h = new Http();
String resp;
HttpResponse res = h.send(req);
resp = res.getBody();
String str = resp;
List<String> lstStr = str.split(',');
List<String> lstStr1 = lstStr[0].split(':');
String st = lstStr1[1].remove('"').trim();
SpreadsheetService service = new SpreadsheetService();
service.setAuthSubToken(st);
GoogleData sheets = service.getSpreadsheets();
sheets.dump();
} }