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.

332 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. var that = this;
  10. if (that.globalData.previewFlag) {//解决微信图片预览重复进入app.js onshow
  11. that.globalData.previewFlag = false
  12. return
  13. }
  14. if (options.query.scene) {
  15. that.globalData.newArr = decodeURIComponent(options.query.scene).split(":");
  16. }
  17. that.globalData.sceneAddress = options.scene;
  18. /**
  19. * 小程序版本更新
  20. */
  21. that.autoUpdate();
  22. /**
  23. * 用户登录
  24. */
  25. that.userLogin(options.scene);
  26. wx.getSystemInfo({
  27. success: res => {
  28. that.statusBarHeight = res.statusBarHeight
  29. }
  30. })
  31. },
  32. onShow:function(options){
  33. console.log("onshow被调用了!")
  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. activityId:'',//活动id方便授权数据回传
  167. typeLsit: [],//初始哈样式
  168. scene: "",
  169. // token
  170. token: null,
  171. // user openId
  172. openId: null,
  173. // 渠道
  174. sceneAddress: null,
  175. // location info
  176. locationInfo: null,
  177. // 二维码参数
  178. scene: null,
  179. // 支持智慧停车, 用户名下有车
  180. phone: null,
  181. supportCar: false,
  182. parkVendor: 1, // 1-ETCP, 2-TJD停简单 3-Dahua大华, 4-ShangAn尚安, 5-BoLink泊链
  183. // ETCP token
  184. etcpToken: null,
  185. carLogin: false,
  186. // 当前商场信息
  187. market: {
  188. name: ""
  189. },
  190. // websocket
  191. socketClient: null,
  192. socketReceiver: function(e) {}, //收到消息回调
  193. curHtml: '',//富文本相关,由于浏览器传参长度有限制
  194. },
  195. // 初始化websocket
  196. initSocket: function() {
  197. let that = this;
  198. // socket是否连接
  199. let socketConnected = false;
  200. // 待发送的消息队列
  201. let messageQueue = [];
  202. // 是否断线重连
  203. let reconnect = true;
  204. // 发送消息
  205. function sendSocketMessage(msg) {
  206. // console.log(msg);
  207. // 如果socket已连接则发送消息
  208. if (socketConnected) {
  209. wx.sendSocketMessage({
  210. data: msg
  211. })
  212. } else {
  213. // socket没有连接将消息放入队列中
  214. messageQueue.push(msg);
  215. }
  216. }
  217. // 关闭连接
  218. function close() {
  219. if (socketConnected) {
  220. wx.closeSocket()
  221. socketConnected = false;
  222. }
  223. }
  224. // 符合WebSocket定义的对象
  225. var ws = {
  226. send: sendSocketMessage,
  227. close: close
  228. }
  229. // 创建一个 WebSocket 连接
  230. function connect() {
  231. wx.connectSocket({
  232. url: config.wsurl,
  233. header: {
  234. token: that.globalData.token //从服务端获取一个token,服务端验证token是否允许连接,案例中没做限制
  235. }
  236. })
  237. }
  238. connect();
  239. // 监听 WebSocket 连接打开事件
  240. wx.onSocketOpen(function(res) {
  241. console.log("WebSocket 连接成功")
  242. socketConnected = true;
  243. ws.onopen();
  244. // 连接成功后,将队列中的消息发送出去
  245. let queueLength = messageQueue.length
  246. for (let i = 0; i < queueLength; i++) {
  247. sendSocketMessage(messageQueue.shift())
  248. }
  249. })
  250. // 监听 WebSocket 接受到服务器的消息事件
  251. wx.onSocketMessage(function(res) {
  252. ws.onmessage(res);
  253. })
  254. // 监听 WebSocket 错误事件
  255. wx.onSocketError(function(res) {
  256. console.log("WebSocket 错误事件")
  257. if (!socketConnected) {
  258. // 断线重连
  259. if (reconnect) {
  260. connect();
  261. }
  262. }
  263. })
  264. // 监听 WebSocket 连接关闭事件
  265. wx.onSocketClose(function(res) {
  266. console.log("WebSocket 连接关闭")
  267. socketConnected = false;
  268. // 断线重连
  269. if (reconnect) {
  270. connect();
  271. }
  272. })
  273. const Stomp = require('/utils/stomp.min.js').Stomp;
  274. /**
  275. * 定期发送心跳或检测服务器心跳
  276. * The heart-beating is using window.setInterval() to regularly send heart-beats and/or check server heart-beats.
  277. * 可看stomp.js的源码(195,207,489行),由于小程序没有window对象,所以我们要调用小程序的定时器api实现
  278. */
  279. Stomp.setInterval = function(interval, f) {
  280. return setInterval(f, interval);
  281. };
  282. // 结束定时器的循环调用
  283. Stomp.clearInterval = function(id) {
  284. return clearInterval(id);
  285. };
  286. const stompClient = Stomp.over(ws);
  287. that.globalData.socketClient = stompClient;
  288. stompClient.connect({}, function(callback) {
  289. // 订阅自己的
  290. stompClient.subscribe('/user/' + config.weapp.AppId + '/' + that.globalData.openId + '/message', function(message, headers) {
  291. console.log('收到只发送给我的消息:', message);
  292. that.globalData.socketReceiver(JSON.parse(message.body));
  293. // 通知服务端收到消息
  294. message.ack();
  295. });
  296. stompClient.subscribe('/topic/' + config.weapp.AppId, function(message, headers) {
  297. console.log('收到TOPIC的消息:', message);
  298. that.globalData.socketReceiver(JSON.parse(message.body));
  299. // 通知服务端收到消息
  300. //message.ack();
  301. });
  302. // 向服务端发送消息
  303. stompClient.send("/app/message", {}, JSON.stringify({
  304. 'msg': 'client: ' + that.globalData.openId
  305. }));
  306. })
  307. },
  308. //统一发送消息
  309. sendSocketMessage: function(msg) {
  310. this.globalData.socketClient.send("/app/message", {}, JSON.stringify(msg));
  311. }
  312. });