I thought this one was going to be a breeze. Hence I’m stuck at the very beginning 🙁
I created a Google Calendar where users can add events using a ‘shared’ dedicated login.
Then I need to write a PHP script on my server to read the events in a given time frame.
I thought the API key described here would be enough. But it’s not.
curl https://www.googleapis.com/calendar/v3/users/me/calendarList?key=mykey
says Login required.
So I read about OAuth2.0 and how I need user to authenticate. The problem is my script is not interactive (although hardcoding the login in the script is not a problem to me: The info is not life-critical). So I read about Service Accounts but it looks like it’s for non-user info.
Question: How do I code my script to force a given login without involving a human?
Note: This SO question seemed promising but the answer is for API version 2.0, which seems obsoleted.
The first thing you need to do is obtain an access token. This will require a human.
Assuming you’re using the Google APIs PHP Client, it can be done with this script (run from the command line).
NOTE: The snippet below works with a Client ID for Installed Applications. Make sure you create a client ID of this type in the Google API Access console.
This will give you a json encoded string containing your accessToken and refreshToken. The accessToken expires after 1 hour, but don’t worry. The refreshToken will not expire (unless you uninstall the application), and can be used to obtain a new refreshToken. The client library takes care of this part.
Next, save the full json string token (not only the access_token property in a safe place and make sure it can’t be read by others. Your app can then call
$client->setAccessToken($token)where $token was looked up from the safe location (Again,$tokenis the full json-encoded string, not limited to itsaccess_tokenproperty).Now, you can make authenticated request to the Calendar APIs!