C端小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
7.2 KiB

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