btnAuth.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const util = require('../../../utils/util.js');
  2. const api = require('../../../config/api.js');
  3. //获取应用实例
  4. const app = getApp()
  5. Page({
  6. data: {
  7. canIUseGetUserProfile: false,
  8. navUrl: '',
  9. code: ''
  10. },
  11. onLoad: function (options) {
  12. let that = this;
  13. if (wx.getUserProfile) {
  14. this.setData({
  15. canIUseGetUserProfile: true
  16. })
  17. }
  18. if (wx.getStorageSync("navUrl")) {
  19. that.setData({
  20. navUrl: wx.getStorageSync("navUrl")
  21. })
  22. } else {
  23. that.setData({
  24. navUrl: '/pages/index/index'
  25. })
  26. }
  27. wx.login({
  28. success: function (res) {
  29. if (res.code) {
  30. that.setData({
  31. code: res.code
  32. })
  33. }
  34. }
  35. });
  36. },
  37. getUserProfile() {
  38. // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
  39. // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
  40. wx.getUserProfile({
  41. desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
  42. success: (resp) => {
  43. //登录远程服务器
  44. this.loginByWeixin(resp)
  45. }
  46. })
  47. },
  48. bindGetUserInfo: function (e) {
  49. //登录远程服务器
  50. this.loginByWeixin(e.detail)
  51. },
  52. loginByWeixin: function (userInfo) {
  53. let that = this;
  54. if (that.data.code) {
  55. util.request(api.AuthLoginByWeixin, {
  56. code: that.data.code,
  57. userInfo: userInfo
  58. }, 'POST', 'application/json').then(res => {
  59. if (res.errno === 0) {
  60. //存储用户信息
  61. wx.setStorageSync('userInfo', res.data.userInfo);
  62. wx.setStorageSync('token', res.data.token);
  63. wx.setStorageSync('userId', res.data.userId);
  64. } else {
  65. // util.showErrorToast(res.errmsg)
  66. wx.showModal({
  67. title: '提示',
  68. content: res.errmsg,
  69. showCancel: false
  70. });
  71. }
  72. });
  73. }
  74. if (that.data.navUrl && that.data.navUrl == '/pages/index/index') {
  75. wx.switchTab({
  76. url: that.data.navUrl,
  77. })
  78. } else if (that.data.navUrl) {
  79. wx.redirectTo({
  80. url: that.data.navUrl,
  81. })
  82. }
  83. },
  84. onReady: function () {
  85. // 页面渲染完成
  86. },
  87. onShow: function () {
  88. // 页面显示
  89. },
  90. onHide: function () {
  91. // 页面隐藏
  92. },
  93. onUnload: function () {
  94. // 页面关闭
  95. }
  96. })