简体   繁体   中英

OAuth 2.0 from Google Apps Script (GAS) to Sheets API

Based on the Google's documentation , I've implemented the following code to append a row to the Google Sheet (and I'm owner of this sheet).

function addSalaryLog(updateArray) {
  const resource = {
    "majorDimension": "ROWS",
    "values": [updateArray]
  };
  const spreadsheetId = 'here_goes_the_spreadsheet_id';
  const range = 'A:A';
  const optionalArgs = {valueInputOption: "USER_ENTERED"};
  Sheets.Spreadsheets.Values.append(resource, spreadsheetId, range, optionalArgs);
}

When I call it, in return I get the following error:

GoogleJsonResponseException: API call to sheets.spreadsheets.values.append failed with error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project .

No need to ask, I clicked the link :-) It explains how to create an OAuth 2.0 in the developer console. Created ✅. But later it does not explain how to actually authorize the script. I expect that before calling the Sheets API, I should be able to trigger launching the permission dialog.

I see the following, possible options:

  1. Instead of Sheets.... use URLFetch .
  2. Trigger the authentication (preferred). Any tips here?

UPDATE I've implemented testAddSalaryLog() which is exactly the same as the original function but has hardcoded values. And it works! It makes me think that the solution is to force the permission screen to trigger.

I have 3 questions/suggestions:

Question 1.

Since you are using the Sheets API. Have you enabled the Google Sheets API advanced service in your script? From Editor > Service > Google Sheet API ?

在此处输入图像描述

在此处输入图像描述

Question 2.

Have you reviewed if the "Sheets API scope" were added to the script by reviewing the project Overview ? If they were not added automatically, you need to add them manually by following these steps:

  1. Access the 'Project Settings' to enable the manifest file in the editor. 在此处输入图像描述

  2. Return to the editor and select 'appsscript.json' 在此处输入图像描述

  3. Add the scopes:

    "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/spreadsheets" 在此处输入图像描述

Question 3.

Have you authorized the code already?

In the Apps Script editor, click Run . The first time you run the sample, it will prompt you to authorize access:

Select Review permissions > Allow.

在此处输入图像描述

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM