Search code examples
phpazureazure-active-directorymicrosoft-graph-api

Microsoft Graph API Get my Events api not working


on miscrosoft graph api they provide v1.0 and v2.0

with v1.0 we used code as they provided on doc, but it does not work and we are not able to access token.

and everywhere they just mentioned all apis that are in v1.0 there is no example of adding calendar event with v2.0.

infect i have used their postman collection and used that one for generating token.

its generated token successfully.

but when i used api that get my calendar events its returns me

{
    "error": {
        "code": "OrganizationFromTenantGuidNotFound",
        "message": "The tenant for tenant guid 'f3fd3de8-d438-4470-b351-5a7dde989db8' does not exist.",
        "innerError": {
            "oAuthEventOperationId": "10aaa007-edfb-4d36-ab46-d68e51af1e28",
            "oAuthEventcV": "bFc6s7xHD3sZPpSDf6Ve5Q.1.1",
            "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant",
            "requestId": "41ca535c-2339-4e95-8915-2f1cdda88231",
            "date": "2024-06-10T06:12:02"
        }
    }
}

i have searched lots of example and documents but i don't get any solution.

at the end i found that token which i have generated is correct one but when i call any calendar addd or get event api its gives me this error.

i have added all full permission to the app for the calendars.

It should add event to calendar

some of dynamic value we have to added those variables.

$url="https://login.microsoftonline.com/$row_comp->ol_tenant_id/oauth2/authorize?client_id=$row_comp->ol_client_id&response_type=code&redirect_uri=$url_auth&response_mode=query&scope=api://$row_comp->ol_client_id/Calendars.ReadWrite%20offline_access&state=12345";

above one is the url.

and on auth url i have added curl request

 $url = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token";

$data = [
    'client_id' => $clientId,
    'scope' => "Calendars.ReadBasic openid profile offline_access",
    'code' => $authorizationCode,
    'redirect_uri' => $redirectUri,
    'grant_type' => 'authorization_code',
    'client_secret' => $clientSecret
];

$options = [
    CURLOPT_URL => $url,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($data),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/x-www-form-urlencoded'
    ],
];

$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if(curl_errno($ch)) {
    $error_msg='1 :. Error:' . curl_error($ch);
}
curl_close($ch);






$responseData = json_decode($response, true);
$full_object['first_call']=json_decode($response);
if (isset($responseData['error'])) {
    $error_msg= "1 :. Error: " . $responseData['error_description'] . "\n";
} else {
    if(isset($responseData['refresh_token']))
    {
        $ol_access_token_old=$responseData['access_token'];
        $ol_refresh_token_old=$responseData['refresh_token'];
        $accessToken = $responseData['access_token'];
        $refreshToken = $responseData['refresh_token'];
    }
}

And then call refresh token

if($refreshToken!="")
{
    $url = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token";
    $params=[];
    $params['url']=$url;
    $params['clientId']=$clientId;
    $params['refreshToken']=$refreshToken;
    $params['clientSecret']=$clientSecret;
    $res_data=RefreshToeknOutlook($params);

    

        
                $full_object['second_call']=$res_data['full_res'];
                $error_msg=$res_data['error_msg'];
            
                $ol_access_token_new=$res_data['ol_access_token_new'];
                $ol_refresh_token_new=$res_data['ol_refresh_token_new'];
                $ol_token_expiry_date=$res_data['ol_token_expiry_date'];

        if($ol_access_token_new!="" && $error_msg=="")
        {
            $dt=date("Y-m-d H:i:s");
            $ol_token_expiry_date=date("Y-m-d H:i:s",strtotime($dt." +".$ol_token_expiry_date." seconds"));
            $sql_update="update tbl_admin set ol_authorization_code='".$db->real_escape_string($code)."'";
            $sql_update.=",ol_access_token_old='".$db->real_escape_string($ol_access_token_old)."'";
            $sql_update.=",ol_refresh_token_old='".$db->real_escape_string($ol_refresh_token_old)."'";
            $sql_update.=",ol_access_token_new='".$db->real_escape_string($ol_access_token_new)."'";
            $sql_update.=",ol_refresh_token_new='".$db->real_escape_string($ol_refresh_token_new)."'";
            $sql_update.=",ol_token_expiry_date='".$db->real_escape_string($ol_token_expiry_date)."'";
            $sql_update.=",ol_log_text='".$db->real_escape_string(json_encode($full_object))."'";
            $sql_update.=" where id='".$row_comp->id."'";
            
            $db->query($sql_update);
            
            
            
            
            
        }
}

The above function returns token. and using that i am calling

https://graph.microsoft.com/v1.0/me/events

but it returns

{
"error": {
    "code": "OrganizationFromTenantGuidNotFound",
    "message": "The tenant for tenant guid 'f3fd3de8-d438-4470-b351-5a7dde989db8' does not exist.",
    "innerError": {
        "oAuthEventOperationId": "10aaa007-edfb-4d36-ab46-d68e51af1e28",
        "oAuthEventcV": "bFc6s7xHD3sZPpSDf6Ve5Q.1.1",
        "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant",
        "requestId": "41ca535c-2339-4e95-8915-2f1cdda88231",
        "date": "2024-06-10T06:12:02"
    }
}

}


Solution

  • The error occurred as you registered application with supported account type as "Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant)" that won't work with personal Microsoft accounts.

    To resolve the error, you need to create app registration with below account type that supports users to login with personal Microsoft accounts:

    enter image description here

    Now, I added Calendars.Read permission of Delegated type in my application as below:

    enter image description here

    To get code value, I ran below authorization request with /common endpoint in Incognito browser that asked user to login like this:

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize
    ?client_id=appId
    &response_type=code
    &redirect_uri=https://jwt.ms
    &response_mode=query
    &scope=Calendars.Read
    &state=12345
    

    enter image description here

    When you enter personal Microsoft account like outlook mail, it will take you to login.live.com page:

    enter image description here

    After successful authentication, it will give code value in address bar starts with 'M.C51' for outlook accounts like this:

    enter image description here

    Now, I used this code to get access token using authorization code flow via Postman with below parameters and got response like this:

    POST https://login.microsoftonline.com/common/oauth2/v2.0/token
    grant_type:authorization_code
    client_id:appId
    client_secret:secret
    scope:Calendars.Read
    code:code
    redirect_uri:https://jwt.ms
    

    Response:

    enter image description here

    When I used this token to call API, I got the response successfully with events like this:

    GET https://graph.microsoft.com/v1.0/me/events
    

    Response:

    enter image description here