OAuth2 with PHP’s built in Streams Functions

Most of the time when I work with APIs from PHP, I use Guzzle – it’s awesome and modern and elegant. However some of my work is with legacy platforms and I recently had a situation where we needed to integrate with a API using OAuth2, and launch that integration before the planned platform upgrade from an older version of PHP was expected to complete.

(this drives me nuts, I love upgrading systems but the downside is you have to work with the old ones first and none of the tools you want have been invented yet!)

For OAuth2, all I had to be able to do was to send an Authorization header with my web request from PHP. My second-favourite way of making API calls from PHP is to use PHP’s stream handling, so I did that. It’s not code you see very often but it’s super-simple and it works on every PHP platform I’ve tried so far, so here’s an example:

<?php

define("LOW_PRIORITY", 2048);  // default is 1024 

$queue =  new Pheanstalk_Pheanstalk($config&#91;'beanstalkd'&#93;&#91;'host'&#93; . ":" . $config&#91;'beanstalkd'&#93;&#91;'port'&#93;);

$queue->useTube("scorem")->put(json_encode(array("action" => "my_important_task")), LOW_PRIORITY);

If you’re trying to make an API call from PHP and installing better tools is hard for any reason, this example may help!

Using OAuth2 for Google APIs with PHP

I’ve been working on something recently where I’m pulling information from lots of places onto a dashboard. Each API has its own little quirks so I’m trying to write up the ones that weren’t idiot-proof, mostly so I can refer back to them later when I need to maintain my system!

I’ve written about Google and OAuth before, but that was OAuth v1.0, and they are introducing OAuth2 for their newer APIs; in this example I was identifying myself in order to use the Google Plus API (which turns out not to do anything you’d expect it to do, but that’s a whole separate blog post!). Continue reading