httputil.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. }
  62. request.getInstance().header({
  63. 'content-type': 'application/x-www-form-urlencoded'
  64. }).url(url).data(userData).method('POST').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.id)
  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. }