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.

386 lines
12 KiB

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