login.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import * as requestAPI from '../../models/dataModel'
  2. import {
  3. isPoneAvailable
  4. } from '../../utils/util'
  5. Page({
  6. data: {
  7. phone: '',
  8. success: false,
  9. code: '',
  10. ifUser: true
  11. },
  12. onLoad() {
  13. if(wx.getStorageSync('token')) {
  14. this.getIfExpired()
  15. wx.switchTab({
  16. url: '/pages/sample/sample',
  17. })
  18. }
  19. },
  20. // 获取手机号号
  21. phoneInput: function (e) {
  22. this.setData({
  23. phone: e.detail.value
  24. })
  25. },
  26. // 获取验证码
  27. codeInput: function (e) {
  28. this.setData({
  29. code: e.detail.value
  30. })
  31. },
  32. // 登录
  33. login: function () {
  34. var self = this
  35. wx.login({
  36. success(wxres) {
  37. console.log(wxres)
  38. requestAPI.userLogin(wxres.code).then(res => {
  39. console.log(res)
  40. if (res.statusCode === 401) {
  41. self.setData({
  42. ifUser: false
  43. })
  44. } else {
  45. if (res.data.access_token) {
  46. wx.setStorageSync('token', res.data.access_token);
  47. wx.switchTab({
  48. url: '/pages/sample/sample',
  49. })
  50. }
  51. }
  52. })
  53. }
  54. })
  55. },
  56. register: function () {
  57. let self = this
  58. if (this.data.phone.length == 0) {
  59. wx.showToast({
  60. title: '手机不能为空',
  61. icon: 'none',
  62. duration: 3000
  63. })
  64. } else if (!isPoneAvailable(this.data.phone)) {
  65. wx.showToast({
  66. title: '请输入正确的手机号',
  67. icon: 'none',
  68. duration: 3000
  69. })
  70. } else {
  71. requestAPI.getSmsCode(this.data.phone).then(res => {
  72. if (isNaN(res.data.msg)) {
  73. wx.showToast({
  74. title: res.data.msg,
  75. icon: 'none',
  76. duration: 3000
  77. })
  78. } else {
  79. self.setData({
  80. code: res.data.msg
  81. })
  82. requestAPI.getSmsToken(self.data.phone, self.data.code).then(res => {
  83. wx.setStorageSync('token', res.data.access_token)
  84. wx.login({
  85. success(wxres) {
  86. console.log(wxres)
  87. requestAPI.bindOpenId(wxres.code).then(res => {
  88. if (res.data.data === true) {
  89. self.setData({
  90. ifUser: true
  91. })
  92. }
  93. })
  94. },fail(res) {
  95. wx.showToast({
  96. title: '验证失败',
  97. duration: 3000
  98. })
  99. }
  100. })
  101. })
  102. }
  103. })
  104. }
  105. },
  106. getIfExpired() {
  107. requestAPI.getUserInfo().then(res => {
  108. })
  109. }
  110. })