当前位置:   article > 正文

微信原生小程序封装用户登陆

微信原生小程序封装用户登陆
场景:

后端在用户登陆后会返回resfreshToken和token;

open-type是小程序中button的属性之一,合法霍倩倩getUserInfo,引导用户授权,可以从bindgetuserinfo回调中获取到用户信息。button可以指定plain属性,完全去掉样式,跟view类似。

 封装的登陆文件(user.js)
  1. /**
  2. * 用户相关服务
  3. */
  4. /**
  5. * Promise封装wx.checkSession
  6. */
  7. function checkSession() {
  8. return new Promise(function(resolve, reject) {
  9. wx.checkSession({
  10. success: function() {
  11. resolve(true);
  12. },
  13. fail: function() {
  14. reject(false);
  15. }
  16. })
  17. });
  18. }
  19. /**
  20. * Promise封装wx.login
  21. */
  22. function wxlogin() {
  23. return new Promise(function(resolve, reject) {
  24. wx.login({
  25. success: function(res) {
  26. if (res.code) {
  27. resolve(res);
  28. } else {
  29. reject(res);
  30. }
  31. },
  32. fail: function(err) {
  33. reject(err);
  34. }
  35. });
  36. });
  37. }
  38. /**
  39. * 判断用户是否登录
  40. */
  41. function checkIndex(){
  42. console.log(wx.getStorageSync('token'))
  43. if(!wx.getStorageSync('token')){
  44. console.log("11")
  45. wx.navigateTo({
  46. url: 'pages/auth/login/login',
  47. })
  48. console.log("12")
  49. }
  50. }
  51. function checkLogin() {
  52. return new Promise(function(resolve, reject) {
  53. if (wx.getStorageSync('token')) {
  54. checkSession().then(() => {
  55. resolve(true);
  56. }).catch(() => {
  57. reject(false);
  58. });
  59. } else {
  60. console.log("跳转")
  61. wx.navigateTo({
  62. url: '../pages/auth/login/login',
  63. })
  64. reject(false);
  65. }
  66. });
  67. }
  68. module.exports = {
  69. checkLogin,
  70. checkIndex,
  71. wxlogin
  72. };
封装微信的网络请求(util.js)
  1. /**
  2. * 封封微信的的request
  3. */
  4. function requestForCheckLincense(url, data = {}, method = 'GET') {
  5. return new Promise(function (resolve, reject) {
  6. wx.request({
  7. url: url,
  8. data: data,
  9. method: method,
  10. header: {
  11. 'Content-Type': 'application/json',
  12. Authorization: 'dowsure' + wx.getStorageSync('token').token
  13. },
  14. success: function (res) {
  15. console.log('response--', res)
  16. res = res.data
  17. if (res.code == 200 || res.code == 0) {
  18. resolve(res)
  19. } else {
  20. if (res.code == 401) {
  21. showErrorToast('登录已失效,请重新登录')
  22. wx.removeStorageSync('token')
  23. // 登录失效
  24. // 切换到登录页面
  25. wx.reLaunch({
  26. url: '/pages/commonLoan/commonIndex/commonIndex'
  27. })
  28. } else {
  29. res.message = res.message || res.msg || '网络异常'
  30. showErrorToast(res.message)
  31. reject(res)
  32. }
  33. }
  34. },
  35. fail: function (err) {
  36. reject(err)
  37. }
  38. })
  39. })
  40. }
代码使用 
  1. 点击登陆按钮
  2. goLogin() {
  3. var refreshToken = wx.getStorageSync('refreshToken')
  4. if (refreshToken) {
  5. // 如果登陆过,刷新token;
  6. this.rToken(refreshToken)
  7. } else {
  8. this.setData({
  9. showLogin: true
  10. })
  11. }
  12. },
  13. 点击自己写的按钮然后打开登陆的弹窗
  14. <van-popup
  15. position="bottom"
  16. custom-style="height:25%;background:linear-gradient(95deg, #F8FCFF -0.03%, #EDF5FF 64.44%, #F8FCFF 133.06%);"
  17. round
  18. show="{{ showLogin }}"
  19. bind:close="onLoginClose"
  20. >
  21. 微信提供的open-type
  22. <button open-type="getPhoneNumber" class="wx-login-btn wx-btn" bindgetphonenumber="wxLogin">
  23. 手机号快捷登录
  24. </button>
  25. <checkbox-group
  26. bindchange="checkboxChange"
  27. class="certificate"
  28. style="width: 90%; margin: 24rpx 40rpx"
  29. >
  30. <checkbox checked="{{isagree}}" class="checkbox" value="{{isagree}}"></checkbox>
  31. <view class="certificate-txt"
  32. >阅读并同意<text class="txt" bindtap="openUrl" data-num="lending003"
  33. >《风险提示与免责声明》</text
  34. >、<text class="txt" bindtap="openUrl" data-num="lending008"
  35. >《服务协议》</text
  36. ></view
  37. >
  38. </checkbox-group>
  39. </van-popup>
  1. //登录
  2. wxLogin(e) {
  3. if (e.detail.errMsg && e.detail.errMsg.indexOf('user deny') !== -1) {
  4. return
  5. }
  6. if (!this.data.isagree) {
  7. return util.showErrorToast('请勾选协议')
  8. }
  9. wx.getUserInfo({
  10. desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
  11. success: res => {
  12. wx.setStorage({
  13. key: 'userInfo',
  14. data: {
  15. nickName: res.userInfo.nickName,
  16. avatarUrl: res.userInfo.avatarUrl
  17. }
  18. })
  19. this.doLogin(e.detail)
  20. },
  21. fail: () => {
  22. util.showErrorToast('微信登录失败')
  23. }
  24. })
  25. },
  1. doLogin: function (obj) {
  2. user
  3. .checkLogin()
  4. .then(() => {
  5. this.login(obj)
  6. })
  7. .catch(() => {
  8. this.login(obj)
  9. })
  10. },
  11. // 微信授权一键登录
  12. login: function (obj) {
  13. const _this = this
  14. wx.showLoading()
  15. util
  16. .request(
  17. login.getPhoneNum, {
  18. code: obj.code,
  19. source: '传入值' || '默认值',
  20. sourceCode: '传入值' || '默认值'
  21. },
  22. 'GET'
  23. )
  24. .then(res => {
  25. wx.setStorage({
  26. key: 'token',
  27. data: {
  28. token: res.token.token,
  29. phone: res.username
  30. },
  31. success: function () {
  32. 自己的操作
  33. // 获取code,以便后台获取唯一的openID
  34. _this.sendCodeForOpenId()
  35. }
  36. })
  37. if (res.refreshToken) {
  38. wx.setStorage({
  39. key: 'refreshToken',
  40. data: res.refreshToken
  41. })
  42. }
  43. })
  44. .catch(err => {})
  45. },
  46. // 获取code,以便后台获取唯一的openID
  47. async sendCodeForOpenId() {
  48. user.wxlogin().then(result => {
  49. util
  50. .request(
  51. login.setBackCodeForOpenId, {
  52. openId: result.code
  53. },
  54. 'GET'
  55. )
  56. .then(res => {
  57. this.setData({
  58. showLogin: false
  59. })
  60. 登陆后续自己的操作
  61. })
  62. })
  63. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/453558
推荐阅读
相关标签
  

闽ICP备14008679号