保管箱 API 中缺少必填字段 "grant_type"

Missing required field "grant_type" in dropbox API

我正在尝试使用 Dropbox api 来显示主列表文件夹,但当我尝试从授权用户那里获得访问令牌时遇到了很多问题。

我的代码非常简单,我通过向我的应用授予权限来获取代码。取回令牌的请求是这样的。

$client = new GuzzleHttp\Client();

try{
//    $response = $client->get("https://www.dropbox.com/oauth2/authorize?client_id=". $client_id . "&response_type=code");

    $response = $client->post("https://api.dropboxapi.com/oauth2/token",
        array(
            'json'  => array(
                'grant_type'    => 'authorization_code',
                'code' => '********ZJtDI'
            ),
            'auth'      => array(
                $client_id,
                $client_secret
            ), 
        ));

    echo $response->getBody();

}catch ( \Exception $e ){
    echo $e->getMessage();
}

Client error: `POST https://api.dropboxapi.com/oauth2/token` resulted in a `400 Bad Request` response:
{"error_description": "missing required field \"grant_type\"", "error": "invalid_request"}

您的 POST 请求必须包含 application/x-www-form-urlencoded 编码的 POST 数据,而不是 JSON 字符串。请参阅 https://www.dropbox.com/developers-v1/core/docs#oa2-token. And read http://docs.guzzlephp.org/en/stable/quickstart.html#post-form-requests 以发送带有普通表单字段的 POST 请求。

正如 Progman 所说,您必须使用通常的表单类型 (application/x-www-form-urlencoded) 而不是 JSON。

使用 Guzzle 很简单:

$response = $client->post("https://api.dropboxapi.com/oauth2/token",
    array(
        'form_params' => array(
            'grant_type' => 'authorization_code',
            'code' => '********ZJtDI',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
        ),
    )
);