loginSchedule.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. if (res.authSetting['scope.userInfo']) {
  53. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  54. wx.getUserInfo({
  55. success: function (res) {
  56. let userInfo = res.userInfo
  57. let url = genAPIUrl('wx/ucenter/user/loginRegist');
  58. const userData = {
  59. encryptedData: res.encryptedData,
  60. sessionKey: sessionKey,
  61. iv: res.iv,
  62. dist: '1133',
  63. headimgurl: userInfo.avatarUrl
  64. }
  65. request.getInstance().url(url).data(userData).method('GET').send().success(res => {
  66. wx.hideToast()
  67. wx.showToast({
  68. title: '登录成功',
  69. icon: 'success',
  70. duration: 1500
  71. })
  72. wx.setStorageSync('uid', res.data.data.uid)
  73. wx.setStorageSync('user', res)
  74. successcallback(res)
  75. });
  76. },
  77. fail: function(res) {
  78. failcallback(res)
  79. }
  80. })
  81. } else {
  82. //没有授权提示用户进行授权
  83. wx.showModal({
  84. title: '提示',
  85. content: '需要获取您的公开信息(昵称、头像等),请从点击授权按钮,允许授权后可正常使用',
  86. showCancel: false,
  87. success: function (res) {
  88. if (res.confirm) {
  89. console.log('用户点击确定')
  90. } else if (res.cancel) {
  91. console.log('用户点击取消')
  92. }
  93. }
  94. })
  95. }
  96. }
  97. })
  98. }
  99. module.exports = {
  100. getOpenidSessionKey
  101. }