【问题标题】:running google api in php cron job在 php cron 作业中运行 google api
【发布时间】:2015-05-26 15:43:07
【问题描述】:

我正在尝试在 php cron 作业中运行 google API (gmail)。

我尝试创建一个服务器密钥并使用 setDeveloperKey 将其嵌入到代码中,但它给出了登录错误。

代码如下:

require_once 'Google/autoload.php';
require_once 'Google/Client.php';   
require_once 'Google/Service/Gmail.php';
$client = new Google_Client();
$client->setClientId($google_clientID);
$client->setClientSecret($google_secret);
$client->setRedirectUri($emm_redirecturi);
$client->addScope('email');
//$client->addScope('profile');     
$client->addScope('https://mail.google.com');           
$client->setAccessType('offline');

$client->setDeveloperKey($google_key);
$client->setApprovalPrompt('auto');

$gmailService = new Google_Service_Gmail($client);

任何人都能够破解这个?我在文档中搜索但无法弄清楚。

错误消息:致命错误:未捕获的异常“Google_Auth_Exception”和消息“获取 OAuth2 访问令牌时出错,消息:'invalid_grant:无效代码。

在调用 google 服务之前一切正常。 (在本例中为 Google_Service_Gmail)。所有凭据均正确。

我需要一个永久性的解决方案。不是存储可能过期的令牌的情况。

【问题讨论】:

    标签: google-api-php-client


    【解决方案1】:

    我遇到了同样的问题,但我偶然发现了刷新令牌。

    $client->setAccessToken($credentials);
    $client->refreshToken($refresh);
    

    我创建了一种持续数年的 cookie,以便脚本读取刷新令牌。需要创建刷新令牌。为了创建这个令牌,我在浏览器中运行了一个类似的脚本,查看了谷歌返回的字段,剩下的只是复制它。所需的凭据是访问令牌、令牌类型、过期时间、ID 令牌、刷新令牌和已创建。步骤如下:

    1)访问它将生成的 authUrl

     $authUrl = getAuthorizationUrl("", ""); //This will create an URL that you need to visit to generate at least once (that's why you have the offline access in your code and the auto prompt)
    

    2) 使用以下脚本,并根据您的设置进行调整。 https://developers.google.com/drive/web/credentials

    3) 存储他们给你的令牌或凭据,在需要 cronjob 的 php 脚本中使用刷新令牌,只要有刷新令牌,它就应该获得授权。

    希望对您有所帮助,如果您还有其他问题,我可以在开发类似脚本时尝试回答。

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多