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.

405 lines
13 KiB

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