C端小程序
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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