Outlook Calendar: Refresh a Delegated Access Token
See more Outlook Calendar Examples
Refresh the Graph token obtained by the public desktop PKCE example, without a client secret or browser. Use the same client ID and authority. This works after a user has signed in and consented; it is not app-only authentication. A refresh token is not permanent: invalid_grant or an interaction requirement means the user must authorize again.
Form parameters are encoded by Chilkat. HTTP/JSON/token-validation failures leave the old cache untouched. Save a new refresh token when one is returned; retain the previous one if the field is absent. A private backup protects against a replacement-write failure; production code should replace credentials atomically, serialize refreshes per account, and remove obsolete protected backups according to its retention policy. No credentials are printed.
The cache is qa_data/tokens/outlookCalendar.json. Refresh before its acquired-time plus expires_in lifetime has elapsed. Keep each cache associated with its original app and account.
HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.
Chilkat CkPhp Downloads
<?php
include("chilkat.php");
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = false;
$token = new CkJsonObject();
$token->put_Strict(true);
$success = $token->LoadFile('qa_data/tokens/outlookCalendar.json');
if ($success != true) {
print 'Read the private token cache or authorize again.' . "\n";
exit;
}
if (($token->JsonTypeOf('refresh_token') != 1) or ($token->StringOfEquals('refresh_token','',true) == true)) {
print 'Expected a nonempty refresh_token in the JSON.' . "\n";
exit;
}
$clientId = 'YOUR_APPLICATION_CLIENT_ID';
// Use the same app and authority as the original authorization.
$tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$http = new CkHttp();
$http->put_RequireSslCertVerify(true);
$http->put_FollowRedirects(false);
$http->put_ConnectTimeout(20);
$http->put_ReadTimeout(30);
$req = new CkHttpRequest();
$req->put_HttpVerb('POST');
$req->put_ContentType('application/x-www-form-urlencoded');
$req->AddParam('client_id',$clientId);
$req->AddParam('grant_type','refresh_token');
$req->AddParam('refresh_token',$token->stringOf('refresh_token'));
// Omitting scope retains the original grant instead of requesting additional permissions.
$resp = new CkHttpResponse();
$result = new CkJsonObject();
$result->put_Strict(true);
$success = $http->HttpReq($tokenUrl,$req,$resp);
// A false result can still include an HTTP error response.
if (($success != true) and ($resp->get_StatusCode() == 0)) {
print 'No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.' . "\n";
exit;
}
if ($resp->get_StatusCode() != 200) {
print 'Unexpected HTTP status: ' . $resp->get_StatusCode() . "\n";
print 'Request ID: ' . $resp->getHeaderField('request-id') . "\n";
if ($resp->get_StatusCode() == 429) {
print 'Retry-After: ' . $resp->getHeaderField('Retry-After') . "\n";
}
if ($resp->get_StatusCode() == 401) {
print 'Refresh the Graph access token or authorize again.' . "\n";
}
exit;
}
$success = $result->Load($resp->bodyStr());
if ($success != true) {
print 'Expected a well-formed JSON response.' . "\n";
exit;
}
if (($result->JsonTypeOf('access_token') != 1) or ($result->StringOfEquals('access_token','',true) == true)) {
print 'Expected a nonempty access_token in the JSON.' . "\n";
exit;
}
if (($result->JsonTypeOf('expires_in') != 2) or ($result->IntOf('expires_in') <= 0)) {
print 'Missing token lifetime; old cache unchanged.' . "\n";
exit;
}
if ($result->JsonTypeOf('refresh_token') == -1) {
$result->UpdateString('refresh_token',$token->stringOf('refresh_token'));
}
else {
if (($result->JsonTypeOf('refresh_token') != 1) or ($result->StringOfEquals('refresh_token','',true) == true)) {
print 'Expected a nonempty refresh_token in the JSON.' . "\n";
exit;
}
}
$obtained = new CkDateTime();
$success = $obtained->SetFromCurrentSystemTime();
if ($success != true) {
print 'Could not timestamp the refreshed token.' . "\n";
exit;
}
$result->UpdateString('obtained_at',$obtained->getAsTimestamp(false));
// Keep a valid previous cache for recovery if the replacement write fails.
$success = $token->WriteFile('qa_data/tokens/outlookCalendar.json.bak');
if ($success != true) {
print 'Could not back up the old cache; no replacement attempted.' . "\n";
exit;
}
$success = $result->WriteFile('qa_data/tokens/outlookCalendar.json');
if ($success != true) {
print 'Could not save the new token; recover the previous cache from the private .bak file.' . "\n";
exit;
}
print 'Refreshed the calendar token cache.' . "\n";
?>