loginSchedule.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 = JSON.parse(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. wx.getSetting({
  51. success: function(res) {
  52. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  53. wx.getUserInfo({
  54. success: function (res) {
  55. let userInfo = res.userInfo
  56. let url = genAPIUrl('wx/ucenter/user/loginRegist');
  57. const userData = {
  58. encryptedData: res.encryptedData,
  59. sessionKey: sessionKey,
  60. iv: res.iv,
  61. dist: '1133',
  62. headimgurl: userInfo.avatarUrl
  63. }
  64. request.getInstance().url(url).data(userData).method('GET').send().success(res => {
  65. wx.hideToast()
  66. wx.showToast({
  67. title: '登录成功',
  68. icon: 'success',
  69. duration: 1500
  70. })
  71. wx.setStorageSync('uid', res.data.data.uid)
  72. wx.setStorageSync('user', res)
  73. successcallback(res)
  74. });
  75. },
  76. fail: function(res) {
  77. failcallback(res)
  78. }
  79. })
  80. }
  81. })
  82. }
  83. module.exports = {
  84. getOpenidSessionKey
  85. }