使用 Curl PHP 进行 URL 编码

Ric*_*ick 2 php curl urlencode url-encoding

我进行了建议的更改,但仍然收到类似的错误:

{“error”:“invalid_request”,“error_description”:“无效的授权类型”}

如果 url 编码设置不正确,则可能会发生此错误。更新后的代码如下 任何帮助将不胜感激!

<?php

$client_id = '...';
$redirect_uri = 'http://website.com/foursquare2.php';
$client_secret = '...';
$code = $_REQUEST['code'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, "https://id.shoeboxed.com/oauth/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
));

$response = curl_exec($ch);

$err = curl_error($ch);
curl_close($ch);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>
Run Code Online (Sandbox Code Playgroud)

han*_*rik 6

您的代码正在以格式发送数据multipart/form-data。当你给 CURLOPT_POST 一个数组时,curl 会自动以该格式对该数组中的数据进行编码multipart/form-data。然后你用你的标头告诉服务器,this data is in application/x-www-form-urlencoded format服务器将尝试这样解析它,并失败,因此你收到了错误。

首先,完全摆脱curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));。如果您使用 application/x-www-form-urlencoded,php/curl 会自动为您添加该标头,并且与您不同的是,php/curl 不会出现任何拼写错误(开发人员有自动测试套件来确保这一点)每个版本之前的内容都是正确的),同样,如果您使用multipart/form-data格式,php/curl 将为您添加该标头,因此不要手动添加这两个特定标头。

如果您想使用该multipart/form-data格式,只需删除标头即可。但是如果你想使用application/x-www-form-urlencoded格式,PHP 有一个内置函数可以编码为这种格式,称为http_build_query,所以可以

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
)));
Run Code Online (Sandbox Code Playgroud)

(并且还要删除内容类型标头,它将自动添加。)