Search code examples
google-apps-scriptgoogle-apps-script-api

Google Apps Script Error while creating document using execution API PHP Client


I tried fetching the list of folder and it got successfully fetched by php client. But when i tried creating a document using app script, the document gets created if i run app script code using Run icon in app script editor. But when I am using PHP client to execute the method, it shows me an error.

Caught exception: Error calling POST https://script.googleapis.com/v1/scripts/..................:run: (401) ScriptError

Also i have send both scopes:

https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/drive

$client = new Google_Client();
 $client->setApplicationName("Apps Script Execution");

     $client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/documents','https://www.googleapis.com/auth/drive.file'));
     //$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
     $client->setAuthConfigFile('client_secrets_app_script.json');

How can i fix it?

Here is my code.gs

/**
 * The function in this script will be called by the Apps Script Execution API.
 */

/**
 * Return the set of folder names contained in the user's root folder as an
 * object (with folder IDs as keys).
 * @return {Object} A set of folder names keyed by folder ID.
 */
function getFoldersUnderRoot() {
  var root = DriveApp.getRootFolder();
  var folders = root.getFolders();
  var folderSet = {};
  while (folders.hasNext()) {
    var folder = folders.next();
    folderSet[folder.getId()] = folder.getName();
  }



  var doc = DocumentApp.create('Naya Doc');
  var body = doc.getBody();
  var rowsData = [['Plants', 'Animals'], ['Ficus', 'Goat'], ['Basil', 'Cat'], ['Moss', 'Frog']];
  body.insertParagraph(0, doc.getName())
      .setHeading(DocumentApp.ParagraphHeading.HEADING1);
  table = body.appendTable(rowsData);
  table.getRow(0).editAsText().setBold(true);


  return folderSet;
}

Solution

  • Problem was in my code. I was using redirect URI and the permission scope was needed in both files. But i added permission scope in only one file. So add permissions in all files wherever you are requesting the client.