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.

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