How to get access token for microsoft graph api

In this article i will share with you how to get access token for microsoft graph api.

In this link you get the Tenand Id and secret Key Get the secret key and tenant Id.

Open the below link.

https://login.microsoftonline.com/ReplaceYourTenantId/oauth2/authorize?client_id=ReplaceYourClientId&response_type=code

And this will redirect on callback url and you will get the code in callback url.

$post_params = array(
    "grant_type" => "authorization_code",
    "client_id" => 'ReplaceYourClientId',
    "resource" => "https://graph.microsoft.com/",
    "client_secret" => 'ReplaceYourClientSecretKey',
    'code' => $_GET['code'],
);
$fullurl = "https://login.windows.net/f573035b-b3ff-45ac-84cb-3d73ac3647ac/oauth2/token?";
$curl = curl_init($fullurl);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("application/x-www-form-urlencoded"));
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
$arrResponse = json_decode($response);
$accessToken = $arrResponse->access_token;
$refreshToken = $arrResponse->refresh_token;

Please store the access token and refresh token in txt file or in database so you will get the refresh token from the above both token. I am storing this both token in my local database.

I hope it will help you.