首页 文章

在php cron job中运行google api

提问于
浏览
1

我想在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_Service_Gmail) . 所有凭据都是正确的 .

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

1 回答

  • 1

    我有同样的问题,但我偶然发现了刷新令牌 .

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

    我创建了一种cookie,它持续了几年,脚本可以读取刷新令牌 . 需要创建刷新令牌 . 为了创建这个令牌,我在浏览器中运行了一个类似的脚本,查看了Google返回的字段,其余的只是为了复制它 . 所需的凭据包括访问令牌,令牌类型,到期,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脚本中使用刷新令牌,只要有一个refreshtoken就应该获得授权 .

    希望它有所帮助,如果你有进一步的问题,我可以尝试回答它们,因为我正在开发一个类似的脚本 .

相关问题