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

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