C端小程序
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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