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.

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