简体   繁体   中英

PHP Unable to update user password through Google Directory API 2.0

We followed the following steps from this url ( https://developers.google.com/admin-sdk/directory/v1/quickstart/php ).

Listing users is working!

But While updating the new password for a given userKey, We are getting following error:

PHP Catchable fatal error: Argument 2 passed to Google_Service_Directory_Resource_Users::update() must be an instance of Google_Service_Directory_User, none given, called in /var/www/passwords_change/danish/quickstart.php on line 85 and defined in /var/www/passwords_change/danish/vendor/google/apiclient-services/src/Google/Service/Directory/Resource/Users.php on line 162

I have attached my code.

Note: We do have a valid credentials...!

<?php
require_once __DIR__ . '/vendor/autoload.php';


define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '/home/ramesh/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
$optParams = array(
  'userKey' => 'danish@XXXX.in',
);

$password = crypt ( "Password", $salt="IamSecretkey" );
$obj = new Google_Service_Directory_User;

try{
    $results = $service->users->update($optParams );
} catch(Error $ex) {
print_r($ex->getMessage());
}
echo "<pre>";
print_r($results);
exit;


/*
// Print the first 10 users in the domain.
$optParams = array(
  'customer' => 'my_customer',
  'maxResults' => 10,
  'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);

if (count($results->getUsers()) == 0) {
  print "No users found.\n";
} else {
  print "Users:\n";
  foreach ($results->getUsers() as $user) {
    printf("%s (%s)\n", $user->getPrimaryEmail(),
        $user->getName()->getFullName());
  }
}
*/

You almost got it right. The part where you went wrong is creating the user resource object and calling the API. The logic should be similar to this:

$service = new Google_Service_Directory($client);

$password = crypt ( "Password", $salt="IamSecretkey" );

$userObj = new Google_Service_Directory_User(
    array(
        'password' =>  $password
    )
);

try{
    $results = $service->users->update("danish@XXXX.in", $userObj );
} catch(Error $ex) {
print_r($ex->getMessage());
}

echo "<pre>";
print_r($results);

Please refer to the official documentation for a better and more detailed explanation. I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM