httpUtilNoLogin.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const request = require('./WXHttpRequest.js');
  2. const url = require('./const.js');
  3. const util = require('./util.js');
  4. const httpRequestApi = require('./APIClient');
  5. const HOST = url.baseApi;
  6. function genAPIUrl(action) {
  7. return HOST + action;
  8. }
  9. // 登录
  10. function wxLogin(successcallback, failcallback) {
  11. wx.showToast({
  12. title: '加载中...',
  13. icon: 'loading',
  14. duration: 1500,
  15. mask: true
  16. })
  17. wx.login({
  18. success: function (res) {
  19. if (res.code) {
  20. // 获取openid
  21. console.log('code', res.code)
  22. let url = genAPIUrl('wx/user/openId')
  23. let data = {
  24. code: res.code
  25. }
  26. return request.getInstance().url(url).data(data).send().success(successcallback).fail(failcallback);
  27. } else {
  28. console.log('获取用户登录态失败!' + res.errMsg)
  29. }
  30. }
  31. })
  32. }
  33. // 获取原来的 openid 和 session_key
  34. function getOpenidNoLogin(successcallback, failcallback) {
  35. if (wx.getStorageSync('user')) {
  36. successcallback(
  37. wx.getStorageSync('user'),
  38. //分享小程序按钮
  39. wx.showShareMenu({
  40. withShareTicket: true
  41. })
  42. );
  43. return;
  44. }
  45. wxLogin(function (res) {
  46. if (res.data.code == 200) {
  47. let sessionKey = res.data.data.session_key;
  48. let openId = res.data.data.openid;
  49. // successcallback()
  50. // wx.setStorageSync('uid', '111')
  51. let url = genAPIUrl('wx/user/register');
  52. request.getInstance().method('POST').url(url).header({
  53. 'content-type': 'application/x-www-form-urlencoded'
  54. }).data({
  55. openId
  56. }).send().success((res) => {
  57. if (res.data.code === 200) {
  58. wx.setStorageSync('uid', res.data.data.uid)
  59. successcallback(res)
  60. }
  61. }).fail(() => {});
  62. }
  63. }, function (res) {
  64. failcallback(res);
  65. })
  66. }
  67. module.exports = {
  68. getOpenidNoLogin
  69. }