问题
后台请求获取手机号码接口,微信直接返回40071
直接说结果
php 发送 curl 请求的时候,需要注意几个点
- heder 头要改成 json 格式请求
- bady 请求体内不要包含 access_token
懂的人已经开始弄起来了,但是肯定还有一头雾水的,请看完整流程↓↓↓
流程
- 前端通过微信小程序组件获取 code,不关我事,没细看,但是是这个地址,有全干的大怨种可以看这个文档,参考官方文档: https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
- 后台得到前端给的 code 后,给微信发送请求,参考官方文档:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
问题主要就卡在第二步
###伪代码
function getPhone($accesstoken, $code){
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$accesstoken;
$postData = [
//这里不用放 access_token ,用了一定报错
'code'=>$code,
];
// 这里一定要用 json_encode 转码,不然一定报错
$ret = request_post($url, json_encode($postData));
if ($ret['errcode'] <1 && $ret['errcode'] >-1 ) {
//这个就是用户的手机号码了,更多的内容看官方的文档
$phoneNumber = $ret['phone_info']['phoneNumber'];
}
}
fuinction request_post($url, $postData){
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $requestUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 验证,生产环境建议使用正确的证书验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// 设置请求方法为 POST
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//这里也是一样,一定要声明是json请求
'Content-Type: application/json',
]);
// 设置 POST 数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// 执行 cURL 请求
$response = curl_exec($ch);
// 检查是否有错误
if (curl_errno($ch)) {
return self::fail('Curl error', curl_error($ch));
}
// 关闭 cURL 会话
curl_close($ch);
return json_decode($response, true);
}
end
至此,艺术已成,可以去拉屎了
参考
https://developers.weixin.qq.com/community/develop/doc/000ccee36c41c00fa59d337765b400
不配图应该也没啥了吧