简体   繁体   中英

How to write to a sheet with Google Sheets API without oAuth consent screen

I'm writing a script in PHP to automate the process of grabbing data from a Database and inserting it into a google sheet. Since it's going to be running at 15 minute intervals and Oauth consent screen isn't really the best option. Is there another option to get the necessary authorization to write to the sheet without the need of signing in via browser?

Most of the examples I've seen in the documentation and online use a consent screen. If I try this:

$client = new Google_Client(); 
$service = new Google_Service_Sheets($client);

Which would work with the Text-to-Speech API I get this (naturally):

> PHP Fatal error:  Uncaught Google\Service\Exception: {   "error": {
>     "code": 401,
>     "message": "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.",
>     "errors": [
>       {
>         "message": "Login Required.",
>         "domain": "global",
>         "reason": "required",
>         "location": "Authorization",
>         "locationType": "header"
>       }
>     ],
>     "status": "UNAUTHENTICATED"   } }

The link in the error message just guides you through making a consent screen. From what I could find online if i were to only be reading a file there wouldn't be a problem, but writing to it, even if i set the sheet to public, requires authentication.

Note: This is all running in a Gcloud VM instance

You can use a service account and then share the sheet with that service account.

  1. Go to console.cloud.google.com and login with the account containing the sheet
  2. Add the Google Sheets API (go to APIs and Services, look up Google Sheets API, add it)
  3. Go back to APIs and Services and click on Credentials
  4. Click on Create credentials -> Service account

凭证图片

  1. Fill in required stuff (mainly Service account name, and give it Owner role) and press done
  2. Click on the service account you just created
  3. Go to keys tab -> Add key -> Create new key -> JSON

键选项卡

This should give you a key to use. This is your client_secret.json. Use

$client->setAuthConfig('./client_secret.json') or $client->setAuthConfigFile('./client_secret.json')

depending on the version of the php google api client you are using.

Also, make sure you set the appropriate scope using

$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
  1. Share the sheet from your drive with the created service account and give it editorial permissions

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