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

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