Google API使用access_token获取收件箱电子邮件?

时间:2012-02-11 10:41:57

标签: php gmail

我可以使用oAuth 2.0为电子邮件,联系人,文档等多种权限获取access_token。我有access_token 我使用以下代码获得了联系人。

$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-  results='.$max_results.'&oauth_token='.$access_token;

$response_contacts=  curl_get_file_contents($url);

现在我想让用户使用此access_token发送电子邮件。 我用过这个网址。但它提供了 401 unauthorized Error

$url = 'https://mail.google.com/mail/feed/atom&oauth_token='.$access_token;
$response_emails=  curl_get_file_contents($url);

请指导我如何使用access_token获取电子邮件。

1 个答案:

答案 0 :(得分:2)

我已使用oauth_token作为请求参数看到了对Gmail Feed的引用。但是,一旦我使用了OAuth Playground,我发现您需要将OAuth信息作为Authorization标题传递,如下所示。

<?php
$now = time();
$consumer = ...; // your own value here
$secret = ...; // your own value here
$nonce = ...; // same value you've been using
$algo = "sha1";
$sigmeth = "HMAC-SHA1";
$av = "1.0";
$scope = "https://mail.google.com/mail/feed/atom";
$path = $scope;
$auth = ...; // an object containing outputs of OAuthGetAccessToken

$args = "oauth_consumer_key=" . urlencode($consumer) .
  "&oauth_nonce=" . urlencode($nonce) .
  "&oauth_signature_method=" . urlencode($sigmeth) .
  "&oauth_timestamp=" . urlencode($now) .
  "&oauth_token=" . urlencode($auth->oauth_token) .
  "&oauth_version=" . urlencode($av);

$base = "GET&" . urlencode($path) . "&" . urlencode($args);

$sig = base64_encode(hash_hmac($algo, $base,
  "{$secret}&{$auth->oauth_token_secret}", true));

$url = $path . "?oauth_signature=" . urlencode($sig) . "&" . $args;

// Create a stream
$opts = array(
  "http" => array(
    "method" => "GET",
    "header" => "Authorization: OAuth " .
       "oauth_version=\"{$av}\", " .
       "oauth_nonce=\"{$nonce}\", " .
       "oauth_timestamp=\"{$now}\", " .
       "oauth_consumer_key=\"{$consumer}\", " .
       "oauth_token=\"{$auth->oauth_token}\", " .
       "oauth_signature_method=\"{$sigmeth}\", " .
       "oauth_signature=\"{$sig}\"\r\n"
  )
);

$context = stream_context_create($opts);

$out = file_get_contents($path, false, $context);
?>