Reputation: 473
I'm trying to build a web app that will access a user's Google Calendar API without them actually being there. So basically add or modify events in their Google Calendar from my server (PHP script) in the background.
I am already oauth2 from Google Calendar and I have a refresh token for them so they don't have to re-login each time. They just log into oauth once and they are good. But how can I make it so that the server can make changes in the background?
Upvotes: 0
Views: 543
Reputation: 473
I figured it out. So what I did was I stored the access_token
in the database and checked if the access token was expired. If it was, I would use the refresh_token
in the database to generate a new access token. So every time the server would access the user's account, it would use the access token from the database. Also, make sure to set the access type to offline
like so:
$client->setAccessType('offline');
Upvotes: 1
Reputation: 789
Doing asynchronous work is usually workflow breaking if you're used to making "normal" webpages, because any asynchronous activity lives outside the usual request lifecycle.
You need to delegate the async task to a dedicated program, process or thread. This implies using a sort of queuing system and having a separate process whose job is to run the tasks in the queuing system and updating the status.
If you're on the road to learning, I'd suggest you roll out your own - a minimal queuing system is a good learning project; you can roll it out using your regular database management system. You'll have to look out for race conditions (hint: use row locks).
If you're on the road to production, I'd recommend using something like ZeroMQ for that - I understand there are good bindings for PHP.
Besides having your website update and read from the queueing system you'll need the task runner - the simplest form of which is a scheduled job; you could do a simple php script living in a while
loop, sleeping for some time (depending on the traffic of the software you're building), checking if there's something in the job queue, and doing the updates when needed.
You'll probably need to learn how to get a process to run every time the computer boots in order to do it, otherwise a simple system reboot would bork your setup.
In the end, the workflow would be a bit like this:
Upvotes: 0