原生小程序实现登录授权与封装统一调用接口 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

原生小程序实现登录授权与封装统一调用接口

发表时间:2021-1-5

发布人:葵宇科技

浏览次数:51

一。登录思路

先通过 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
          })
        }
      }
    })
  }

相关案例查看更多