如何使用PHP在服务器上实现OAuth 2.0,以便为我们的域创建/更新电子邮件帐户。大多数示例使用$ CLIENT_SECRET,我没有,可能是它的旧方法或其他东西。这是我写的代码:
createEmail('azzozhsn@domain', 'password', 'Azzoz', 'Al-hasani');
function createEmail($username, $password, $firstName, $lastName)
{
$p12key = file_get_contents('file.p12');
$APIkey = 'XXXXXXXXXXXXX';
$clientId = 'YYYYYYYYYYcipbi.apps.googleusercontent.com';
$emailAddress = 'ZZZZZZZZZZ@developer.gserviceaccount.com';
$certFingerprints = 'WWWWWWWWWWW';
$user2impersonate = 'admin@domain';
require_once('Google/autoload.php');
$scopes = array('https://www.googleapis.com/auth/admin.directory.user');
$cred = new Google_Auth_AssertionCredentials(
$clientId,
$scopes,
$p12key
);
$cred->sub = $user2impersonate;
$client = new Google_Client();
$client->setClientId($clientId);
$client->addScope("https://www.googleapis.com/auth/admin.directory.user");
$client->setAssertionCredentials($cred);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();
$name->setFamilyName($lastName);
$name->setGivenName($firstName);
$user->setName($name);
$user->setHashFunction("MD5");
$user->setPrimaryEmail($username);
$user->setPassword(hash("md5", $password));
$user->setExternalIds(array("value"=>28790,"type"=>"custom","customType"=>"EmployeeID"));
$service = new Google_Service_Directory($client);
$result = $service->users->insert($user);
return $result;
}
然后通过一些调试我发现了这条消息:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
我知道问题在于身份验证,但我不知道该怎么做,我发现的大多数代码都使用了我没有的client_secret。它像旧方法或其他东西......
答案 0 :(得分:1)
整夜工作后我得到了答案。 首先,我想我在$ clientId和$ emailAddress之间混淆然后我需要获得$ client-> getAccessToken()并在它到期时刷新它。
$key = file_get_contents(KEY_FILE);
$client = new Google_Client();
$client->setApplicationName('GmailAdmin');
$cred = new Google_Auth_AssertionCredentials(
$emailAddress,
array('https://www.googleapis.com/auth/admin.directory.user'),
$key
);
$cred->sub = user2impersonate;
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}