2021年4月28日24时后发布的小程序新版本,无法通过wx.getUserInfo与<button open-type="getUserInfo"/>获取用户个人信息(头像、昵称、性别与地区),采用getUserProfile接口获取,以下是个案例,供大家参考。
1、wxml前端按钮部分
<view><button class="btn_submit" catchtap="getUser">登录</button></view>
2、js部分代码:
//获取用户信息
async getUser(e) {
var _that = this
wx.getUserProfile({
desc:'正在获取',//不写不弹提示框
success:async function(res){
console.log(res.userInfo)//获取到的用户信息
wx.login({
success:async function(res) {
if (res.code) {
let getOpenidResponse = await getOpenid({code:res.code})
_that.isOpenid = getOpenidResponse.data.data.openid
} else {
wepy.wx.showModal({
title: '提示',
content: '网络繁忙,请稍后再试'
})
}
}
})
},
fail:function(err){
wepy.wx.showModal({
title: '提示',
content: '授权失败'
})
}
})
}3、php部分代码:通过获取到用户的code,后端请求接口,获取用户openid
public function getOpenid(Request $request){
$appId = Env('WECHAT_MINI_PROGRAM_APPID');
$secret = Env('WECHAT_MINI_PROGRAM_SECRET');
$authorization_code= 'authorization_code';
if(empty($request->code)){
return response ()->json(['code'=>500,'msg'=>'error','data'=>'is null']);
}else{
$js_code = $request->code;
$curl = curl_init();
//使用curl_setopt() 设置要获得url地址
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$secret.'&js_code='.$js_code.'&grant_type=authorization_code';
curl_setopt($curl, CURLOPT_URL, $url);
//设置是否输出header
curl_setopt($curl, CURLOPT_HEADER, false);
//设置是否输出结果
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设置是否检查服务器端的证书
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//使用curl_exec()将curl返回的结果转换成正常数据并保存到一个变量中
$data = curl_exec($curl);
$data =json_decode($data,true);
//关闭会话
curl_close($curl);
if(isset($data['openid'])){
return response ()->json(['code'=>200, 'msg'=>'成功', 'data'=>$data]);
}else{
return response ()->json(['code'=>500, 'msg'=>'失败']);
}
}
}
关于简忆
简忆诞生的故事



粤ICP备16092285号
文章评论(0)