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.

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