C端小程序
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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