2016-03-02 106 views
2

在Google Oauth2實現中,我試圖使用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是什麼?

+1

我的第一個猜測是,發送的請求在某種程度上不完全相同。我將開始使用「調試」請求選項。傳遞一個真值作爲您的客戶實例或您的發佈請求中的一個選項。 –

回答

3

我嘗試沒有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()