C端小程序
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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