【问题标题】:How can I implement GMail OAuth 2.0 on server using PHP?如何使用 PHP 在服务器上实现 GMail OAuth 2.0?
【发布时间】:2015-08-07 07:49:15
【问题描述】:

如何使用 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 女巫。它喜欢旧方法或其他东西......

【问题讨论】:

  • 我认为您可以找到此链接developers.google.com/console/help/new/#generatingoauth2 有助于为您的 API 创建 client_secret。如果您使用的是 Auth 2.0,那么您需要根据该链接创建客户端 ID、客户端密码。
  • 是的,当我创建“网络应用程序”帐户时,它要求我登录以完成该过程。我不想那样。当我添加我想要的“服务帐户”女巫时。我不知道如何实现它。

标签: php oauth google-oauth gmail-api


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 2016-04-16
    • 2021-06-22
    • 2017-10-28
    • 2012-11-18
    • 2023-03-19
    • 2020-12-30
    • 2020-10-29
    • 2013-08-26
    相关资源
    最近更新 更多