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.

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