Using the FreeAgent API with PHP and OAuth2

FreeAgent, the online business accounting software that we use, has just released a new version of its developer API. This post explains how to authenticate with the API from a PHP script and start fetching data.

The new API uses OAuth 2.0 for authentication instead of HTTP Basic Auth used in the previous version. OAuth 2.0 is designed to be simpler to implement than OAuth 1.0 but it’s still in development which means documentation and client libraries are a bit thin on the ground. I’m using PHP-OAuth2 and you’ll need to download those files to use this example.

First, go to the FreeAgent Developer Dashboard and create an app. Put whatever you want in the name and description fields and leave the URL fields empty. Once created, copy the OAuth identifier and secret and paste them into the script below. Save the script on your local web server and load it up in a browser. That’s it!


require_once 'GrantType/IGrantType.php';
require_once 'GrantType/AuthorizationCode.php';
require_once 'Client.php';

//get these values from the FreeAgent developer dashboard
$identifier = '';
$secret = '';

//the URL of this script. doesn't have to be publicly accessible.
$script_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

//the base URL of the API. shouldn't need to change this.
$base_url = 'https://api.freeagent.com/v2';

//create the OAuth client
$client = new OAuth2\Client($identifier, $secret);

//check what stage we're at
if (empty($_GET['code']) && empty($_GET['token'])) {

	//no code and no token so redirect user to FreeAgent to log in
	$auth_url = $client->getAuthenticationUrl($base_url . '/approve_app', $script_url);
	header('Location: ' . $auth_url);

} elseif (isset($_GET['code'])) {

	//we have a code so use it to get an access token
	$response = $client->getAccessToken(
		$base_url . '/token_endpoint',
		'authorization_code',
		array('code' => $_GET['code'], 'redirect_uri' => $script_url)
	);

	//normally you would store the token for use in future requests
	$token = $response['result']['access_token'];
	header('Location: ' . $script_url . '?token=' . $token);

} elseif (isset($_GET['token'])) {

	//when we have a token, just set up the client
	$client->setAccessToken($_GET['token']);
	$client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);

	//and make the request to the API
	$response = $client->fetch(
		$base_url . '/projects', //API path
		array(), //request parameters
		OAuth2\Client::HTTP_METHOD_GET, //GET, PUT, POST, DELETE
		array('User-Agent' => 'Example app') //API requires UA header
	);

	//show response
	echo '<pre>'.print_r($response, true).'</pre>';
}

This is just a simple example to get you started. A real implementation would do error checking and much more.

Hope it helps.

Comments

Tom 6 Nov 2012

This is brilliant – it helps make it so much easier than a lot of the stuff out there that makes you go round in circled!
I have managed to get it to bring the data back, as per the example.
How would I be able to get it to bring back the data in an user friendly way that displays it in a table and say bring back all the expenses associated with a given project, for example?

Thanks so much.

James stevenson 10 Apr 2013

I used this script to enable my app, now I am stuck.

After the app has been approved how can I create a new contact and invoice using php curl script?

Tamlyn 10 Apr 2013

@Tom Once you have the response, you can parse data out of it and display it however you like, just as with any other data in PHP.

@James Don’t use cURL, use the Client object which does the OAuth stuff for you. Take a look at the API docs for creating invoices and modify the $client->fetch() command appropriately.

Write a comment