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.

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