<view class="wx"> <view class="subtitle">微信快捷登錄</view> <!-- #ifdef MP-WEIXIN --> <text class="iconfont icon-weixin" @tap="wxLogin"></text> <text>微信端</text> <!-- #endif --> <!-- #ifdef H5 || APP-PLUS --> <text class="iconfont icon-weixin" @tap="appLogin"></text> <text>app端</text> <!-- #endif --> </view>
//小程序登錄 begin登錄
// 邏輯:登錄 > 拿到code > 后端通過code獲取sessionKey、openid(unionid)等
wxLogin(e) { let _this = this; uni.login({ provider: 'weixin', success: function(res) { console.log(res); if (res.code) { let code = res.code; //將用戶登錄code傳遞到后台置換用戶SessionKey、OpenId等信息 //...寫用code置換SessionKey、OpenId的接口 // _this.$http.post("/api/user/login", {code:code}) // .then(res => { // let openId= res.openId; // _this.wxSubmit(openId) // }) // .catch(err => { // _this.$ant.toast('登錄失敗') // }); } else { uni.showToast({ title: '登錄失敗!', duration: 2000 }); console.log('登錄失敗!' + res.errMsg) } }, }); }
// app登錄邏輯 app端能直接拿到openId
appLogin() { var that = this; uni.getProvider({ service: 'oauth', success: function(res) { console.log(res.provider); //支持微信、qq和微博等 if (~res.provider.indexOf('weixin')) { uni.login({ provider: 'weixin', success: function(loginRes) { console.log("App微信獲取用戶信息成功", loginRes); // 獲取用戶信息 uni.getUserInfo({ provider: 'weixin', success: function(infoRes) { console.log('-------獲取微信用戶所有-----'); console.log(infoRes.userInfo.openId); console.log(JSON.stringify(infoRes.userInfo)); // 提交信息 that.wxSubmit(infoRes.userInfo.openId) } }); // that.getApploginData(loginRes) //請求登錄接口方法 }, fail: function(res) { console.log("App微信獲取用戶信息失敗", res); } }) } } }); },
記錄時間2021-07-13,親測有效,有用的話,麻煩給點個贊。
