I've searched for hours for an answer to this, so please bear with me!
I'm using Apps Script to connect to the Google Drive API. I have created a service account in Console, and collected the relevant credentials. I've got the following code:
function test()
{
function getOAuthService(user) {
var JSON = {
"private_key": "-----BEGIN PRIVATE KEY-----\nMY KEY HERE\n",
"client_email": "clientemail@clientemail.iam.gserviceaccount.com",
"client_id": "11111111111111",
"user_email": "myemail@myemail.com"
};
return OAuth2.createService("Service Account")
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(JSON.private_key)
.setIssuer(JSON.client_email)
.setSubject(JSON.user_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setParam('access_type', 'offline')
.setScope('https://www.googleapis.com/auth/drive');
}
function getUserFiles() {
var service = getOAuthService();
service.reset();
var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}, muteHttpExceptions: true
});
Logger.log(response.getContentText());
}
function reset() {
var service = getOAuthService();
service.reset();
}
getUserFiles()
}
I have also added the OAuth2 library into the script.
Every time I run this I am met with the following error though: Error: Access not granted or expired. (line 454, file "Service")
Does anybody have any ideas?
Thanks!