C端小程序
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

304 行
8.8 KiB

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