httpUtil.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. console.log(res)
  54. successcallback(res)
  55. });
  56. },
  57. fail: function(res) {
  58. failcallback(res)
  59. }
  60. })
  61. }
  62. })
  63. }
  64. // 获取原来的 openid 和 session_key
  65. function getOpenidSessionKey(successcallback, failcallback) {
  66. if (wx.getStorageSync('user')) {
  67. successcallback(
  68. wx.getStorageSync('user'),
  69. //分享小程序按钮
  70. wx.showShareMenu({
  71. withShareTicket: true
  72. })
  73. );
  74. return;
  75. }
  76. wxLogin(function(res) {
  77. if(res.data.code == 200){
  78. let sessionKey = res.data.data.session_key;
  79. let openId = res.data.data.openid;
  80. getLoginSchedule(sessionKey, openId, successcallback, failcallback);
  81. }
  82. },function(res) {
  83. failcallback(res);
  84. })
  85. }
  86. module.exports = {
  87. getOpenidSessionKey
  88. }