Back

Step by Step Guide to Building a Microsoft Graph API Integration in PHP

Aug 7, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Microsoft Graph API? If you're looking to supercharge your PHP applications with Microsoft's powerful ecosystem, 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've got this, right?)
  • Composer installed (because who wants to manage dependencies manually?)
  • A Microsoft Azure account (if you don't have one, now's the time!)
  • An application registered in Azure AD (we'll assume you've tackled this already)

Installation

First things first, let's get that package installed:

composer require microsoft/microsoft-graph

Easy peasy, right?

Authentication

Now, let's get you authenticated:

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;

Setting up the Graph Client

With our access token in hand, let's set up the Graph client:

$graph = new Graph(); $graph->setAccessToken($accessToken);

Making API Calls

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

Retrieving User Information

$user = $graph->createRequest("GET", "/users/[email protected]") ->setReturnType(Model\User::class) ->execute(); echo $user->getDisplayName();

Sending an Email

$message = new Model\Message(); $message->setSubject("Hello from Graph API!"); $message->setBody(new Model\ItemBody(["contentType" => "Text", "content" => "This is the email body"])); $message->setToRecipients([ new Model\Recipient([ "emailAddress" => [ "address" => "[email protected]" ] ]) ]); $graph->createRequest("POST", "/users/[email protected]/sendMail") ->attachBody(["message" => $message]) ->execute();

Handling Responses

Most responses will come back as JSON. PHP's got your back here:

$response = $graph->createRequest("GET", "/me") ->execute(); $decodedBody = json_decode($response->getBody(), true);

For error handling, wrap your requests in a try-catch block:

try { $response = $graph->createRequest("GET", "/me")->execute(); } catch(\GuzzleHttp\Exception\ClientException $e) { $errorBody = json_decode($e->getResponse()->getBody(), true); // Handle the error }

Advanced Usage

Batch Requests

Need to make multiple requests? Batch 'em up:

$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();

Change Notifications (Webhooks)

Want to stay updated? Set up a webhook:

$subscription = new Model\Subscription(); $subscription->setChangeType("created,updated"); $subscription->setNotificationUrl("https://yourapp.com/notifications"); $subscription->setResource("/users/{user-id}/messages"); $subscription->setExpirationDateTime(new \DateTime("+1 week")); $newSubscription = $graph->createRequest("POST", "/subscriptions") ->attachBody($subscription) ->setReturnType(Model\Subscription::class) ->execute();

Best Practices

  • Mind the rate limits! Microsoft's got 'em, so be nice.
  • Cache when you can. Your users (and Microsoft) will thank you.

Conclusion

And there you have it! You're now armed and dangerous with Microsoft Graph API integration in PHP. Remember, this is just scratching the surface - there's a whole world of possibilities out there. Keep exploring, keep coding, and most importantly, have fun!

Need more? Check out the official Microsoft Graph documentation and the PHP SDK on GitHub.

Now go build something awesome!