URL 使用 Curl 编码 PHP

URL Encode With Curl PHP

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

{"error":"invalid_request","error_description":"invalid grant type"}

如果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;
}
?>

您的代码正在以 multipart/form-data 格式发送数据。当您给 CURLOPT_POST 一个数组时,curl 会自动将该数组中的数据编码为 multipart/form-data 格式。然后你用 header 告诉服务器 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 会自动为您添加 header,并且与您不同的是,php/curl 不会出现任何拼写错误(开发人员获得了自动化测试套装确保这些东西在每次发布之前都是正确的),同样,如果您使用 multipart/form-data 格式,php/curl 会为您添加 header,所以不要添加这两个特定的header 手动。

如果您想使用 multipart/form-data 格式,只需去掉 header 即可。但是如果你想使用 application/x-www-form-urlencoded 格式,PHP 有一个 built-in 函数可以编码成这种格式,叫做 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
)));

(同时去掉content-type header,它会自动添加。)