微信小程序一键授权之前先勾选用户协议
开始想的是直接在getPhoneNumber()方法中加一个判断。这种做法存在的问题是,没有勾选协议的情况下点击按钮后弹出授权页面,会挡住前面加的判断提示,点击授权同意后才会看到提示请勾选用户协议的提示框。然后勾选协议再次点击按钮时又出现授权弹框,用户体验不好。
解决方法: wxml页面写两个一模一样的按钮,绑定不同的方法,显示隐藏加一个判断,判断条件是是否勾选,勾选的话就调用获取手机号方法,没勾选的话显示点击弹出提示勾选的方法。
data: {
agree:agree //默认勾选状态
},
//获取手机号
getPhoneNumber: function (e) {
var that = this;
if (this.data.agree == ){
wx.showToast({
title: 请勾选用户协议,
icon: none,
duration: 2000
})
}
if (e.detail.errMsg == getPhoneNumber:fail user deny) {
wx.showToast({
title: 您已取消授权,
icon: none,
duration: 2000
})
} else {
console.log("同意授权手机号")
console.log(e);
var number = e;
wx.login({
success: function (res) {
if (res.code) {
net.mylog("code是" + res.code);
net.request_post(false, myurl + /wx/getInfo,
{
code: res.code },
function (res2) {
//请求接口解密
console.log(number)
var pc = new WXBizDataCrypt(config.appId, res2.data.session_key)
var data = pc.decryptData(number.detail.encryptedData, number.detail.iv);
console.log(data.phoneNumber);
that.submitRegister(data.phoneNumber); //提交注册信息
})
} else {
wx.showToast({
title: "获取手机号码失败",
icon: none,
duration: 2000
})
}
},
fail: function (error) {
wx.showToast({
title: "获取手机号码失败",
icon: none,
duration: 2000
})
}
})
}
} ,
上面代码中,在util.js文件夹中新建工具类封装方法。(在页面中调用封装的方法时,要记得引用)
var net = require("../../../utils/netTools.js");
封装post请求:
function request_post(auto,url, data, success, fail) {
if(auto==true){
wx.showLoading({
title: 加载中,
})
}
wx.request({
url: url, //接口地址
data: data,
method: POST,
header: {
Content-Type: application/x-www-form-urlencoded;charset=utf-8
},
success: function (res) {
// console.log(res);
if (auto == true) {
wx.hideLoading();
}
if (res.data.code==200) {
success(res.data);
}else {
wx.showToast({
title: res.data.msg,
icon: none,
duration: 2000
})
}
},
fail:function(){
wx.showToast({
title: "服务异常",
icon: none,
duration: 2000
})
if (auto == true) {
wx.hideLoading();
}
if(fail != null){
fail();
}
}
})
}
module.exports = {
request_post: request_post
}
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信小程序的一些基本知识,微信小程序开发
