uniapp微信小程序登录,获取手机号,支付,分享,消息订阅功能
登录
uni.login() 获取code
将code传给后端获取SessionKey、OpenId。
uni.getUserProfile()获取公开信息(头像,昵称等)
/* html 使用的是uni.getUserProfile() 一个普通按钮就可以,
微信基础库2.10.4版本对用户信息相关接口进行了调整,使用 uni.getUserInfo 获取得到的 userInfo 为匿名数据,建议使用 uni.getUserProfile 获取用户信息。
*/
/* js 只有获取code 和获取公开信息两个函数
*/
login() {
let _that = this;
uni.login({
provider: 'weixin',
success: loginRes => {
console.log(loginRes);
_that.code = loginRes.code;
// 2. 将用户登录code传递到后台置换用户SessionKey、OpenId等信息
this.$u.get('/WxOpenData?js_code=' + loginRes.code).then(res => {
if (res.code == 200) {
_that.openId = res.obj;
} else {
uni.showToast({
title: '获取openId失败!',
icon: 'none'
});
setTimeout(function() {
uni.redirectTo({
url: '/pages/login/login'
});
}, 1000);
}
console.log(res);
});
},
fail: () => {
uni.showToast({ title: '获取 code 失败', icon: 'none' });
setTimeout(function() {
uni.redirectTo({
url: '/pages/login/login'
});
}, 1000);
return false;
}
});
return false;
}
wxGetUserInfo() {
let _that = this;
_that.login();
// 1.获取用户的信息
uni.getUserProfile({
desc: '获取微信公开信息',
lang: 'zh_CN',
success: infoRes => {
// console.log(infoRes);
_that.wxPublicInfo = infoRes.userInfo; //保存公开信息
uni.setStorageSync('touristWxPublicInfo', _that.wxPublicInfo); //暂时保存为游客公开信息
if (_that.openId != '') {
_that.theStep = 2; //公开信息授权成功后,进行手机号授权
}
},
fail: err => {
uni.showToast({ title: '获取用户公开信息失败', icon: 'none' });
// setTimeout(function(){
// uni.redirectTo({
// url:'/pages/login/login'
// })
// },1000)
}
});
return false;
},
二. 获取手机号
在获取完openid的前提下使用 getPhoneNumber获取到加密的手机号,传给后端解密即可。
// html
// js
// 获取手机号
getPhoneNumber(e) {
const _that = this;
if (e.detail.errMsg == 'getPhoneNumber:ok') {
// 允许授权,获取手机号
// 传给后端解密,包括基本信息传给后端保存()
this.$u
.post('/decodeUserInfo', {
encrypted: e.detail.encryptedData,
iv: e.detail.iv,
openid: _that.openId,
avatarUrl: _that.wxPublicInfo.avatarUrl, //头像
city: _that.wxPublicInfo.city, //城市
country: _that.wxPublicInfo.country, //国家
nickName: _that.wxPublicInfo.nickName, //昵称
province: _that.wxPublicInfo.province //省
})
.then(res => {
if (res.code == 200) {
var phone = res.obj; //解析好的手机号
// 登录- 获取token
this.$u
.post('/memberLogin', {
account: phone,
password: '123456'
})
.then(memberLoginRes => {
console.log(memberLoginRes);
if (memberLoginRes.code == 200 && memberLoginRes.obj) {
uni.setStorageSync('pk_token', memberLoginRes.obj.tokenHead + ' ' + memberLoginRes.obj.token);
// 获取基本信息
this.$u.get('/info').then(suc => {
if (suc.code == 200) {
uni.setStorageSync('userInfo', suc.obj); //用户基本信息
uni.setStorageSync('openId', _that.openId); //保存openid
uni.setStorageSync('firstAuthorization', true); //登录状态
// 不是游客-删除
uni.removeStorageSync('touristWxPublicInfo');
getApp().globalData.userInfo = suc.obj;
// console.log(getApp().globalData)
uni.redirectTo({
url: '/pagesHome/home/home'
});
}
});
} else if (memberLoginRes.code == 500) {
// 未注册会员
uni.showModal({
title: '温馨提示',
content: '您还不是名子瑜伽会员,可以选择游客模式访问',
success: function(res) {
if (res.confirm) {
uni.redirectTo({
url: '/pages/login/login'
});
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
}
});
} else {
// 解析手机号错误
uni.showToast({
title: '手机号错误',
icon: 'none'
});
}
});
} else {
//拒绝授权后弹出一些提示
uni.showToast({
title: '已拒绝手机号授权登录',
icon: 'none'
});
setTimeout(function() {
uni.redirectTo({
url: '/pages/login/login'
});
}, 1000);
}
},
三. 微信支付
前端将订单信息(openid,商品信息,付款人等)传给后,后端返回拉起支付所需要的参数,前端拉起支付,前端根据支付状态做对应的操作,返回支付状态给后端
var payData=JSON.parse(res.obj.signPackage);//拉起支付所需字段
var orderNumber=res.obj.merchantOrderSn;//订单号
uni.requestPayment({
provider: 'wxpay',
_debug:1,
timeStamp: payData.timeStamp,
nonceStr: payData.nonceStr,
package: payData.package,
signType: payData.signType,
paySign: payData.paySign,
success: function (resPay) {
console.log('success:' + JSON.stringify(resPay));
// var resPay=JSON.parse(resPay).errMsg;
_that.$u.post('/payState',{
orderNumber:orderNumber,//订单号
payState:1,//订单支付状态:1为支付成功,0为预支付,2为支付失败
}).then(resPayState=>{
if(resPayState.code==200){
uni.showToast({
title:'支付成功!',
})
setTimeout(function(){
uni.redirectTo({
url:'/pages/exchangeRecord/exchangeRecord'
});
},1000)
}
})
},
fail: function (err) {
console.log('fail:' + JSON.stringify(err));
uni.showToast({
title:'支付失败!',
icon:'none'
})
setTimeout(function(){
uni.redirectTo({
url:'/pages/exchangeRecord/exchangeRecord'
});
},1000)
}
});
四. 分享
使用onShareAppMessage() 和onShareTimeline() 就可以分享,这两个函数和onLoad()同级
页面中自定义按钮分享需要加 open-type=“share”
//html
// js
onLoad(option) {},
// 分享给朋友
onShareAppMessage(res) {
if (res.from === 'button') {
// 来自页面内分享按钮
console.log(res.target);
}
return {
title: '标题',
path: 'pages/exchangeShop/exchangeShop',
imageUrl: '/static/common/mzlogo.png'
};
},
// 分享到朋友圈
onShareTimeline() {
if (res.from === 'button') {
// 来自页面内分享按钮
console.log(res.target);
}
return {
title: '标题',
path: 'pages/exchangeShop/exchangeShop',
imageUrl: '/static/common/mzlogo.png'
};
},
// css 清除 button 默认样式,
button::after {
border: none;
background-color: none;
}
五. 消息订阅
微信小程序的消息订阅需要先在小程序后台添加消息模板
订阅一次只能发送一次消息
// 弹出消息订阅
newsSubscription() {
// 获取用户的当前设置,判断是否点击了“总是保持以上,不在询问”
uni.getSetting({
withSubscriptions: true, //是否获取用户订阅消息的订阅状态,默认false不返回
success(res) {
if (res.authSetting['scope.subscribeMessage']) {
uni.openSetting({
// 打开设置页
success(resSet) {
console.log(resSet.authSetting);
}
});
} else {
// 用户没有点击“总是保持以上,不再询问”则每次都会调起订阅消息
uni.requestSubscribeMessage({
tmplIds: ['模板id'], //
success(res) {
console.log(res);
if (res['字段'] == 'accept') {
// 字段就是tmplIds模板id
// ....
}
}
});
}
}
});
},