httputil.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const request = require('./httpRequest.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/user/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. if(res.statusCode == 200){
  41. let sessionKey = JSON.parse(res.data).session_key;
  42. getLoginSchedule(sessionKey, successcallback, failcallback);
  43. }
  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. withCredentials: true,
  55. success: function (res) {
  56. let url = genAPIUrl('wx/user');
  57. const userData = {
  58. encryptedData: res.encryptedData,
  59. sessionKey: sessionKey,
  60. iv: res.iv,
  61. code: wx.getStorageSync('uid') ? wx.getStorageSync('uid') : ''
  62. }
  63. request.getInstance().header({
  64. 'content-type': 'application/x-www-form-urlencoded'
  65. }).url(url).data(userData).method('POST').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.id)
  73. wx.setStorageSync('user', res)
  74. successcallback(res)
  75. });
  76. },
  77. fail: function(res) {
  78. failcallback(res)
  79. }
  80. })
  81. }
  82. })
  83. }
  84. module.exports = {
  85. getOpenidSessionKey
  86. }