C端小程序
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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