读&使用服务帐户

时间:2016-03-01 12:36:56

标签: php google-api gmail-api

我需要一个cron才能在我的共享主机上运行,​​它将每30分钟扫描一次我的Gmail帐户,并使用PHP回复所有未读的电子邮件

首先我用作曲家下载了apiclient - > { "require": { "google/apiclient": "1.*" } }。然后我创建服务帐户(https://console.developers.google.com/apis/credentials/serviceaccountkey?project=xxxxxx)并获取具有以下值的json文件:

"type": "service_account",
  "project_id": "xxxxxx",
  "private_key_id": "xyxyxyxyyxyxy",
  "private_key": "-----BEGIN PRIVATE KEY-----\ndddddddddddddddmr\n-----END PRIVATE KEY-----\n",
  "client_email": "yy-yyy@zzzz-zzzzzz.iam.gserviceaccount.com",
  "client_id": "11763887676776474",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxx%40zzz-zzzzzz.iam.gserviceaccount.com"

还确保启用了gmail api(from)。 现在我想知道如何连接gmail并使用php读取未读取的电子邮件...

我正在修改示例代码,但卡在这里($ apiKey =)......

<?php
include_once "vendor/google/templates/base.php";
echo pageHeader("Simple API Access");

require_once realpath(dirname(__FILE__) . '/vendor/google/apiclient/src/Google/autoload.php');

$client = new Google_Client();
$client->setApplicationName("Gmail access test");
$apiKey = "<YOUR_API_KEY>"; // WHICH VALUE i SHOULD PUT HERE????.

// Warn if the API key isn't changed.
if (strpos($apiKey, "<") !== false) {
    echo missingApiKeyWarning();
    exit;
}
$client->setDeveloperKey($apiKey);

$service = new Google_Service_Books($client);
...
...
...

更新:我的更新代码如下所示

<?php
require_once realpath(dirname(__FILE__) . '/vendor/google/apiclient/src/Google/autoload.php');

session_start();

$scopes = array(
    Google_Service_Gmail::GMAIL_READONLY,
    Google_Service_Gmail::GMAIL_COMPOSE,
    Google_Service_Gmail::GMAIL_SEND,
    Google_Service_Gmail::MAIL_GOOGLE_COM,
);

$client = new Google_Client();
$arDetails = $client->loadServiceAccountJson('99b15f1f2326.json', $scopes);

$client->setAssertionCredentials($arDetails);
$client->setScopes($scopes);

$fl = $client->getAuth()->isAccessTokenExpired() ;

if($fl) {
    $client->getAuth()->refreshTokenWithAssertion($arDetails);
}

$client->setAccessType('offline');
$gmailService = new Google_Service_Gmail($client);


#$users = $gmailService->users;
$users = $gmailService->users_messages;

$optParams['maxResults'] = 5; // Return Only 5 Messages
$optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox
$messages     = $gmailService->users_messages->listUsersMessages('me',$optParams);

echo '<br/><pre>';
print_r($users);
print_r($messages);

----
---
---

但我收到错误 -

PHP Fatal error:  Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=5&labelIds=INBOX: (400) Bad Request' in /home3/shafico1/public_html/imsdev/frontend/web/atiq/vendor/google/apiclient/src/Google/Http/REST.php:110
Stack tra

0 个答案:

没有答案