Gmail API:一个请求API的例子



我正在尝试访问Gmail API与我的应用程序。我应该已经正确地完成了所有的设置,我正在测试对API的请求,在特定的请求中获得只读消息。

我代码:

public function gmail_get_messages()
{
    $client = new Google_Client();
    $client->setApplicationName("Gmail API test");
    $client->setDeveloperKey("MY_KEY");
    $client->setClientSecret('MY_CLIENT_SECRET');
    $client->setScopes(array('https://www.googleapis.com/auth/gmail.readonly'));
    // $client->setAccessToken($token);
    $service = new Google_Service_Gmail($client);
    $url = 'https://www.googleapis.com/gmail/v1/users/MY_EMAIL/messages';
    $header = array("Authorization: access_token {MY_ACCESS_TOKEN}");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    $retValue = curl_exec($ch);
    $response = json_decode(curl_exec($ch));
    $ee       = curl_getinfo($ch);
    print_r($ee);
    print_r($retValue);
}

反应:

{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } }

一个要点是关于令牌的。我已经获得了访问令牌和刷新令牌作为json格式的文件,但我不知道如何将它们包含在请求中。

如何正确地将令牌传递给请求?是缺了唯一的东西还是有别的东西?

如果有人能提供一个适当的请求的例子,我将非常感激!

我想你很接近了!尝试像这样为客户端分配访问令牌:

$client = new Google_Client();

$client->setApplicationName('Gmail API test');
$client->setDeveloperKey('MY_KEY');
$client->setClientSecret('MY_CLIENT_SECRET');
$client->SetClientId('MY_CLIENT_ID');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.readonly'));
$client->setAccessToken('{"access_token":"MY_ACCESS_TOKEN",
                          "token_type":"Bearer"‌​,"expires_in":3600,
                          "refresh_token":"MY_REFRESH TOKEN","created":1433329214}');
$service = new Google_Service_Gmail($client);
$messages = $service->users_messages->listUsersMessages('me');
$list = $messages->getMessages();
// Look at the contents of the first message
$message = $list[0];
$parts = $message->getPayload()->getParts();
$body = $parts[0]['body'];
$rawData = $body->data;
$sanitizedData = strtr($rawData,'-_', '+/');
$decodedMessage = base64_decode($sanitizedData);
var_dump($decodedMessage);

相关内容

  • 没有找到相关文章

最新更新