1
votes

I'm trying to insert a new event using only an API Key that I created.

The problem is that when I'm just checking available times using FreeBusy, everything works perfectly, but when I try to create and insert a new event, I get the following error:

Uncaught Google_Service_Exception: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

In the Authorizing Requests to the Google Calendar API page it is stated that:

Your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported. If your application uses Google Sign-In, some aspects of authorization are handled for you.

But I can't manually authorize access to the calendar every time it is asked for.

How can I authorize requests and insert new events without having to manually authorize them?

1
If you read the rest of the page in the docs developers.google.com/calendar/auth you will see that once a user has authorized your app to access their calendar, it will issue you a token that you can store and user for future calls to the API. - lufc
@lufc Yes, I know that. The problem is that after 1 hour the token expires and I have to manually run my code again through the terminal just so I can get the auth link, give my consent, copy the code, paste it in the terminal and then finally refresh the token. - Daniel Bertoldi
Use a refresh token to generate a new token outside the first hour. See here getRefreshToken() github.com/googleapis/google-api-php-client/blob/master/src/… - lufc

1 Answers

1
votes

You need to use a Service Account, if you want to perform server-to-server API requests. Please see https://developers.google.com/calendar/auth.

Generally you'd create a key, and download the JSON file that is provided. You can then call $client->setAuthConfig($jsonPath); to set up authentication. It's probably a good idea to keep the private key outside of the web root. Then set the scope using $client->addScope('https://www.googleapis.com/auth/calendar'), and instantiate the Calendar service using $service = new Google_Service_Calendar($client);. You should now be able to do your stuff.

You may also need to share the calendar with the generated e-mail address that is associated with the Service Account.