loginSchedule.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const request = require('./WXHttpRequest.js');
  2. const url = require('./const.js');
  3. const HOST = url.apiUrl;
  4. function genAPIUrl(action) {
  5. return HOST + action;
  6. }
  7. // 登录
  8. function wxLogin(successcallback, failcallback) {
  9. wx.showToast({
  10. title: '登录中...',
  11. icon: 'loading',
  12. duration: 1500
  13. })
  14. wx.login({
  15. success: function(res) {
  16. if (res.code) {
  17. // 获取openid
  18. let url = genAPIUrl('wx/ucenter/openId')
  19. let data = { code: res.code }
  20. return request.getInstance().url(url).data(data).send().success(successcallback).fail(failcallback);
  21. } else {
  22. console.log('获取用户登录态失败!' + res.errMsg)
  23. }
  24. }
  25. })
  26. }
  27. // 获取 openid 和 session_key
  28. function getOpenidSessionKey(successcallback, failcallback) {
  29. if (wx.getStorageSync('user')) {
  30. successcallback(wx.getStorageSync('user'));
  31. return;
  32. }
  33. wxLogin(function(res) {
  34. //console.log('获取sessionKey等内容'+JSON.stringify(res.data));
  35. let sessionKey = res.data.session_key;
  36. //登录
  37. getLoginSchedule(sessionKey, successcallback, failcallback);
  38. },function(res) {
  39. failcallback(res);
  40. })
  41. }
  42. //登录
  43. function getLoginSchedule(sessionKey, successcallback, failcallback) {
  44. //获取个人信息
  45. wx.getUserInfo({
  46. success: function (res) {
  47. let userInfo = res.userInfo
  48. let url = genAPIUrl('wx/ucenter/user/loginRegist');
  49. const userData = {
  50. encryptedData: res.encryptedData,
  51. sessionKey: sessionKey,
  52. iv: res.iv,
  53. dist: '1133',
  54. headimgurl: userInfo.avatarUrl
  55. }
  56. request.getInstance().url(url).data(userData).method('GET').send().success(res => {
  57. wx.hideToast()
  58. wx.showToast({
  59. title: '登录成功',
  60. icon: 'success',
  61. duration: 1500
  62. })
  63. wx.setStorageSync('uid', res.data.data.uid)
  64. wx.setStorageSync('user', res)
  65. successcallback(res)
  66. });
  67. },
  68. fail: function(res) {
  69. failcallback(res)
  70. }
  71. })
  72. }
  73. module.exports = {
  74. getOpenidSessionKey
  75. }