微信小程序button受权

前瞻:css

 

 

微信小程序受权方式改成只能经过button按钮点击触发,抛弃原来的模态框受权模式;

 

  

实现思路:数据库

  实现地方在小程序全局app.js里面触发,但app.js中没法实现dom操做.故惟一方式就是当获取到新用户的时候利用跳转路由方法,跳转至一个新的页面去进行受权操做.json

  

案例难点:小程序

  1.app.js中 当验证受权是 经过wx.getSetting 中的res.authSetting['scope.userInfo'] 判断是否为新用户在此作跳转;微信小程序

  2.当受权成功时跳转回首页,数据没法从新加载,应在app.js中添加一个函数来监控状态值当受权成功时调用配合数据刷新从新获取数据;微信

  3.跳转的时候运用redirectTo 这样能实现不受权禁止访问的需求;app

页面:dom

 

 

代码片断:函数

login.wxmlthis

 

<view wx:if="{{canIUse}}">
<view class='header'>
<image src='/images/wx_login.png'></image>
</view>

<view class='content'>
<view>申请获取如下权限</view>
<text>得到你的公开信息(昵称,头像等)</text>
</view>

<button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo"> 受权登陆 </button>
</view>

<view wx:else>请升级微信版本</view>

 


 

login.wcss

 

.header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; line-height: 450rpx;
} .header image { width: 200rpx; height: 200rpx;
} .content { margin-left: 50rpx; margin-bottom: 90rpx;
} .content text { display: block; color: #9d9d9d; margin-top: 40rpx;
} .bottom { border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx;
}

 

login.json

 

{
"navigationBarTitleText": "受权登陆"
}
 

 

app.js

Page({ data: { //判断小程序的API,回调,参数,组件等是否在当前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo') }, onLoad: function () { var that = this; // 查看是否受权
wx.getSetting({ success: function (res) { if (res.authSetting['scope.userInfo']) { wx.getUserInfo({ success: function (res) { //从数据库获取用户信息
that.queryUsreInfo(); //用户已经受权过
wx.switchTab({ url: '' }) } }); } } }) }, bindGetUserInfo: function (e) { if (e.detail.userInfo) { //用户按了容许受权按钮
var that = this; //插入登陆的用户的相关信息到数据库
wx.request({ url: getApp().globalData.urlPath + 'hstc_interface/insert_user', data: { openid: getApp().globalData.openid, nickName: e.detail.userInfo.nickName, avatarUrl: e.detail.userInfo.avatarUrl, province:e.detail.userInfo.province, city: e.detail.userInfo.city }, header: { 'content-type': 'application/json' }, success: function (res) { //从数据库获取用户信息
that.queryUsreInfo(); console.log("插入小程序登陆用户信息成功!"); } }); //受权成功后,跳转进入小程序首页
wx.switchTab({ url: '' }) } else { //用户按了拒绝按钮
wx.showModal({ title:'警告', content:'您点击了拒绝受权,将没法进入小程序,请受权以后再进入!!!', showCancel:false, confirmText:'返回受权', success:function(res){ if (res.confirm) { console.log('用户点击了“返回受权”') } } }) } }, //获取用户信息接口
queryUsreInfo: function () { wx.request({ url: getApp().globalData.urlPath + 'hstc_interface/queryByOpenid', data: { openid: getApp().globalData.openid }, header: { 'content-type': 'application/json' }, success: function (res) { console.log(res.data); getApp().globalData.userInfo = res.data; } }); }, })

 


补充:
---------------------
做者:csdn_小东
来源:CSDN
原文:https://blog.csdn.net/weidong_y/article/details/79636386
版权声明:本文为博主原创文章,转载请附上博文连接!

 

代码片断直接上了 大佬的 我的由于项目保密

相关文章
相关标签/搜索