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.

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