登录授权获取用户信息,本文使用的新版的登录授权接口,结合后端ThinkPHP6框架实现
1、放置授权登录按钮
<template> <view class="userinfo" v-if="userInfo !=''"> <view class="userimg"> <image :src="userInfo.avatar" mode=""></image> </view> <view class="nickName"> {{userInfo.nickName}} </view> </view> <view class="userinfo" v-else> <view class="userimg"> <image src="../../static/tx.png" mode=""></image> </view> <button @click="onGotUserInfo">授权</button> </view> </template>
2、授权方法
export default { data() { return { userInfo: '', } }, methods: { /** * 用户同意授权个人微信信息 * @param {Object} e 用户的信息 */ async onGotUserInfo() { uni.getUserProfile({ desc:'正在获取',//不写不弹提示框 success: res=> { uni.login({ success: async res1=> { if (res1.code) { const res2 = await this.$myRequest({ url: '/index/Index/getUserLogin', data: { code: res1.code, nickName: res.userInfo.nickName, avatar: res.userInfo.avatarUrl }, }) if(res2.data.code==200){ uni.setStorageSync('dy_userInfo', res2.data.data); this.userInfo = uni.getStorageSync('dy_userInfo'); // this.userInfo = res2.data } } else { uni.showModal({ title: '提示', content: '网络繁忙,请稍后再试' }) } } }) }, fail: err=> { uni.showToast({ title: '请点击授权进行登录', icon: 'none' }); } }) }, } }
3、后端代码
//授权·登录 public function getUserLogin(){ $appId = 'APPID'; $secret = 'secret'; $authorization_code= 'authorization_code'; if(empty(input('code'))){ return json(['code'=>500,'msg'=>'error','data'=>'is null']); }else{ $js_code = input('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'])){ $addArray = [ 'avatar' =>input('avatar'), 'nickName' =>input('nickName'), 'openid' =>$data['openid'], 'created_at' =>time(), 'updated_at' =>time(), 'ip' =>$_SERVER['REMOTE_ADDR'], ]; $updateArray = [ 'avatar' =>input('avatar'), 'nickName' =>input('nickName'), 'openid' =>$data['openid'], 'updated_at' =>time(), 'ip' =>$_SERVER['REMOTE_ADDR'], ]; $find = Db::name('weixin_dy_user')->where(array('openid'=>$data['openid']))->find(); if($find){ $res = Db::name('weixin_dy_user')->where(array('openid'=>$data['openid']))->update($updateArray); }else{ $res = Db::name('weixin_dy_user')->insert($addArray); } if($res){ $findRes = Db::name('weixin_dy_user')->where(array('openid'=>$data['openid']))->find(); return json(['code'=>200, 'msg'=>'成功', 'data'=>$findRes]); } }else{ return json(['code'=>500, 'msg'=>'失败']); } } }
4、效果展示:
文章评论(0)