微信小程序实现授权登录功能,并获取用户账号信息

2021-08-01   阅读:2298   分类:后端    标签: 微信小程序

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'=>'失败']);
		 }
		 
		
	}
}
【腾讯云】 爆款2核2G3M云服务器首年 61元,2核2G4M云服务器新老同享 99元/年,续费同价

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://tpxhm.com/adetail/755.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×