auth.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // component/auth/auth.js
  2. const api = require('../../config/api')
  3. const util = require('../../utils/util.js');
  4. import {getSubOpen} from './api'
  5. Component({
  6. /**
  7. * 页面的初始数据
  8. */
  9. data: {
  10. show: false,
  11. canIUse: wx.canIUse('button.open-type.getUserInfo')
  12. },
  13. attached() {
  14. this.callback = () => {
  15. this.setData({show: !getApp().globalData.loginProps.isLogin})
  16. let pages = getCurrentPages()
  17. let currPage = pages[pages.length - 1].route
  18. if (currPage === 'pages/discover/discover') {
  19. this.setData({bottom: '50px'})
  20. } else {
  21. this.setData({bottom: 0})
  22. }
  23. }
  24. this.callback()
  25. getApp().addLoginListener(this.callback)
  26. getSubOpen()
  27. },
  28. detached() {
  29. getApp().removeLoginListener(this.callback)
  30. },
  31. methods: {
  32. quitHandle: function() {
  33. getApp().setLoginProps(true)
  34. },
  35. getCode: function() {
  36. return new Promise(r => {
  37. wx.login({
  38. success: function(res) {
  39. console.log(res)
  40. if (res.code) {
  41. r(res.code)
  42. }
  43. }
  44. });
  45. })
  46. },
  47. authLogin() {
  48. this.triggerEvent('login')
  49. },
  50. bindGetUserInfo: async function(e) {
  51. let code = await this.getCode()
  52. console.log('******')
  53. console.log(e.detail)
  54. //登录远程服务器
  55. util.request(api.AuthLoginByWeixin, {
  56. code: code,
  57. userInfo: e.detail
  58. }, 'POST', 'application/json').then(res => {
  59. if (res.errno === 0) {
  60. console.log('&&&&&&&')
  61. console.log(res.data)
  62. //存储用户信息
  63. res.data.userInfo.userId = res.data.userId
  64. res.data.userInfo.sessionKey = res.data.sessionKey
  65. console.log('-------', res.data.userInfo)
  66. wx.setStorageSync('userInfo', res.data.userInfo);
  67. wx.setStorageSync('token', res.data.token);
  68. wx.setStorageSync('userId', res.data.userId);
  69. wx.setStorageSync('isLogin', true);
  70. getApp().setLoginProps(true)
  71. this.authLogin()
  72. getSubOpen()
  73. } else {
  74. // util.showErrorToast(res.errmsg)
  75. // wx.showModal({
  76. // title: '提示',
  77. // content: res.errmsg,
  78. // showCancel: false
  79. // });
  80. }
  81. });
  82. },
  83. }
  84. })