我得到了 google api-php-client并且我无法登录,因为我总是收到错误:
[02-Nov-2017 15:30:52 Europe/Helsinki] ***START***
scripto\CustomException: [0: E_CUSTOM: Suppressed or Custom error] cURL error 6: Could not resolve host: www.googleapis.com (see http://curl.haxx.se/libcurl/c/libcurl-errors.html).
in /home/suexec-test/server/GuzzleHttp/Handler/CurlFactory.php on line 186
[Trace]:
#0 /home/suexec-test/server/ExceptionFactory.php(117): scripto\CustomException::buildFromException(Object(GuzzleHttp\Exception\ConnectException))
#1 [internal function]: scripto\ExceptionFactory::exception_handler(Object(GuzzleHttp\Exception\ConnectException))
#2 {main}
[Previous]:
scripto\CustomException: [0: E_CUSTOM: Suppressed or Custom error] cURL error 6: Could not resolve host: www.googleapis.com (see http://curl.haxx.se/libcurl/c/libcurl-errors.html).
in /home/suexec-test/server/GuzzleHttp/Handler/CurlFactory.php on line 186
[Trace]:
#0 /home/suexec-test/server/GuzzleHttp/Handler/CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
#1 /home/suexec-test/server/GuzzleHttp/Handler/CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#2 /home/suexec-test/server/GuzzleHttp/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#3 /home/suexec-test/server/GuzzleHttp/Handler/Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#4 /home/suexec-test/server/GuzzleHttp/Handler/Proxy.php(51): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#5 /home/suexec-test/server/GuzzleHttp/PrepareBodyMiddleware.php(66): GuzzleHttp\Handler\Proxy::GuzzleHttp\Handler\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#6 /home/suexec-test/server/GuzzleHttp/Middleware.php(30): GuzzleHttp\PrepareBodyMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#7 /home/suexec-test/server/GuzzleHttp/RedirectMiddleware.php(70): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#8 /home/suexec-test/server/GuzzleHttp/Middleware.php(57): GuzzleHttp\RedirectMiddleware->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#9 /home/suexec-test/server/GuzzleHttp/HandlerStack.php(67): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Request), Array)
#10 /home/suexec-test/server/GuzzleHttp/Client.php(281): GuzzleHttp\HandlerStack->__invoke(Object(GuzzleHttp\Psr7\Request), Array)
#11 /home/suexec-test/server/GuzzleHttp/Client.php(103): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array)
#12 /home/suexec-test/server/GuzzleHttp/Client.php(110): GuzzleHttp\Client->sendAsync(Object(GuzzleHttp\Psr7\Request), Array)
#13 /home/suexec-test/server/Google/Auth/HttpHandler/Guzzle6HttpHandler.php(34): GuzzleHttp\Client->send(Object(GuzzleHttp\Psr7\Request), Array)
#14 /home/suexec-test/server/Google/Auth/OAuth2.php(501): Google\Auth\HttpHandler\Guzzle6HttpHandler->__invoke(Object(GuzzleHttp\Psr7\Request))
#15 /home/suexec-test/server/Google/Google_Client.php(195): Google\Auth\OAuth2->fetchAuthToken(Object(Google\Auth\HttpHandler\Guzzle6HttpHandler))
#16 /home/suexec-test/server/Google/Google_Client.php(174): Google_Client->fetchAccessTokenWithAuthCode('4/4BhYCtvi43DGf...')
#17 /home/suexec-test/tests/testGoogle-4.php(56): Google_Client->authenticate('4/4BhYCtvi43DGf...')
#18 /home/suexec-test/server/Dispatcher.php(96): require_once('/home/suexec-te...')
#19 /home/suexec-test/server/Controller.php(68): scripto\Dispatcher->run()
#20 /home/suexec-test/public_html/index.php(7): scripto\Controller->run()
#21 {main}
***END***
我创建了一个网络应用程序,
问题是即使加载了所有类,我的代码也无法通过$client->authenticate($_GET['code']);
。
我为你准备了一个测试文件:你应该调用http://localhost/auth/google/login
同http://localhost/auth/google/logout
一个文件来观察抛出的错误。
测试文件是对这篇文章的修改:
<?php
if (\session_status() != PHP_SESSION_ACTIVE) {
Session_start();
}
$whoami = $_SERVER['REQUEST_URI'];
$login = $logout = false;
if (\strpos($whoami, '/login') !== false)
$login = true;
if (\strpos($whoami, '/logout') !== false)
$logout = true;
/*
* Configuration and setup Google SDK
*/
$appId = '519650546062-XXXXXX.apps.googleusercontent.com';
$appSecret = 'XXXXXXX';
// CALLED BY US & GOOGLE!
$loginUri = 'http://localhost/auth/google/login';
// CALLED BY US!
$logoutUri = 'http://localhost/auth/google/logout';
$access = 'online';
$scopes = "openid profile email";
$incremental_scopes = false; // what if for true?
//$state = 123;
//Create Google Client
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($appId);
$client->setClientSecret($appSecret);
$client->setRedirectUri($loginUri);
$client->setAccessType($access);
$client->setIncludeGrantedScopes($incremental_scopes);
$client->addScope($scopes);
//$client->setState($state);
//Send Client Request?
$objOAuthService = new Google_Service_Oauth2($client);
//CALLED BY US
if ($logout) {
unset($_SESSION['access_token']);
$client->revokeToken();
// Back to login!
header('Location: ' . filter_var($loginUri, FILTER_SANITIZE_URL));
}
//CALLED BY GOOGLE
if (isset($_GET['code'])) {
error_log('1....I\'M GOING TO BREAK...');
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
// Back to this file!
header('Location: ' . filter_var($loginUri, FILTER_SANITIZE_URL));
}
//CALLED BY US 2ND TIME (after previous header)
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
error_log('2....session access token='.$_SESSION['access_token']);
$client->setAccessToken($_SESSION['access_token']);
}
//ONLY DURING 2ND CALL (from previous if...)
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
if(!empty($userData)) {
// do sth with data!
}
$_SESSION['access_token'] = $client->getAccessToken();
error_log('3.....user data:'.print_r($userData, true));
} else {
$authUrl = $client->createAuthUrl();
}
$out = <<<EOT
<html>
<head>
<title>Google OAuth v.2.0 Login test</title>
</head>
<body>
EOT;
if (isset($authUrl)) {
$d = \urldecode($authUrl);
$out .= <<<EOT
<p>decoded authUrl = '{$d}'</p>
EOT;
}
$out .= <<<EOT
<h2>PHP Google OAuth 2.0 Login</h2>
EOT;
if (isset($authUrl)) {
$out .= <<<EOT
<p><a href='{$authUrl}'>Login with Google API</a></p>
EOT;
} else {
$out .= <<<EOT
<p>Welcome <a href="{$userData['link']}">{$userData['name']}</a>.</p>
<p>Your email: {$userData['email']}</p>
<p><a href={$logoutUri}>Logout</a></p>
EOT;
}
$e = \nl2br(\htmlspecialchars(\print_r($_SESSION, true)));
$out .= <<<EOT
<p><h3>SESSION:</h3></p>
<p>{$e}</p>
</body>
</html>
EOT;
echo $out;
代码在error_log('1....I\'M GOING TO BREAK...');
. 有趣的是,我设法用curl绕过了整个库并获得了具有以下形式的访问令牌:
[02-Nov-2017 14:06:38 Europe/Helsinki] Array
(
[access_token] => ya29.Glv3B...xlSKIL_N67PE4...PYGDjZo-jD8v...ITFTnU
[expires_in] => 2017-11-02 15:06:37
[id_token] => eyJhbGciOiJImt...tlf_-Y1hXoCVSp...Ve_bK8F-jTCt...zg
[token_type] => Bearer
)
但我找不到端点获取用户数据:像这样[偶尔]中断[我数了多达 90% 的失败]
public function userinfo() {
$access_token = $this->access['access_token'];
$url = 'https://www.googleapis.com/plus/v1/people/me';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code != 200)
throw new \ErrorException(__CLASS__ . "::userinfo() is called but failed to get user information!", 0, 1);
$this->data = $data;
}
感谢这篇出色的帖子。
知道官方 php 库有什么问题吗?我在控制台中缺少什么吗?
谢谢你。