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.

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