C端小程序
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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