【问题标题】:Using stream_context_create to do a POST -- Result is false:(使用 stream_context_create 进行 POST -- 结果为假:(
【发布时间】:2012-01-03 20:57:39
【问题描述】:

也许有人可以指出我在这里可能做错了什么。我在搞乱谷歌 API 和 OAuth,所以我可以通过谷歌将用户注册到我的应用程序。我发现他们提供的 PHP 相当繁琐,所以我决定更多地练习执行 https 请求等。到目前为止,我已经取得了一些成功,但是获取令牌以交换用户信息的最后一步需要一个 POST 方法。只需重定向浏览器,使用 GET 方法复制最终 url 就会返回错误。接下来我将开始研究 cURL 扩展,但也许有人能发现这段代码有什么问题?

$url = "https://accounts.google.com/o/oauth2/token";
$fields = array(
    'code' => $_GET['code'],
    'client_id' => $google['clientID'],
    'client_secret' => $google['clientSecret'],
    'redirect_uri' => "http://www.qwiku.com/scripts/php/google/reg_response.php",
    'grant_type' => "authorization_code"
);

$data = http_build_query($fields);

echo $data."<br />";

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    )
));

$result = file_get_contents($url, false, $context);

var_dump($result);  

结果转储为假。您可以在此处查看 google 文档,但我 99% 确信数据的公式是正确的。 http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#formingtheurl

更新

我现在正在使用 curl,它似乎可以正常工作。唯一的问题是谷歌返回“invalid_grant”错误。不知道为什么,因为它完全按照他们指定的方式设置。

$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

更新 2

我刷新了整个过程,因为我刚刚刷新了重定向和宾果游戏,它正在工作。代码必须已过期。

【问题讨论】:

标签: php post google-api


【解决方案1】:

你的方法看起来不错,

看看你有没有漏掉什么。
<?php
$data = http_build_query(....

$response = @file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create([
'http' => [ 'method'          => 'POST'
          , 'follow_location' => true
          , 'content'         => $data
          , 'header'          => implode("\r\n", ['Accept: */*'
                                                , 'Connection: keep-alive'
                                                , 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
                                                , 'User-Agent: jacob']) . "\r\n"
]]));
?>

【讨论】:

    【解决方案2】:

    您可以尝试使用另一种方法,例如使用 http 客户端类,它可以为您提供所有类似的东西:

    http://www.phpclasses.org/package/576-PHP-GET-HEAD-POST-methods-with-a-lot-of-features.html

    或者尝试像这样使用 OAuth 类:

    http://www.phpclasses.org/package/7700-PHP-Authorize-and-access-APIs-using-OAuth.html

    我已经通过 Practico 框架实现了这一点,并且一切正常,而不是使用 stream_context_create。

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多