1

我正在使用 PHP,并且已成功为使用 Coinbase Oauth2 登录我的应用程序的用户生成访问令牌。但是,在使用相同的代码获取用户的数据时,我不断收到以下结果:

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

我的问题是,如何获得可以成功执行我的 API 调用的有效令牌?

这是我的 Laravel 代码如下:

$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;
4

1 回答 1

0

我刚刚在代码中看到了问题。该错误是由于此 Authorization 标头使用了错误的语法造成的。

$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;
于 2022-01-13T08:09:15.477 回答