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!
Before we jump in, make sure you've got:
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';
Now, let's get our app registered in Azure AD:
Keep these handy – we'll need them soon!
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;
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();
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(); }
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();
Remember to cache your access tokens and be mindful of rate limits. Your future self will thank you!
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!