小程序授权index.wxml
<view class="container">
<view class="userinfo">
<block wx:if="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
</view>
index.js
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUseGetUserProfile: false,
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
wx.login({
success (res) {
console.log(res.code)
if (res.code) {
wx.request({
url: 'http://www.tp1.com/index.php/admin/create',
data:{code:res.code},
header:{
//从缓存中获取token
'token': wx.getStorageSync('token')
},
success(res){
console.log(res.data.data.openid)
//把openid与token放入缓存中
wx.setStorageSync('openid', res.data.data.openid)
wx.setStorageSync('token', res.data.data.token)
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
getUserProfile(e) {
console.log(e)
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
var openid = wx.getStorageSync('openid')
console.log(res.userInfo.nickName)
var nickName = res.userInfo.nickName;
wx.request({
url: 'http://www.tp1.com/index.php/admin/edit',
data:{openid:openid,nickName:nickName},
success(res){
console.log(res)
// if(res){
// wx.navigateTo({
// url: '/pages/index2/index2',
// })
// }
}
})
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},
})
后端实现 判断库中是否有openid
public function edit()
{
$data = input();
$res = \app\admin\model\login::where('openid',$data['openid'])->select()->toArray();
if ($res[0]['nickName'] == ''){
$re = \app\admin\model\login::where('openid',$data['openid'])->update(['nickName'=>$data['nickName']]);
return json(['data'=>'','msg'=>'授权成功','code'=>0]);
}else{
$re = \app\admin\model\login::create(['nickName'=>$data['nickName'],'openid'=>$data['openid']]);
return json(['data'=>'','msg'=>'授权成功','code'=>0]);
}
}