Home / Blog / Using the FreeAgent API with PHP and OAuth2

Using the FreeAgent API with PHP and OAuth2

13 Apr 2012

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 OAuth2Client($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(OAuth2Client::ACCESS_TOKEN_BEARER);

	//and make the request to the API
	$response = $client->fetch(
		$base_url . '/projects', //API path
		array(), //request parameters
		OAuth2Client::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.