Hey there, fellow developer! Ready to dive into the world of Housecall Pro API integration? You're in for a treat. We'll be using the nifty compwright/oauth2-housecallpro
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that package installed. Fire up your terminal and run:
composer require compwright/oauth2-housecallpro
Easy peasy, right?
Now, let's set things up:
use Compwright\OAuth2\Client\Provider\HousecallPro; $provider = new HousecallPro([ 'clientId' => 'YOUR_CLIENT_ID', 'clientSecret' => 'YOUR_CLIENT_SECRET', 'redirectUri' => 'https://your-redirect-uri.com/callback' ]);
Time to implement the authorization flow:
$authorizationUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authorizationUrl); exit;
And handle that callback like a champ:
if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); exit('Invalid state'); } $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // Store this token somewhere safe!
Now for the fun part - let's make some requests!
GET request:
$request = $provider->getAuthenticatedRequest( 'GET', 'https://api.housecallpro.com/v1/jobs', $token ); $response = $provider->getParsedResponse($request);
POST request:
$request = $provider->getAuthenticatedRequest( 'POST', 'https://api.housecallpro.com/v1/jobs', $token, ['body' => json_encode($jobData)] ); $response = $provider->getParsedResponse($request);
Don't let those pesky errors catch you off guard:
try { $response = $provider->getParsedResponse($request); } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { // Handle OAuth errors echo $e->getMessage(); } catch (\Exception $e) { // Handle other errors echo $e->getMessage(); }
And when that token expires:
if ($token->hasExpired()) { $newToken = $provider->getAccessToken('refresh_token', [ 'refresh_token' => $token->getRefreshToken() ]); // Save the new token }
And there you have it! You're now ready to rock the Housecall Pro API like a pro. Remember, practice makes perfect, so don't be afraid to experiment and push the boundaries of what you can do with this integration.
Happy coding, and may your API calls always return 200 OK! 🚀