【发布时间】:2016-02-26 15:08:43
【问题描述】:
我正在使用 Google API 客户端阅读来自 Gmail 的电子邮件。现在我想添加一个 Cronjob,让它每 5 分钟读取一次邮件。
使用Google API Client的问题是需要允许用户先点击授权链接,并允许用户使用Google API Client。
我有一个类收件箱,其中包含一个初始化 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));
}
你们知道如何使用刷新令牌或其他什么来修复它吗?我无法让它工作,而且我没有想法。
如果我正在访问 URL 并单击“单击此处”并允许它成功运行,但不能使用 Cronjob,因为我无法单击“单击此处” URL...
我希望你们理解它并可以帮助我:)。
亲切的问候,
亚尼克
【问题讨论】:
标签: php cron crontab google-api-php-client