C端小程序
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

219 satır
6.1 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. }
  54. });
  55. },
  56. globalData: {
  57. // token
  58. token: null,
  59. // user openId
  60. openId: null,
  61. // 渠道
  62. sceneAddress: null,
  63. // location info
  64. locationInfo: null,
  65. // 二维码参数
  66. scene: null,
  67. // 支持智慧停车, 用户名下有车
  68. phone: null,
  69. supportCar: false,
  70. parkVendor: 1, // 1: ETCP, 2: TJD
  71. // ETCP token
  72. etcpToken: null,
  73. carLogin: false,
  74. // 当前商场信息
  75. market: {
  76. name: "陕西大悦城"
  77. },
  78. // websocket
  79. socketClient: null,
  80. socketReceiver: function (e) { }, //收到消息回调
  81. },
  82. // 初始化websocket
  83. initSocket: function () {
  84. let that = this;
  85. // socket是否连接
  86. let socketConnected = false;
  87. // 待发送的消息队列
  88. let messageQueue = [];
  89. // 是否断线重连
  90. let reconnect = true;
  91. // 发送消息
  92. function sendSocketMessage(msg) {
  93. // console.log(msg);
  94. // 如果socket已连接则发送消息
  95. if (socketConnected) {
  96. wx.sendSocketMessage({
  97. data: msg
  98. })
  99. } else {
  100. // socket没有连接将消息放入队列中
  101. messageQueue.push(msg);
  102. }
  103. }
  104. // 关闭连接
  105. function close() {
  106. if (socketConnected) {
  107. wx.closeSocket()
  108. socketConnected = false;
  109. }
  110. }
  111. // 符合WebSocket定义的对象
  112. var ws = {
  113. send: sendSocketMessage,
  114. close: close
  115. }
  116. // 创建一个 WebSocket 连接
  117. function connect() {
  118. wx.connectSocket({
  119. url: config.wsurl,
  120. header: {
  121. token: that.globalData.token //从服务端获取一个token,服务端验证token是否允许连接,案例中没做限制
  122. }
  123. })
  124. }
  125. connect();
  126. // 监听 WebSocket 连接打开事件
  127. wx.onSocketOpen(function (res) {
  128. console.log("WebSocket 连接成功")
  129. socketConnected = true;
  130. ws.onopen();
  131. // 连接成功后,将队列中的消息发送出去
  132. let queueLength = messageQueue.length
  133. for (let i = 0; i < queueLength; i++) {
  134. sendSocketMessage(messageQueue.shift())
  135. }
  136. })
  137. // 监听 WebSocket 接受到服务器的消息事件
  138. wx.onSocketMessage(function (res) {
  139. ws.onmessage(res);
  140. })
  141. // 监听 WebSocket 错误事件
  142. wx.onSocketError(function (res) {
  143. console.log("WebSocket 错误事件")
  144. if (!socketConnected) {
  145. // 断线重连
  146. if (reconnect) {
  147. connect();
  148. }
  149. }
  150. })
  151. // 监听 WebSocket 连接关闭事件
  152. wx.onSocketClose(function (res) {
  153. console.log("WebSocket 连接关闭")
  154. socketConnected = false;
  155. // 断线重连
  156. if (reconnect) {
  157. connect();
  158. }
  159. })
  160. const Stomp = require('/utils/stomp.min.js').Stomp;
  161. /**
  162. * 定期发送心跳或检测服务器心跳
  163. * The heart-beating is using window.setInterval() to regularly send heart-beats and/or check server heart-beats.
  164. * 可看stomp.js的源码(195,207,489行),由于小程序没有window对象,所以我们要调用小程序的定时器api实现
  165. */
  166. Stomp.setInterval = function (interval, f) {
  167. return setInterval(f, interval);
  168. };
  169. // 结束定时器的循环调用
  170. Stomp.clearInterval = function (id) {
  171. return clearInterval(id);
  172. };
  173. const stompClient = Stomp.over(ws);
  174. that.globalData.socketClient = stompClient;
  175. stompClient.connect({}, function (callback) {
  176. // 订阅自己的
  177. stompClient.subscribe('/user/' + config.weapp.AppId + '/' + that.globalData.openId + '/message', function (message, headers) {
  178. console.log('收到只发送给我的消息:', message);
  179. that.globalData.socketReceiver(JSON.parse(message.body));
  180. // 通知服务端收到消息
  181. message.ack();
  182. });
  183. stompClient.subscribe('/topic/' + config.weapp.AppId, function (message, headers) {
  184. console.log('收到TOPIC的消息:', message);
  185. that.globalData.socketReceiver(JSON.parse(message.body));
  186. // 通知服务端收到消息
  187. //message.ack();
  188. });
  189. // 向服务端发送消息
  190. stompClient.send("/app/message", {}, JSON.stringify({
  191. 'msg': 'client: ' + that.globalData.openId
  192. }));
  193. })
  194. },
  195. //统一发送消息
  196. sendSocketMessage: function (msg) {
  197. this.globalData.socketClient.send("/app/message", {}, JSON.stringify(msg));
  198. }
  199. });