小程式實現授權完整流程
阿新 • • 發佈:2018-12-15
小程式html頁面
<view class="container2"> <view style='width:100%;padding-left:30rpx;font-size: 28rpx;margin-top:30rpx;' class="item">1、同意當前小程式獲取我的微信頭像;</view> <view style='width:100%;padding-left:30rpx;font-size: 28rpx;margin-top:30rpx;' class="item">2、同意當前小程式獲取我的微信暱稱等其他資訊;</view> <button open-type="getUserInfo" bindgetuserinfo="getInfo" class="save-btn">授權登入</button> </view>
小程式js頁面
const util = require('../../utils/util.js'); Page({ data: { }, onLoad: function (options) { }, getInfo(e){ if(!e.detail.userInfo){ wx.showModal({ title: '提示', content: '您拒絕了授權部分功能無法使用', showCancel: false }) return; }else{ wx.setStorageSync('userInfo', e.detail.userInfo); this.login() } }, login(){ let token = wx.getStorageSync('token'); console.log(token) let tokenStr = util.baseApi2 +'/user/check-token'; let loginStr = util.baseApi2+'user/wxapp/login'; let that = this; if(token){ util.fetchData2(tokenStr,{token}).then((res)=>{ if(res.code!=0){ wx.removeStorageSync('token'); that.login(); }else{ wx.navigateBack({}); } }) }else{ wx.login({ success: (res)=>{ util.fetchData2(loginStr,{code: res.code,type: 2}).then((data)=>{ console.log(data) if(data.code==1000){ that.register() }else if(data.code!=0){ wx.showModal({ title: '提示', content: '請求出錯', showCancel: false }) return; }else{ wx.setStorageSync('token', data.data.token); wx.setStorageSync('uid', data.data.uid); wx.navigateBack({ }) } }) } }) } }, register(){ let that = this; let regStr = util.baseApi2+'/user/wxapp/register/complex'; wx.login({ success: (res)=>{ let code = res.code; wx.getUserInfo({ success: (data)=>{ let iv = data.iv; let encryptedData = data.encryptedData; util.fetchData2(regStr,{ code, iv, encryptedData }).then((res)=>{ that.login(); }) } }) } }) } })
注意部分介面來自於api工廠