C端小程序
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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