Yan*_*eld 5 php cron crontab google-api-php-client
我正在使用Google API客户端来阅读Gmail中的电子邮件.现在我想添加一个Cronjob,每5分钟读一次邮件.
使用Google API客户端的问题是,它需要允许用户首先点击授权链接并允许用户使用Google API客户端.
我有一个类Inbox,其初始化函数初始化了Google API客户端.但是cronjob不起作用,因为我必须获得access_token.
public function initialize() {
$configuration = Configuration::getConfiguration('class_Inbox');
// Creates the Google Client
$this->client = new Google_Client();
$this->client->setApplicationName('Tiptsernetwork');
$this->client->setClientId($configuration['clientId']);
$this->client->setClientSecret($configuration['clientSecret']);
$this->client->setRedirectUri('http://www.tipsternetwork.nl/cronjob/authenticate');
$this->client->addScope('https://mail.google.com/');
$this->client->setApprovalPrompt('force');
$this->client->setAccessType('offline');
// Creates the Google Gmail Service
$this->service = new Google_Service_Gmail($this->client);
// Authenticates the user.
if (isset($_GET['code'])) {
$this->authenticate($_GET['code']);
}
// Check if we have an access token in the session
if (isset($_SESSION['access_token'])) {
$this->client->setAccessToken($_SESSION['access_token']);
} else {
$loginUrl = $this->client->createAuthUrl();
echo '<a href="'.$loginUrl.'">Click Here</a>';
}
// If the token is expired it used the refresh token to generate a new Access Token
if($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($configuration['refreshToken']);
}
}
public function authenticate($code) {
// Creates and sets the Google Authorization Code
$this->client->authenticate($code);
$_SESSION['access_token'] = $this->client->getAccessToken();
$this->client->refreshToken($configuration['refreshToken']);
// Redirect the user back after authorizaton
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($url, FILTER_VALIDATE_URL));
}
Run Code Online (Sandbox Code Playgroud)
你们知道如何使用刷新令牌修复它吗?我不能让它工作,我没有想法.
如果我正在访问该URL并单击"单击此处"并允许它成功运行但不能使用Cronjob,因为我无法单击"单击此处"URL ...
我希望你们能理解它并且可以帮助我:).
亲切的问候,
Yanick
这个答案更像是关于如何使用 O-Auth2 Flow的一般方法,因为我不久前遇到了类似的问题。我希望它会有所帮助。
一个可能的问题(在理解 OAuth 的正确使用方面)是您将其force用作批准提示。为什么你强迫用户在他已经这样做的情况下给予许可?
当用户针对您的后端进行身份验证时,系统会询问他是否要向您的应用程序授予scope. 您的应用程序第一次获得此权限(通过用户单击“同意”按钮)时,您的脚本将从谷歌获得一个access_tokenand refresh_token。
将access_token用于与帐户验证用户的访问谷歌的API。如果您想在没有用户在场的情况下访问 google API,您应该将其存储在服务器上的某个位置(所谓的offline-access)。使用此令牌,您可以以用户的名义执行任何操作(仅限于定义的范围)。它会在 1 小时左右后失效。在整个时间(1 小时)内,您可以使用此令牌而无需用户在场!
在refresh_token当需要access_tokenwents这一段时间后失效。只有那时。你只得到refresh_token 一次,它永远不会改变。这是非常重要的数据,应该安全存储!
因此,如果您想在用户不在场的情况下访问 google API,则必须使用存储的access_token. 如果响应类似于token expired(我认为有一个错误代码 - 必须进行研究),那么您$client->refreshToken($refreshToken)使用存储在安全位置的刷新令牌进行调用。你会从中得到一个新的access_token。有了这个,access_token您可以做进一步的工作,而无需用户(再次)单击某处。
下次新的access_token无效时,您必须使用与refresh_token以前相同的方法,这就是为什么这refresh_token如此重要的原因。
我希望我能帮到你一点点。如果没有,请对此发表评论。
快乐编码
资源