P粉4267805152023-09-06 00:58:31
Use OAuth 2.0 Authorization
to authenticate the user and obtain an access token. And use it to call Microsoft Graph API
to retrieve the user's email.
For your question, the login page may appear when you are not logged in. To resolve this issue, you need to use OAuth 2.0 client credentials
instead of the authorization code. p>
Sample code to obtain an access token using client credentials.
$tenantId = 'your-tenant-id';
$client_id = 'your-client-id';
$client_secret = 'your-client-secret';
$resource = 'https://graph.microsoft.com';
$tokenEndpoint = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token';
$data = array(
'grant_type' => 'client_credentials',
'client_id' => $client_id,
'client_secret' => $client_secret,
'resource' => $resource
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($tokenEndpoint, false, $context);
$token = json_decode($result)->access_token;
After you obtain the access token, you can use it to call the Microsoft Graph API
and retrieve the user's email.
Sample code to retrieve user email.
php $graphApiEndpoint = 'https://graph.microsoft.com/v1.0/me/messages'; $options = array( 'http' => array( 'header' => "Authorization: Bearer $token\r\n" . "Content-type: application/json\r\n", 'method' => 'GET' ) ); $context = stream_context_create($options); $result = file_get_contents($graphApiEndpoint, false, $context); $messages = json_decode($result)->value;
For more information, see MSDoc1 and MSDoc2.