loginSchedule.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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(
  31. wx.getStorageSync('user'),
  32. //分享小程序按钮
  33. wx.showShareMenu({
  34. withShareTicket: true
  35. })
  36. );
  37. return;
  38. }
  39. wxLogin(function(res) {
  40. //console.log('获取sessionKey等内容'+JSON.stringify(res.data));
  41. let sessionKey = res.data.session_key;
  42. //登录
  43. getLoginSchedule(sessionKey, successcallback, failcallback);
  44. },function(res) {
  45. failcallback(res);
  46. })
  47. }
  48. //登录
  49. function getLoginSchedule(sessionKey, successcallback, failcallback) {
  50. //获取个人信息
  51. wx.getUserInfo({
  52. success: function (res) {
  53. let userInfo = res.userInfo
  54. let url = genAPIUrl('wx/ucenter/user/loginRegist');
  55. const userData = {
  56. encryptedData: res.encryptedData,
  57. sessionKey: sessionKey,
  58. iv: res.iv,
  59. dist: '1133',
  60. headimgurl: userInfo.avatarUrl
  61. }
  62. request.getInstance().url(url).data(userData).method('GET').send().success(res => {
  63. wx.hideToast()
  64. wx.showToast({
  65. title: '登录成功',
  66. icon: 'success',
  67. duration: 1500
  68. })
  69. wx.setStorageSync('uid', res.data.data.uid)
  70. wx.setStorageSync('user', res)
  71. successcallback(res)
  72. });
  73. },
  74. fail: function(res) {
  75. failcallback(res)
  76. }
  77. })
  78. //
  79. }
  80. module.exports = {
  81. getOpenidSessionKey
  82. }