2015-11-24 269 views
5

我正在使用Google API客户端从Gmail中读取电子邮件。现在我想添加一个Cronjob,以便每5分钟阅读一次邮件。Google API客户端和Cronjob

使用Google API客户端的问题在于,它需要允许用户先单击授权链接并允许用户使用Google API客户端。

我有一个具有函数初始化类的收件箱,用于初始化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)); 
} 

你们是否知道如何使用刷新令牌或任何解决它?我无法做到这一点,并且我没有想法。

如果我访问的网址,然后点击“点击这里”,并允许其它的作品成功地但不是一个cronjob,因为我不能点击“点击这里”网址...

希望你们了解它并可以帮助我:)。

亲切的问候,
Yanick

回答

3

这个答案是更多的一般方法如何使用O型Auth2流量,因为我前一段时间面临着类似的问题。我希望这会有所帮助。

一个可能的问题(在了解正确使用OAuth时)是您使用force作为批准提示。你为什么强迫用户在他已经做的时候给予许可?

当用户对您的后端进行身份验证时,系统会询问他是否希望为您的应用程序授予在scope中定义的操作权限。当您的应用第一次获得此权限时(用户点击“同意”按钮),您的脚本将从谷歌获得access_tokenrefresh_token

access_token用于使用该认证用户的帐户访问Google-API。如果你想访问google API而不需要用户在场(所谓的离线访问),你应该将其存储在服务器的某个地方。使用此令牌,您可以以用户的名义进行任何操作(仅限于定义的范围)。它会在1小时左右后失效。在整个(1小时)的时间内,您可以使用此令牌而不需要用户在场!

access_token在这段时间后无效,需要refresh_token。只有那样。你只能得到refresh_token一次它永远不会改变。这是非常重要的数据,应该安全存储!

所以,如果你想访问谷歌API没有用户的存在,你必须使用存储的access_token API调用。如果响应类似token expired(我认为有一个错误代码 - 必须进行研究),那么您可以拨打$client->refreshToken($refreshToken)并将刷新标记存储在安全的地方。你会从中得到一个新的access_token。有了这个access_token你可以做更多的工作,而不需要用户再次点击某个地方。

下一次新的access_token wents无效,你必须像以前一样使用相同的refresh_token,这就是为什么这refresh_token如此重要的原因。

我希望我可以帮你一点点。如果没有,请对此评论。

快乐编码

资源