代码之家  ›  专栏  ›  技术社区  ›  rfc1484

如何使用查询字符串参数制作Guzzle帖子

  •  6
  • rfc1484  · 技术社区  · 8 年前

    在一个GoogleOauth2实现中,我尝试使用一个guzzle调用来交换授权码和令牌。

    以下guzzle调用工作正常,并返回预期值:

     $result = $this->client->post(
            'https://www.googleapis.com/oauth2/v3/token?code=<authorization_code>&redirect_uri=<redirect_uri>&client_id=<client_id>&client_secret=<client_secret>&grant_type=authorization_code')
    ->getBody()->getContents();
    

    然而,这似乎是一种安装post请求的肮脏方式。

    为了让它更干净,我尝试了以下方法:

        $result = $this->client->post(
            'https://www.googleapis.com/oauth2/v3/token',
            [
                'query' =>
                    [
                        'code' => <authorization_code>,
                        'redirect_uri' => <redirect_uri>,
                        'client_id' => <client_id>,
                        'client_secret' => <client_secret>
                        'grant_type' => 'authorization_code',
                    ]
            ]
        )->getBody()->getContents();
    

    然而,第二次调用会生成 Malformed Json 错误消息。

    你知道我可能做错了什么,或者我如何调试上面示例中生成的最终url吗?

    2 回复  |  直到 8 年前
        1
  •  11
  •   D.Dimitrioglo    8 年前

    我试过没有 code 参数和它的工作。

    $client = new \GuzzleHttp\Client();
    
    $response = $client->post('https://www.googleapis.com/oauth2/v3/token', [
        'query' => [
            'client_id' => '...apps.googleusercontent.com',
            'client_secret' => 'secret',
            'refresh_token' => 'token',
            'grant_type' => 'refresh_token'
        ]
    ]);
    
    $token = $response->getBody()->getContents()
    
        2
  •  -3
  •   Jason    8 年前

    您是否尝试过使用数组和 http://php.net/json_encode