首页 > 建站教程 > PHP教程 >  thinkphp6 获取小程序码 47001错误正文

thinkphp6 获取小程序码 47001错误

在用thinkphp6写一个项目的接口时,需要用wxacode.getUnlimited获取小程序码,代码如下:
//获取小程序码
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_POST, 1);
$fields = [
    'scene' => $data['scene'],
    'page' => $data['page'],
    'width' => 500
];
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
$res = curl_exec($curl);
curl_close($curl);
var_dump(json_encode($res));
可是得到的结果却是:
{"errcode":47001,"errmsg":"data format error hint:"}
从字面意思是,参数格式错误。后来找了半天,才发现:
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
上面这行代码有问题,参数必须要json格式化,官方文档根本没有说要这么干,太坑了!加上请求头,并且将参数json化,不再报上面的错了:
//获取小程序码
$curl = curl_init();
$headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
curl_setopt($curl, CURLOPT_URL, 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl, CURLOPT_POST, 1);
$fields = [
    'scene' => $data['scene'],
    'page' => $data['page'],
    'width' => 500
];
//参数json序列化
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields));
//设置请求头
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
$res = curl_exec($curl);
curl_close($curl);
var_dump(json_encode($res));