PHP curl 不能与 dropbox OAuth 一起使用,returns "invalid request"

PHP curl not working with dropbox OAuth, returns "invalid request"

Dropbox 文档说要进行身份验证,您必须执行以下操作:

curl https://api.dropbox.com/oauth2/token \
    -d code=<AUTHORIZATION_CODE> \
    -d grant_type=authorization_code \
    -d redirect_uri=<REDIRECT_URI> \
    -u <APP_KEY>:<APP_SECRET>

这是我尝试使用 PHP 但是 dropbox returns 出现错误 无效请求 - 请求参数与任何支持的授权流程都不匹配

$url = "https://api.dropbox.com/oauth2/token";
            $redirect_uri = 'https://www.mywebsite.com/oauth_dropbox';
           
            $postfields = array(
                'code' => $_GET['code'],
                'grant_type' => 'authorization_code',
                'redirect_uri' => $redirect_uri
            );

            $auth = "$app_key:$app_secret";
            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields));
            curl_setopt($curl, CURLOPT_USERPWD, $auth);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

            $json_response = curl_exec($curl);
            $responseObj = json_decode($json_response);

我该如何解决?

您当前的 curl 发送 GET 请求(这就是为什么外部 API 没有看到任何发送的参数),但您正在添加内容,因为它是 POST 请求。也加上CURLOPT_POST

$url = "https://api.dropbox.com/oauth2/token";
$redirect_uri = 'https://www.mywebsite.com/oauth_dropbox';
           
$postfields = [
    'code' => $_GET['code'],
    'grant_type' => 'authorization_code',
    'redirect_uri' => $redirect_uri
];

$auth = "$app_key:$app_secret";
$curl = curl_init($url);

curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields));
curl_setopt($curl, CURLOPT_USERPWD, $auth);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$json_response = curl_exec($curl);
$responseObj = json_decode($json_response);

如果您显式设置基本授权,这似乎可行,也就是说,而不是:

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

设置这个:

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);