Edinburgh Web Development

FreeAgent integration using PHP OAuth2

Here's how to do it

by Iain Wilson

19 March 2014
Freeagent

FreeAgent is a great cloud based accountancy product, developed right here in Edinburgh.

It's used by loads of small and medium sized businesses all over the world.  

In addition to the user software, FreeAgent have an application programming interface (API).  If you can program, you can integrate FreeAgent into your software to do things like automatically creating invoices from online sales.

In this article, we'll look at the PHP programming needed to authenticate and carry out instructions.  If you're not a programmer, this is going to sound like double-Dutch, sorry.

Security using OAuth2

Security is obviously a big factor in this and FreeAgent uses OAuth2 to authenticate access and transactions.  

OAuth is a security standard and involves a series of exchanges between a program and a host to authenticate the access and establish a connection to send and receive information.

Not surprisingly, this involves a level of complication but the steps are quite clear.

Before you can do anything though, you must register your integration app within your FreeAgent developer account. Once you've registered, you will have a unique OAuth Client ID and Secret - these will always be used whenever your want to run your integration.

The basic steps are

  1. The app sends the user to the API endpoint, and provides the Client ID.  The endpoint will ask the user to log into FreeAgent using their credentials, and approve access.
  2. If this is done satisfactorily, FreeAgent will send the app an authorisation token.
  3. The app can then use this authorisation token along with the Secret and Client ID to request an Access Token.
  4. Once the app has an Access Token, it must use this in every API request.
  5. An Access Token will last for a while, so you don't necessarily have to go through the entire authtication process every time, but in our example we'll assume that you do.

OAuth2 libraries

There are several OAuth2 client libraries available which do the heavy lifting of some of the the security exchanges. We used the PHP-OAuth2 one which can be easily downloaded from GitHub at https://github.com/adoy/PHP-OAuth2

However, it proved difficult to find examples of using the library, so we thought we'd share how we did it. The following paragraphs give examples of the code used to do each of the steps above.

Setup

require('client.php');
require('./GrantType/IGrantType.php');
require('./GrantType/AuthorizationCode.php');
const CLIENT_ID     = 'yourClientId';
const CLIENT_SECRET = 'YourSecret';

const REDIRECT_URI           = 'https://www.yoursite.com/yourApp.php';
const AUTHORIZATION_ENDPOINT = 'https://api.freeagent.com/v2/approve_app';
const TOKEN_ENDPOINT         = 'https://api.freeagent.com/v2/token_endpoint';
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); 

The setup simply involves setting up the libraries by including them using the require statements, creating constants with your ID and Secret, creating constants for the API endpoints and most importantly, the location of your app that the API should redirect to once it does its work (this can be entered into your details in Freeagent when registering the app).  

In this case we're coding a single program so the redirection will be the name of the current program. Finally we create an instance of the OAuth2 object in $client. 

Athentication

if (!isset($_GET['code']) && !isset($_GET['token']) )
{
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
    header('Location: ' . $auth_url);
    die('Redirect');
}

Now we need to get authenticated.  We test for 'code' and 'token' variables. These will not be set if the program has not got authentication, so we call the getAuthenticationUrl method to get authentication.  What will happen at this point is that the user will be redirected to the API endpoint where they must provide the correct username and password and confirm access is allowed.  

If this is done satisfactorly, the user will be redirected back to the app program, but this time the redirection will provide an authentication code we will use to get an access token.

Access Token

elseif (isset($_GET['code']))
{
	$params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
        $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
	$result=json_decode($response['result'],true); // old version when json was returned
	$access=$response['result']['access_token'];
	header('Location: https://www.yoursite.com/yourApp.php?token=' . $access);
	exit();
}

So we use the authentication code and redirect location as parameters to the getAccessToken method, which will return a valid access token. We then redirect to your app using the token as a parameter.  At this point we are now able to start making API requests using the access token.

API requests

elseif (isset($_GET['token'])) 
{
	$access=$_GET['token'];
	$client->setAccessToken($access);

        $info = $client->fetch('https://api.freeagent.com/v2/freeagent_request',
	  array(), 
          'GET', 
          array('Authorization' => 'Bearer '. $access,'User-Agent' => 'App name')
		);
}

We use the access token to make API endpoint requests to Freeagent, according to their spec.  In thise case 'freeagent_request' would be one of their documented requests, with any request parameters in the first array.  

After the request, $info will contain the fetched data in JSON format, or any error message if the command was not successful.

Liked this article? Please share it with your friends and colleagues.


comments powered by Disqus
 
Blot Design,
10 Colinton Road, Edinburgh, EH10 5DT
Terms, Cookies & Privacy