【发布时间】:2017-01-07 18:39:34
【问题描述】:
当我尝试访问phpmailer/get_outh_token.php 以获取refresh token 服务器返回时:
HTTP 错误 500
Client ID、Secret key 和 redirect Uri 是正确的,我已经在 Wordpress 中使用它。
我已经下载了最新版本的phpmailer,也用旧版本进行了测试,结果相同。
我找到原因了,就是这部分:
namespace League\OAuth2\Client\Provider;
当我删除它时,脚本当然会加载错误,因为
未加载提供程序命名空间。
网站正在使用PHP 7.
这是get_outh_token.php的完整代码,是原创的(当然只是凭证不同):
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
/**
* Get an OAuth2 token from Google.
* * Install this script on your server so that it's accessible
* as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
* e.g.: http://localhost/phpmail/get_oauth_token.php
* * Ensure dependencies are installed with 'composer install'
* * Set up an app in your Google developer console
* * Set the script address as the app's redirect URL
* If no refresh token is obtained when running this file, revoke access to your app
* using link: https://accounts.google.com/b/0/IssuedAuthSubTokens and run the script again.
* This script requires PHP 5.4 or later
* PHP Version 5.4
*/
namespace League\OAuth2\Client\Provider; //when i remove this line, than page load without 500, but with errors.
require 'vendor/autoload.php';
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;
session_start();
//If this automatic URL doesn't work, set it yourself manually
$redirectUri = 'https://www.secret.co/phpmailer/get_oauth_token.php';
//These details obtained are by setting up app in Google developer console.
$clientId = 'secret.apps.googleusercontent.com';
$clientSecret = 'secret';
class Google extends AbstractProvider
{
use BearerAuthorizationTrait;
const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'id';
/**
* @var string If set, this will be sent to google as the "access_type" parameter.
* @link https://developers.google.com/accounts/docs/OAuth2WebServer#offline
*/
protected $accessType;
/**
* @var string If set, this will be sent to google as the "hd" parameter.
* @link https://developers.google.com/accounts/docs/OAuth2Login#hd-param
*/
protected $hostedDomain;
/**
* @var string If set, this will be sent to google as the "scope" parameter.
* @link https://developers.google.com/gmail/api/auth/scopes
*/
protected $scope;
public function getBaseAuthorizationUrl()
{
return 'https://accounts.google.com/o/oauth2/auth';
}
public function getBaseAccessTokenUrl(array $params)
{
return 'https://accounts.google.com/o/oauth2/token';
}
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return ' ';
}
protected function getAuthorizationParameters(array $options)
{
if (is_array($this->scope)) {
$separator = $this->getScopeSeparator();
$this->scope = implode($separator, $this->scope);
}
$params = array_merge(
parent::getAuthorizationParameters($options),
array_filter([
'hd' => $this->hostedDomain,
'access_type' => $this->accessType,
'scope' => $this->scope,
// if the user is logged in with more than one account ask which one to use for the login!
'authuser' => '-1'
])
);
return $params;
}
protected function getDefaultScopes()
{
return [
'email',
'openid',
'profile',
];
}
protected function getScopeSeparator()
{
return ' ';
}
protected function checkResponse(ResponseInterface $response, $data)
{
if (!empty($data['error'])) {
$code = 0;
$error = $data['error'];
if (is_array($error)) {
$code = $error['code'];
$error = $error['message'];
}
throw new IdentityProviderException($error, $code, $data);
}
}
protected function createResourceOwner(array $response, AccessToken $token)
{
return new GoogleUser($response);
}
}
//Set Redirect URI in Developer Console as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
$provider = new Google(
array(
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'scope' => array('https://mail.google.com/'),
'accessType' => 'offline'
)
);
if (!isset($_GET['code'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken(
'authorization_code',
array(
'code' => $_GET['code']
)
);
// Use this to get a new access token if the old one expires
echo 'Refresh Token: ' . $token->getRefreshToken();
}
【问题讨论】:
-
您应该删除
namespace行。没有必要。您的有状态变量也有不正确的值。看起来您复制并粘贴了此代码但没有阅读它。另外,您为什么要在文件顶部开始会话?您应该仅在发生某些事情后(即在函数中)才开始会话。 cmets 也无济于事,它们基本上与代码的作用相同...除了代码更易于阅读。 -
@Rafael 这是来自上一个 phpmailer 的原始 phpmailer get_oauth_token.php 文件,我只是将我的凭据粘贴到那里。
-
@Rafael 当我删除它时,我得到:致命错误:require(): Failed opening required 'vendor/autoload.php' (include_path='.:/usr/share/php:/ usr/share/pear') 在第 20 行的 /home/xx/zzazfhvsnt/public_html/phpmailer/get_oauth_token.php 中
-
@Rafael 我需要用 composer 安装 phpmailer 吗?
-
我不确定您的设置或您使用的框架。如果您不使用框架,而只是编写一个连接到 google 的简单邮件程序。我会使用
lusitanian/oauth和phpmailer/phpmailer。 oauth 库已经有一个谷歌实现。 Composer 也会为您处理自动加载。但这就是我会做的。
标签: php gmail phpmailer http-status-code-500