login.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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/index',
  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. requestAPI.userLogin(wxres.code).then(res => {
  38. if (res.statusCode === 401) {
  39. self.setData({
  40. ifUser: false
  41. })
  42. } else {
  43. if (res.data.access_token) {
  44. wx.setStorageSync('token', res.data.access_token);
  45. wx.switchTab({
  46. url: '/pages/sample/index',
  47. })
  48. }
  49. }
  50. })
  51. }
  52. })
  53. },
  54. register: function () {
  55. let self = this
  56. if (this.data.phone.length == 0) {
  57. wx.showToast({
  58. title: '手机不能为空',
  59. icon: 'none',
  60. duration: 3000
  61. })
  62. } else if (!isPoneAvailable(this.data.phone)) {
  63. wx.showToast({
  64. title: '请输入正确的手机号',
  65. icon: 'none',
  66. duration: 3000
  67. })
  68. } else {
  69. requestAPI.getSmsCode(this.data.phone).then(res => {
  70. if (isNaN(res.data.msg)) {
  71. wx.showToast({
  72. title: res.data.msg,
  73. icon: 'none',
  74. duration: 3000
  75. })
  76. } else {
  77. self.setData({
  78. code: res.data.msg
  79. })
  80. requestAPI.getSmsToken(self.data.phone, self.data.code).then(res => {
  81. wx.setStorageSync('token', res.data.access_token)
  82. wx.login({
  83. success(wxres) {
  84. requestAPI.bindOpenId(wxres.code).then(res => {
  85. if (res.data.data === true) {
  86. self.setData({
  87. ifUser: true
  88. })
  89. }
  90. })
  91. },fail(res) {
  92. wx.showToast({
  93. title: '验证失败',
  94. duration: 3000
  95. })
  96. }
  97. })
  98. })
  99. }
  100. })
  101. }
  102. },
  103. getIfExpired() {
  104. requestAPI.getUserInfo().then(res => {
  105. })
  106. }
  107. })