How can I access Microsoft-graph-api with access token in PHP?
To access Microsoft Graph API using an access token in PHP, you need to use a library that supports making HTTP requests and handling OAuth2 authentication. One popular library for this purpose is "GuzzleHttp". Here's a step-by-step guide on how to use it:
- Install GuzzleHttp using Composer:
First, you need to install GuzzleHttp using Composer, which is a dependency management tool for PHP. If you don't have Composer installed, download it from https://getcomposer.org/ and follow the installation instructions.
Once you have Composer installed, open a terminal or command prompt and run the following command to install GuzzleHttp:
composer require guzzlehttp/guzzle
- Create a new PHP file:
Create a new PHP file, for example, msgraph.php
, and include the GuzzleHttp library at the beginning of the file:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
- Define your access token:
Replace <access_token>
with your actual access token:
$accessToken = "<access_token>";
- Create a GuzzleHttp client:
Create a new instance of the GuzzleHttp client and set the default headers, including the access token:
$client = new Client([
'base_uri' => 'https://graph.microsoft.com/v1.0/',
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json'
]
]);
- Make API requests:
Now you can use the client to make API requests. For example, to get the user's profile information, use the following code:
try {
$response = $client->get('me');
$data = json_decode($response->getBody(), true);
print_r($data);
} catch (RequestException $e) {
echo 'Error: ' . $e->getMessage();
}
Replace the print_r($data)
line with the code to process the response as needed.
- Save and run the script:
Save the file and run it using a PHP interpreter, such as the command-line version or a web server like Apache or Nginx. The script should now make a request to the Microsoft Graph API using the provided access token.
Keep in mind that this example is just a starting point, and you may need to modify it to fit your specific use case. For more information on GuzzleHttp and Microsoft Graph API, refer to their respective documentation:
- GuzzleHttp: https://docs.guzzlephp.org/
- Microsoft Graph API: https://docs.microsoft.com/en-us/graph/api/api-overview?view=graph-rest-1.0