Skip to main content
3 of 4
Added cURL example

access_token not present in /oauth/access_token response

When using the explicit oath authentication for stack apps, I have problem receiving the access_token. A user goes to /approve and is then forwarded to approve the app. When redirected back to my site I catch the code parameter and do the final POST to get the access_token. However I cant find it in the response object!

This is my php routes file:

use GuzzleHttp\Client;

Route::get('/approve', function () {
    header('Location: https://stackexchange.com/oauth?client_id=12345&scope=write_access&redirect_uri=https://mysite.com/approved');
});

Route::get('/approved', function (Request $request) {
    $client = new Client();    
    $response = $client->request('POST', 'https://stackexchange.com/oauth/access_token/json', [
        'form_params' => [
            'client_id' => 12345,
            'client_secret' => 'apfeusenfpuansefpunapfn((',
            'code' => \Request::get("code"),
            'redirect_uri' => 'https://mysite.com/approved'
        ]
    ]);

    dd($response); // dumping the response gives no trace of access_token
});
  • Running getStatusCode() on the response object gives a 200 All ok.
  • Dumping the full response, body, or headers give me no reference of the access_token whatsoever.
  • I tried swapping "form_params" to "query" same result.
  • Adding "json" to the API URL gives no change.
  • I'm using Guzzle 6

Any ideas, where did I go wrong?


Update: I managed to get the access_token with cURL so I am assuming I am not using guzzle correctly...

function RequestToken($code)
{
    $params = array(
        "code" => $code,
        "client_id" => 12345,
        "client_secret" => 'agibsgiasbgoaigbasorgibas((',
        "redirect_uri" => 'https://mysite.com/approved'
    );
    $postString = rawurldecode(http_build_query( $params ));
    
    $ch = curl_init('https://stackexchange.com/oauth/access_token');
    
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, false );
    curl_setopt( $ch, CURLOPT_HEADER, false );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POST, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $postString );
    
    $httpResponse = curl_exec( $ch );
    
    parse_str($httpResponse, $output);
    
    return $output["access_token"];
}