C端小程序
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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