Using the Infusionsoft PHP SDK with a Microframework

Languages: PHP | Difficulty: Moderate

Setup & Install Laravel Lumen

Many applications that rely on data from Keap need to allow a server to make requests on a user's behalf. For example, we may have a job that runs nightly to ingest all of the user's contacts and save them to our application's database. To demonstrate how this works, we've created three very simple endpoints in our sample application - one that authenticates the user, one handles the Infusionsoft OAuth callback, and one that performs a request to grab some data from Keap.

To get started, we recommend cloning the example code from Github. Make sure to follow the installation instructions in the readme (here's a brief overview):
  1. Clone the repo
  2. Create a new file named .env and duplicate all of the keys in the included .env.example file. Then, set all the proper values for APP_KEY, all keys prefixed with DB_ if you plan to use a database, and all keys prefixed with INFUSIONSOFT_
  3. Run composer install

Next: Update Your routes.php File

Update Your routes.php File

Take a look at the provided routing instruction at /app/Http/routes.php. We're going to create three routes for this application:
  • /, or the root location, is going to show our users a link to begin the authentication process
  • /callback is the route we're going to tell Keap to redirect our user to after they grant our application permission to access their account
  • /contacts is going to show our user a list of their contacts that have a first name of "John"

For now, your routes file should look like this:


$app->get('/', function() use ($app) { ... });

$app->get('/callback', function() use ($app) { ... });

$app->get('/contacts', function() use ($app) { ... });


Next: Direct the User to Infusionsoft

Direct the User to Infusionsoft

$app->get('/', function() use ($app) {

	// Setup a new Infusionsoft SDK object
	$infusionsoft = new InfusionsoftInfusionsoft(array(
		'clientId'     => getenv('INFUSIONSOFT_CLIENT_ID'),
		'clientSecret' => getenv('INFUSIONSOFT_CLIENT_SECRET'),
		'redirectUri'  => getenv('INFUSIONSOFT_REDIRECT_URL'),
	));

	echo '&#60a href="' . $infusionsoft->getAuthorizationUrl() . '">Click here to connect to Infusionsoft</a>';

});

Next: Exchange the Code for an Access Token

Exchange the Code for an Access Token

After the user has granted permission to our application, they'll be directed back to the redirect_url you specified earlier. We'll exchange that access code for an access token, and save that token to the session.

$app->get('/callback', function() use($app) {

	// Setup a new Infusionsoft SDK object
	$infusionsoft = new InfusionsoftInfusionsoft(array(
		'clientId'     => getenv('INFUSIONSOFT_CLIENT_ID'),
		'clientSecret' => getenv('INFUSIONSOFT_CLIENT_SECRET'),
		'redirectUri'  => getenv('INFUSIONSOFT_REDIRECT_URL'),
	));

	// If the serialized token is already available in the session storage,
	// we tell the SDK to use that token for subsequent requests, rather
	// than try and retrieve another one.
	if (Session::has('token')) {
		$infusionsoft->setToken(unserialize(Session::get('token')));
	}

	// If we are returning from Infusionsoft we need to exchange the code
	// for an access token.
	if (Request::has('code') and !$infusionsoft->getToken()) {
		$infusionsoft->requestAccessToken(Request::get('code'));
	}

	// NOTE: there's some magic in the step above - the Infusionsoft SDK has
	// not only requested an access token, but also set the token in the current
	// Infusionsoft object, so there's no need for you to do it.

	if ($infusionsoft->getToken()) {
		// Save the serialized token to the current session for subsequent requests
		// NOTE: this can be saved in your database - make sure to serialize the
		// entire token for easy future access
		Session::put('token', serialize($infusionsoft->getToken()));

		// Now redirect the user to a page that performs some Keap actions
		return redirect()->to('/contacts');
	}

	// something didn't work, so let's go back to the beginning
	return redirect()->to('/');
});


Next: Use the Access Token to Make a Request

Use the Access Token to Make a Request

Now that we have permission and an access token, we can request data from Keap on behalf of the user. You can utilize the full power of the API at this point, but in this example we're just going to grab the first 10 users that have a first name of "John"

$app->get('/contacts', function() use ($app) {

	// Setup a new Keap SDK object
	$infusionsoft = new InfusionsoftInfusionsoft(array(
		'clientId'     => getenv('INFUSIONSOFT_CLIENT_ID'),
		'clientSecret' => getenv('INFUSIONSOFT_CLIENT_SECRET'),
		'redirectUri'  => getenv('INFUSIONSOFT_REDIRECT_URL'),
	));

	// Set the token if we have it in storage (in this case, a session)
	$infusionsoft->setToken(unserialize(Session::get('token')));

	try {
		// Retrieve a list of contacts by querying the data service
		$contacts = $infusionsoft->data->query('Contact', 10, 0, ['FirstName' => 'John'], ['FirstName', 'LastName', 'Email', 'ID'], 'FirstName', true);
	} catch (InfusionsoftTokenExpiredException $e) {
		// Refresh our access token since we've thrown a token expired exception
		$infusionsoft->refreshAccessToken();

		// We also have to save the new token, since it's now been refreshed. 
		// We serialize the token to ensure the entire PHP object is saved 
		// and not accidentally converted to a string
		Session::put( 'token', serialize( $infusionsoft->getToken() ) );

		// Retrieve the list of contacts again now that we have a new token
		$contacts = $infusionsoft->data->query('Contact', 10, 0, ['FirstName' => 'John'], ['FirstName', 'LastName', 'Email', 'ID'], 'FirstName', true);
	}

	return $contacts;

});

Discussion