Google Apps Script Error while creating document u

2019-08-11 06:18发布

问题:

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;
}

回答1:

As James Nicholas said, this error is from lack of permission scope. I got this same error when extending the PHP quickstart.php tutorial. When the Google Apps Script function is modified and published, it should have pointed out to you that the scopes have changed. You will need to adjust the defined scopes in the PHP as well.

To find the scopes you need to add, go to File -> Project Properties and click the Scopes tab.

For example I added https://www.googleapis.com/auth/spreadsheets:

define('SCOPES', implode(' ', array(
  "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets")
));

Once you do that, you will need to delete the .credentials/script-php-quickstart.json as it says to do in the comment above so that your that the scopes can regenerate properly.



回答2:

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.