原生小程序实现登录授权与封装统一调用接口
作者:互联网
一。登录思路
先通过 wx.login 返回 res.code 到后台接口换取 openId, sessionKey, unionId。然后通过 wx.getUserInfo 获取用户信息
如果要获取用户敏感信息则要 wx.getUserInfo 返回的数据传到后台进行解析(我这边是用大佬封装好的api进行解析 )。
二。代码
1。小程序封装统一请求接口
function Request(url, param, method, isJson) { const resUrl = wx.getStorageSync('url') + url; return new Promise((resolve, reject) => { wx.request({ url: resUrl, data: param, header: { 'content-type': isJson ? 'application/json' : 'application/x-www-form-urlencoded' }, method: method, dataType: 'json', responseType: 'text', success: function (res) { // console.log("返回结果------") // console.log(res) resolve(res.data) }, fail: function (err) { // console.log("请求失败:" + err.errMsg) wx.showToast({ title: '请求失败', icon: 'none', duration: 2000, mask: true }) } }) }).then((resData) => { return resData; }) } module.exports = { Request: Request } 2。创建一个api包专门区别放调用后台接口,我这个是api包里的user.js const requests = require("../utils/request.js") module.exports = { // 登录 wxLogin: (data) => { return requests.Request("/wx/login/wx-login.json", { jsCode: data }, 'post', true); },//获取用户信息 getUserInfo: (data) => { return requests.Request("/wx/login/get-user-info.json", data, 'post', true); },
//获取用户手机号 getUserPhone: (data) => { return requests.Request("/wx/login/get-user-phone.json", data, 'post', true); } } 3.修改下app.js const userRequest = require("/api/user.js") App({ onLaunch: function () { // 展示本地存储能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs)
wx.setStorageSync('url', "http://localhost:8087");
this.getUserInfo(); }, onShow() { }, getUserInfo() { let that = this; // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId userRequest.wxLogin(res.code).then((res) => { if (res.code === "SUCCESS") { wx.setStorageSync('sessionKey', res.data.sessionKey); that.globalData.userInfo = res.data.wxUser; // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (that.userInfoReadyCallback) { that.userInfoReadyCallback(res.data.wxUser) } } else { wx.showToast({ title: '登录失败', icon: 'none', duration: 2000, mask: true }) } }); } }) }, globalData: { userInfo: null } }) 4.别的页面调用 onLoad: function () { let that = this; wx.getSetting({ success: function (res) { if (res.authSetting['scope.userInfo']) { //用户授权了 that.setData({ isShowAuth: false }) that.initData(); } else { //用户还没授权,弹出授权窗 that.setData({ isShowAuth: true }) } } }) } 5.
标签:原生,function,getUserInfo,封装,程序实现,res,login,data,wx 来源: https://www.cnblogs.com/GGDong/p/13816505.html