接口文档给的示例代码如下图:
<?php
$host = "http://id2meta.market.alicloudapi.com";
$path = "/id2meta";
$method = "GET";
$appcode = "你自己的AppCode";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "identifyNum=identifyNum&identifyNumMd5=identifyNumMd5&userName=userName&userNameMd5=userNameMd5";
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
if (1 == strpos("$".$host, "https://"))
{
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
var_dump(curl_exec($curl));
?>
这个代码用上之后有两个问题。
一是返回值带head请求头信息,导致json_decode($data,true);处理后结果为null,把curl_setopt($curl, CURLOPT_HEADER, true);里的true改为false后解决。
二是请求的参数中姓名是中文,错误提示为参数非法(userName),推断是编码问题。先是
修改请求头header,加上如下代码。
$headers = array();
array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
或
array_push($headers, "Content-Type" . ":" . "text/html; charset=UTF-8");
都不行,然后猜测是存在bom格式,加入如下代码处理
if(preg_match('/^\xEF\xBB\xBF/',$info)){
$info = substr($info,3);
}
$info = json_decode(trim($info),true);
还是不行,最后给中文参数加上urlencode()函数处理后成功。但这是header请求头设置了utf-8编码的情况,单独用这个函数是否可以没试。
$querys = "identifyNum=".$card."&"."userName=".urlencode($name);
扩展:
其实在接口文档提供的调试工具中,可以发现接口传参是这样子的:
![](https://img-blog.csdnimg.cn/8902ff230bcb4ed58774d052320ce4ba.png)
即中文姓名被编码成了百分号与16进制数字的组合,这就是Urlencode编码,其又称百分号编码,是一种很常用的编码方式。如果了解这点,或许能更快的发现问题。
参考文献:
云盾身份认证(身份证二要素核验)【最新版】_实名认证接口/API_身份证接口/API-云市场-阿里云 (aliyun.com)
php curl后json_decode无法显示的问题_php json_decode 数组值不显示缩在一起。。。显示_0xzmz的博客-CSDN博客
PHP基于curl发送post、get请求中文乱码问题解决方法 亲测有效_curl utf8_夏夏老是睡不着.的博客-CSDN博客