Back

Step by Step Guide to Building a Microsoft Office 365 API Integration in PHP

Aug 2, 20245 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Microsoft Graph API? If you're looking to integrate Office 365 functionality into your PHP application, you're in the right place. We'll be using the microsoft/microsoft-graph package to make our lives easier. Let's get started!

Prerequisites

Before we jump in, make sure you've got:

  • A PHP environment (you're a pro, so I'm sure you've got this covered)
  • Composer installed (because who wants to manage dependencies manually?)
  • A Microsoft 365 developer account (if you don't have one, go grab it – it's free!)

Setting up the project

First things first, let's get our project set up:

composer require microsoft/microsoft-graph

Don't forget to include the Composer autoloader in your PHP script:

require_once 'vendor/autoload.php';

Registering the application in Azure AD

Now, let's get our app registered in Azure AD:

  1. Head over to the Azure Portal
  2. Navigate to "App registrations" and click "New registration"
  3. Give your app a snazzy name and configure the redirect URI
  4. Once registered, grab your client ID and create a client secret

Keep these handy – we'll need them soon!

Authentication

Time to implement the OAuth 2.0 flow. Here's a quick example:

use Microsoft\Graph\Graph; use Microsoft\Graph\Model; $guzzle = new \GuzzleHttp\Client(); $url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/v2.0/token'; $token = json_decode($guzzle->post($url, [ 'form_params' => [ 'client_id' => $clientId, 'client_secret' => $clientSecret, 'scope' => 'https://graph.microsoft.com/.default', 'grant_type' => 'client_credentials', ], ])->getBody()->getContents()); $accessToken = $token->access_token;

Making API calls

Now for the fun part – let's make some API calls!

$graph = new Graph(); $graph->setAccessToken($accessToken); // Get user profile $user = $graph->createRequest("GET", "/me") ->setReturnType(Model\User::class) ->execute(); // Send an email $message = new Model\Message(); $message->setSubject("Hello from Graph API!"); $message->setBody(new Model\ItemBody(["content" => "This is the body"])); $message->setToRecipients([ new Model\Recipient(["emailAddress" => new Model\EmailAddress(["address" => "[email protected]"])]) ]); $graph->createRequest("POST", "/me/sendMail") ->attachBody(["message" => $message]) ->execute();

Handling responses and errors

Always be prepared for things to go wrong:

try { $result = $graph->createRequest("GET", "/me")->execute(); } catch(\Microsoft\Graph\Exception\GraphException $e) { echo 'Oops, something went wrong: ' . $e->getMessage(); }

Advanced usage

Want to level up? Try batch requests:

$batch = $graph->createCollectionRequest("POST", "/\$batch") ->addHeaders(["Content-Type" => "application/json"]) ->attachBody([ "requests" => [ ["id" => "1", "method" => "GET", "url" => "/me"], ["id" => "2", "method" => "GET", "url" => "/me/messages"], ] ]); $responses = $batch->execute();

Best practices and optimization

Remember to cache your access tokens and be mindful of rate limits. Your future self will thank you!

Conclusion

And there you have it! You're now equipped to build awesome Office 365 integrations with PHP. The Graph API is incredibly powerful, so don't be afraid to explore and experiment. Happy coding!