httpUtil.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const request = require('./WXHttpRequest.js');
  2. const url = require('./const.js');
  3. const util = require('./util.js');
  4. const HOST = url.baseApi;
  5. function genAPIUrl(action) {
  6. return HOST + action;
  7. }
  8. // 登录
  9. function wxLogin(successcallback, failcallback) {
  10. wx.showToast({
  11. title: '登录中...',
  12. icon: 'loading',
  13. duration: 1500
  14. })
  15. wx.login({
  16. success: function(res) {
  17. if (res.code) {
  18. // 获取openid
  19. let url = genAPIUrl('wx/user/openId')
  20. let data = { code: res.code }
  21. return request.getInstance().url(url).data(data).send().success(successcallback).fail(failcallback);
  22. } else {
  23. console.log('获取用户登录态失败!' + res.errMsg)
  24. }
  25. }
  26. })
  27. }
  28. //登录
  29. function getLoginSchedule(sessionKey, openId, successcallback, failcallback) {
  30. wx.getSetting({
  31. success: function(res) {
  32. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  33. wx.getUserInfo({
  34. withCredentials: true,
  35. success: function (res) {
  36. let url = genAPIUrl('wx/user/loginRegist');
  37. const userData = {
  38. encryptedData: res.encryptedData,
  39. sessionKey: sessionKey,
  40. iv: res.iv
  41. }
  42. request.getInstance().url(url).header({
  43. "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
  44. }).data(userData).method('POST').send().success(res => {
  45. wx.hideToast()
  46. wx.showToast({
  47. title: '登录成功',
  48. icon: 'success',
  49. duration: 1500
  50. })
  51. wx.setStorageSync('uid', res.data.data.data.uid)
  52. wx.setStorageSync('user', res)
  53. successcallback(res)
  54. });
  55. },
  56. fail: function(res) {
  57. failcallback(res)
  58. }
  59. })
  60. }
  61. })
  62. }
  63. // 获取原来的 openid 和 session_key
  64. function getOpenidSessionKey(successcallback, failcallback) {
  65. if (wx.getStorageSync('user')) {
  66. successcallback(
  67. wx.getStorageSync('user'),
  68. //分享小程序按钮
  69. wx.showShareMenu({
  70. withShareTicket: true
  71. })
  72. );
  73. return;
  74. }
  75. wxLogin(function(res) {
  76. if(res.data.code == 200){
  77. let sessionKey = res.data.data.session_key;
  78. let openId = res.data.data.openid;
  79. getLoginSchedule(sessionKey, openId, successcallback, failcallback);
  80. }
  81. },function(res) {
  82. failcallback(res);
  83. })
  84. }
  85. module.exports = {
  86. getOpenidSessionKey
  87. }