C端小程序
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

224 行
6.2 KiB

  1. let config = require("./config/config.js");
  2. const Http = require("./utils/HttpBasics");
  3. App({
  4. data: {},
  5. onLaunch: function (options) {
  6. console.log("onUnload ")
  7. var that = this;
  8. that.globalData.sceneAddress = options.scene;
  9. if (wx.canIUse('getUpdateManager')) {
  10. const updateManager = wx.getUpdateManager()
  11. updateManager.onCheckForUpdate(function (res) {
  12. console.log('onCheckForUpdate====', res)
  13. // 请求完新版本信息的回调
  14. if (res.hasUpdate) {
  15. console.log('res.hasUpdate====')
  16. updateManager.onUpdateReady(function () {
  17. wx.showModal({
  18. title: '更新提示',
  19. content: '新版本已经准备好,是否重启应用?',
  20. success: function (res) {
  21. console.log('success====', res)
  22. // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
  23. if (res.confirm) {
  24. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  25. updateManager.applyUpdate()
  26. }
  27. }
  28. })
  29. })
  30. updateManager.onUpdateFailed(function () {
  31. // 新的版本下载失败
  32. wx.showModal({
  33. title: '已经有新版本了哟~',
  34. content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~'
  35. })
  36. })
  37. }
  38. })
  39. }
  40. },
  41. /**
  42. * 获取地址位置信息
  43. */
  44. getLocation: function () {
  45. var that = this
  46. wx.getLocation({
  47. type: "wgs84",
  48. success: function (res) {
  49. that.globalData.locationInfo = res;
  50. },
  51. fail: error => {
  52. console.log(error);
  53. wx.showModal({
  54. title:'提示',
  55. content: error.errMsg,
  56. showCancel:false
  57. })
  58. }
  59. });
  60. },
  61. globalData: {
  62. // token
  63. token: null,
  64. // user openId
  65. openId: null,
  66. // 渠道
  67. sceneAddress: null,
  68. // location info
  69. locationInfo: null,
  70. // 二维码参数
  71. scene: null,
  72. // 支持智慧停车, 用户名下有车
  73. phone: null,
  74. supportCar: false,
  75. parkVendor: 1, // 1: ETCP, 2: TJD
  76. // ETCP token
  77. etcpToken: null,
  78. carLogin: false,
  79. // 当前商场信息
  80. market: {
  81. name: "陕西大悦城"
  82. },
  83. // websocket
  84. socketClient: null,
  85. socketReceiver: function (e) { }, //收到消息回调
  86. },
  87. // 初始化websocket
  88. initSocket: function () {
  89. let that = this;
  90. // socket是否连接
  91. let socketConnected = false;
  92. // 待发送的消息队列
  93. let messageQueue = [];
  94. // 是否断线重连
  95. let reconnect = true;
  96. // 发送消息
  97. function sendSocketMessage(msg) {
  98. // console.log(msg);
  99. // 如果socket已连接则发送消息
  100. if (socketConnected) {
  101. wx.sendSocketMessage({
  102. data: msg
  103. })
  104. } else {
  105. // socket没有连接将消息放入队列中
  106. messageQueue.push(msg);
  107. }
  108. }
  109. // 关闭连接
  110. function close() {
  111. if (socketConnected) {
  112. wx.closeSocket()
  113. socketConnected = false;
  114. }
  115. }
  116. // 符合WebSocket定义的对象
  117. var ws = {
  118. send: sendSocketMessage,
  119. close: close
  120. }
  121. // 创建一个 WebSocket 连接
  122. function connect() {
  123. wx.connectSocket({
  124. url: config.wsurl,
  125. header: {
  126. token: that.globalData.token //从服务端获取一个token,服务端验证token是否允许连接,案例中没做限制
  127. }
  128. })
  129. }
  130. connect();
  131. // 监听 WebSocket 连接打开事件
  132. wx.onSocketOpen(function (res) {
  133. console.log("WebSocket 连接成功")
  134. socketConnected = true;
  135. ws.onopen();
  136. // 连接成功后,将队列中的消息发送出去
  137. let queueLength = messageQueue.length
  138. for (let i = 0; i < queueLength; i++) {
  139. sendSocketMessage(messageQueue.shift())
  140. }
  141. })
  142. // 监听 WebSocket 接受到服务器的消息事件
  143. wx.onSocketMessage(function (res) {
  144. ws.onmessage(res);
  145. })
  146. // 监听 WebSocket 错误事件
  147. wx.onSocketError(function (res) {
  148. console.log("WebSocket 错误事件")
  149. if (!socketConnected) {
  150. // 断线重连
  151. if (reconnect) {
  152. connect();
  153. }
  154. }
  155. })
  156. // 监听 WebSocket 连接关闭事件
  157. wx.onSocketClose(function (res) {
  158. console.log("WebSocket 连接关闭")
  159. socketConnected = false;
  160. // 断线重连
  161. if (reconnect) {
  162. connect();
  163. }
  164. })
  165. const Stomp = require('/utils/stomp.min.js').Stomp;
  166. /**
  167. * 定期发送心跳或检测服务器心跳
  168. * The heart-beating is using window.setInterval() to regularly send heart-beats and/or check server heart-beats.
  169. * 可看stomp.js的源码(195,207,489行),由于小程序没有window对象,所以我们要调用小程序的定时器api实现
  170. */
  171. Stomp.setInterval = function (interval, f) {
  172. return setInterval(f, interval);
  173. };
  174. // 结束定时器的循环调用
  175. Stomp.clearInterval = function (id) {
  176. return clearInterval(id);
  177. };
  178. const stompClient = Stomp.over(ws);
  179. that.globalData.socketClient = stompClient;
  180. stompClient.connect({}, function (callback) {
  181. // 订阅自己的
  182. stompClient.subscribe('/user/' + config.weapp.AppId + '/' + that.globalData.openId + '/message', function (message, headers) {
  183. console.log('收到只发送给我的消息:', message);
  184. that.globalData.socketReceiver(JSON.parse(message.body));
  185. // 通知服务端收到消息
  186. message.ack();
  187. });
  188. stompClient.subscribe('/topic/' + config.weapp.AppId, function (message, headers) {
  189. console.log('收到TOPIC的消息:', message);
  190. that.globalData.socketReceiver(JSON.parse(message.body));
  191. // 通知服务端收到消息
  192. //message.ack();
  193. });
  194. // 向服务端发送消息
  195. stompClient.send("/app/message", {}, JSON.stringify({
  196. 'msg': 'client: ' + that.globalData.openId
  197. }));
  198. })
  199. },
  200. //统一发送消息
  201. sendSocketMessage: function (msg) {
  202. this.globalData.socketClient.send("/app/message", {}, JSON.stringify(msg));
  203. }
  204. });