Google API客户端和Cronjob [英] Google API Client and Cronjob

查看:168
本文介绍了Google API客户端和Cronjob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Google API客户端从Gmail读取电子邮件。现在我想添加一个Cronjob,所以它每5分钟读取邮件。



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



我有一个类Inbox,带有初始化Google API客户端的函数初始化。但是cronjob不工作,因为我得到一个access_token。

  public function initialize(){
$ configuration = Configuration :: getConfiguration('class_Inbox');

//创建Google客户端
$ 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');

//创建Google Gmail服务
$ this-> service = new Google_Service_Gmail($ this-> client);

//验证用户。
if(isset($ _ GET ['code'])){
$ this-> authenticate($ _ GET ['code']);
}

//检查我们在会话中是否有访问令牌
if(isset($ _ SESSION ['access_token'])){
$ this- > client-> setAccessToken($ _ SESSION ['access_token']);
} else {
$ loginUrl = $ this-> client-> createAuthUrl();
echo'< a href ='。$ loginUrl。'>点击此处< / a>';
}

//如果令牌过期,它使用刷新令牌生成新的访问令牌
if($ this-> client-> isAccessTokenExpired()) {
$ this-> client-> refreshToken($ configuration ['refreshToken']);
}
}

public function authenticate($ code){
//创建并设置Google授权代码
$ this-> client- > authenticate($ code);
$ _SESSION ['access_token'] = $ this-> client-> getAccessToken();

$ this-> client-> refreshToken($ configuration ['refreshToken']);

//在授权
$ url ='http://'之后重定向用户。 $ _SERVER ['HTTP_HOST']。 $ _SERVER ['PHP_SELF'];
header('Location:'。filter_var($ url,FILTER_VALIDATE_URL));
}

你们知道如何使用刷新令牌我不能让它工作,我的想法。



如果我访问的URL,并单击点击这里,并允许它的工作成功,但不是与Cronjob,因为我不能点击点击这里URL ...



我希望你的人能理解它,并可以帮助我:)。



关心,

Yanick

解决方案

答案是更常见的方法在如何使用O-Auth2流,因为我面临一个类似的问题前一段时间。



一个可能的问题(理解正确使用OAuth)是使用 force 作为审批提示。你为什么强制用户在他已经执行过操作时授予权限?



当用户对你的后端进行自动化时,会询问他是否要向应用程序授予权限在 scope 中定义。第一次你的应用程序获得这个权限(通过用户单击同意 - 按钮)你的脚本会得到一个 access_token refresh_token 来自google。



access_token 用于访问Google-API验证用户。如果您希望在不让用户存在的情况下访问google API(因此称为离线访问),则应将其存储在服务器上的某个位置。使用此令牌,您可以在用户名中进行任何操作(仅限于定义的范围)。它将在1小时左右后无效。在整个时间(1小时)中,您可以使用此令牌,而不必让用户出现!



refresh_token access_token 在此时间段后失效时,需要c>。只有那时。您只能获得 refresh_token ONCE ,它永远不会改变。这是非常重要的数据,应该安全地存储!



所以如果你想访问google APIs没有用户的存在,你必须使用存储的 access_token 。如果响应是令牌过期(我认为有一个错误代码 - 必须做研究),然后你调用 $ client-> ; refreshToken($ refreshToken)使用您存储在某处的刷新令牌。你会得到一个新的 access_token 。使用此 access_token ,您可以进行进一步的工作,而无需用户点击某处(再次)。



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



我希望我能帮你一点。



资源


$ b b $ b

I am using the Google API Client to read emails from Gmail. Now I want to add a Cronjob so it reads every 5 minutes the mails.

The problem using the Google API Client is that it needs to allow the user to first click on the authorization link and allow the user to use the Google API Client.

I have a class Inbox with a function initialize that initliazes the Google API Client. But the cronjob doesn't work because I have to get an 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));
}

Do you guys know how to fix it using the refresh token or whatever? I can't get it working and I am out of ideas.

If I am accessing the URL and click on "Click Here" and allow it it works succesfully but not with a Cronjob because I can't click on the "Click Here" URL...

I hope you people understand it and can help me :).

Kind regards,
Yanick

解决方案

This answer is more a general approach on how to use the O-Auth2 Flow, since I faced with a similar problem a while ago. I hope it'll help a bit.

One possible problem (in understanding the correct use of OAuth) is that you use force as approval prompt. Why do you force the user to give permission when he already did?

When a user autheticates against your backend, he's asked if he wants to give your application permission to the actions defined in scope. The first time your application get this permissions (by the user clicking the "Agree"-Button) your Script will get an access_token and refresh_token from google.

The access_token is used to access the Google-APIs with the account of that authenticated user. You should store that somewhere on your server if you want to access the google APIs without having the user to be present (so called offline-access). With this token you can do anything in the name of the user (limited to defined scopes). It will went invalid after 1 hour or so. In the whole time (of 1 hour) you can use this token without having the user to be present!

The refresh_token is needed when the access_token wents invalid after this period of time. And only then. You only get the refresh_token ONCE and it will never change. This is very important data and should be stored safely!

So if you want to access google APIs without the user's presence you have to make API calls with the stored access_token. If the response is something like token expired (I think there was a errorcode for that - have to do research), then you call $client->refreshToken($refreshToken) with the refresh token you stored somewhere safe. You'll get a new access_token from that. With this access_token you can do further work, without having the user to click somewhere (again).

Next time that new access_token wents invalid, you have to use the same refresh_token as before and that's the reason why this refresh_token is so important.

I hope I could help you a little bit. If not, please comment on this.

Happy coding

Resources

这篇关于Google API客户端和Cronjob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆