1

I'm using PHP and I've successfully generated an access token for a user using Coinbase Oauth2 to sign in to my application. However, on using the same code to fetch the data of the user, I keep receiving the result below:

{"errors":[{"id":"invalid_token","message":"The access token is invalid"}]}

My question is, how do get a valid token that can enable carry out my API calls successfully?

This is my Laravel code below:

$apiURL = "https://api.coinbase.com/oauth/token";
    
    //parameters for the endpoint to generate access token for auth user
    $postInput = [
        'grant_type' => 'authorization_code',
        'code' => $request->code,
        'client_id' => env('COINBASE_CLIENT_ID'),
        'client_secret' => env('COINBASE_CLIENT_SECRET'),
        'redirect_uri' => env('COINBASE_REDIRECT_URI'),
    ];
    
    $response = Http::post($apiURL, $postInput);
    $statusCode = $response->status();
    $responseBody = json_decode($response->getBody(), true);

    $newAccessToken = [
        "access_token" => $responseBody['access_token'],
        "refresh_token" => $responseBody['refresh_token']
    ];

    //collect user info
    $apiURL = "https://api.coinbase.com/v2/user/";
    $headers = [
        'Authorization: Bearer ' . $newAccessToken["access_token"]
    ];
    
    $response = Http::withHeaders($headers)->get($apiURL);
    $responseBody = json_decode($response->getBody(), true);
    
    return $responseBody;

1 Answers1

0

I just saw the problem in the code. The error was as a result of this Authorization header that used a wrong syntax.

$apiURL = "https://api.coinbase.com/oauth/token";
    
    //parameters for the endpoint to generate access token for auth user
    $postInput = [
        'grant_type' => 'authorization_code',
        'code' => $request->code,
        'client_id' => env('COINBASE_CLIENT_ID'),
        'client_secret' => env('COINBASE_CLIENT_SECRET'),
        'redirect_uri' => env('COINBASE_REDIRECT_URI'),
    ];
    
    $response = Http::post($apiURL, $postInput);
    $statusCode = $response->status();
    $responseBody = json_decode($response->getBody(), true);

    $newAccessToken = [
        "access_token" => $responseBody['access_token'],
        "refresh_token" => $responseBody['refresh_token']
    ];

    //collect user info
    $apiURL = "https://api.coinbase.com/v2/user/";

    $headers = [
        'Authorization' => 'Bearer ' . $newAccessToken["access_token"]
    ]; // I used a wrong syntax of 'Authorization: Bearer ' . $newAccessToken["access_token"]
    
    $response = Http::withHeaders($headers)->get($apiURL);
    $responseBody = json_decode($response->getBody(), true);
    
    return $responseBody;