Need help with Google admin SDK. I'm a newbie to google admin SDK. So I am stuck on its showing error while authorizing like:
{ error: "unauthorized_client", "error_description": "Client is unauthorized to retrieve access tokens using this method" }
Here is my code.
<?php
include_once '../vendor/autoload.php';
include_once "base.php";
session_start();
echo pageHeader("Service Account Access");
/************************************************
Make an API request authenticated with a service
account.
************************************************/
$client = new Google_Client();
$client->setAuthConfig('service_account.json');
$client->setApplicationName("automate user");
$client->setSubject('admin@******.org');
$client->setScopes(['https://www.googleapis.com/auth/admin.directory.user']);
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
//$auth_url = $client->createAuthUrl();
//header('Location: '.filter_var($auth_url, FILTER_SANITIZE_URL));
if(isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
if ($credentials_file = checkServiceAccountCredentialsFile()) {
// set the location manually
$client->setAuthConfig('client_secret1.json');
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS=service_account.json')) {
// use the application default credentials
$client->useApplicationDefaultCredentials();
} else {
echo missingServiceAccountDetailsWarning();
return;
}
$dir = new Google_Service_Directory($client);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();
//$results = $dir->users->get('********@****.com');
$name->setGivenName('*****');
$name->setFamilyName('*****');
$user->setName($name);
$user->setHashFunction('SHA-1');
$user->setPrimaryEmail('****@***');
$user->setpassword(hash('sha1','******'));
$user->setchangePasswordAtNextLogin(false);
$results = $dir->users->insert($user);
if($results) {
echo "New user : ".$results->primaryEmail."";
} else{
echo " User doesn't exist : ".$email;
}
}
else {
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
//file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
$redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. '/google/oauth.php';
header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
<?php pageFooter(__FILE__); ?>
1st time it works perfectly. After some days I run this code it displays error of unauthorized_client
. I don't know why this error shows. I already created domain-wide delegation service account. Please help and tell what i am doing wrong