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.

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