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.

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