user.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * 用户相关服务
  3. */
  4. const util = require('../utils/util.js');
  5. const api = require('../config/api.js');
  6. /**
  7. * Promise封装wx.checkSession
  8. */
  9. function checkSession() {
  10. return new Promise(function (resolve, reject) {
  11. wx.checkSession({
  12. success: function () {
  13. resolve(true);
  14. },
  15. fail: function () {
  16. reject(false);
  17. }
  18. })
  19. });
  20. }
  21. /**
  22. * Promise封装wx.login
  23. */
  24. function login() {
  25. return new Promise(function (resolve, reject) {
  26. wx.login({
  27. success: function (res) {
  28. if (res.code) {
  29. resolve(res);
  30. } else {
  31. reject(res);
  32. }
  33. },
  34. fail: function (err) {
  35. reject(err);
  36. }
  37. });
  38. });
  39. }
  40. /**
  41. * 调用微信登录
  42. */
  43. function loginByWeixin(userInfo) {
  44. return new Promise(function (resolve, reject) {
  45. return login().then((res) => {
  46. //登录远程服务器
  47. util.request(api.AuthLoginByWeixin, { code: res.code, userInfo: userInfo }, 'POST').then(res => {
  48. if (res.errno === 0) {
  49. //存储用户信息
  50. wx.setStorageSync('userInfo', res.data.userInfo);
  51. wx.setStorageSync('token', res.data.token);
  52. resolve(res);
  53. } else {
  54. reject(res);
  55. }
  56. }).catch((err) => {
  57. reject(err);
  58. });
  59. }).catch((err) => {
  60. reject(err);
  61. })
  62. });
  63. }
  64. /**
  65. * 判断用户是否登录
  66. */
  67. function checkLogin() {
  68. return new Promise(function (resolve, reject) {
  69. if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
  70. checkSession().then(() => {
  71. resolve(true);
  72. }).catch(() => {
  73. reject(false);
  74. });
  75. } else {
  76. reject(false);
  77. }
  78. });
  79. }
  80. module.exports = {
  81. loginByWeixin,
  82. checkLogin,
  83. };