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.

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