app.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. //app.js
  2. import api from './api'
  3. let mta = require('/utils/mta_analysis.js')
  4. import regeneratorRuntime from '/utils/runtime'
  5. const FILE_BASE_NAME = 'tmp_base64src';
  6. App({
  7. onLaunch: function (options) {
  8. wx.removeStorageSync("loginInfo");
  9. // this.getToken();
  10. const scene = decodeURIComponent(options.query.scene);
  11. mta.App.init({
  12. "appID": "500719713",
  13. "eventID": "500719847",
  14. "autoReport": true,
  15. "statParam": true,
  16. "ignoreParams": [],
  17. "statPullDownFresh": true,
  18. "statShareApp": true,
  19. "statReachBottom": true
  20. });
  21. if(scene){
  22. const sceneQuery=scene.split(':');
  23. if(sceneQuery.length==2){
  24. mta.Event.stat(sceneQuery[0],{
  25. [sceneQuery[1]]:'true'
  26. })
  27. }
  28. }
  29. },
  30. api:api,
  31. isLogin:false,
  32. loginCallBack:[],
  33. onShow:function(){
  34. //this.post(api.findSale)
  35. //this.post(api.querySale)
  36. },
  37. /**获取用户登录的后的一些信息**/
  38. getToken: function (isJump=true) {
  39. var loginInfo = wx.getStorageSync("loginInfo");
  40. //console.log('loginInfo',loginInfo);
  41. return new Promise((resolve, reject) => {
  42. var that=this;
  43. //登录成功回调
  44. let SuccessBack = function (res, loginType){
  45. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  46. let code = res.code;
  47. //console.info("微信请求token1"+code);
  48. that.request({
  49. url:api.code,
  50. data:{
  51. code: code,
  52. // uuid:new Date().getTime(),
  53. wxAppId:"wxe0bc848feb0176a9"
  54. },
  55. method: 'POST',
  56. header:{
  57. 'content-type': 'application/json'
  58. }, // 默认值
  59. }).then((data)=>{
  60. //console.log(data);
  61. return Promise.resolve(data)
  62. }).then(res=>{
  63. //console.log('userToken3',res);
  64. // let isGoLogin=false;
  65. /* if(isJump&&!res.data.auth){
  66. //reject('未注册');
  67. isGoLogin=true
  68. wx.navigateTo({
  69. url:"/pages/login/login"
  70. });
  71. //return false
  72. }*/
  73. //res.data.auth=false; //测试未注册状态
  74. wx.setStorageSync("loginInfo",res.data)
  75. that.isLogin=false;
  76. resolve(res.data);
  77. while (that.loginCallBack.length>0){
  78. that.loginCallBack.pop()()
  79. }
  80. }).catch(error=>{
  81. console.log('登录失败',error);
  82. /* reject(error)*/
  83. });
  84. }
  85. //个人微信登录逻辑
  86. let LoginWx = function(){
  87. wx.login({
  88. success: res=>SuccessBack(res,1),
  89. fail:error=>{
  90. that.isLogin=false;
  91. console.info("wx.login error={}",JSON.stringify(error));
  92. reject(error);
  93. }
  94. });
  95. };
  96. wx.checkSession({
  97. success:r=> {
  98. //console.log('wx.checkSession')
  99. if (loginInfo) {
  100. resolve(loginInfo);
  101. return;
  102. }
  103. this.isLogin=true;
  104. LoginWx();
  105. },
  106. fail:e=>{
  107. console.log('checkSession',false)
  108. this.isLogin=true;
  109. LoginWx();
  110. }
  111. });
  112. });
  113. },
  114. //判断用户是否注册
  115. authorization: async function () {
  116. const userInfo = await this.getToken();
  117. if (!userInfo.auth) {
  118. wx.navigateTo({
  119. url: "/pages/login/login"
  120. })
  121. return Promise.resolve(false)
  122. }
  123. return Promise.resolve(true)
  124. },
  125. /** 微信request 封装 **/
  126. request: function (options) {
  127. var that = this;
  128. return (function (options) {
  129. var promise = new Promise((resolve, reject) => {
  130. //init
  131. let i=0, maxRequest=3;
  132. let request=function(refres=false){
  133. i++;
  134. //登录过期刷新headerToekn
  135. if(refres){
  136. const loginInfo=wx.getStorageSync('loginInfo');
  137. options.header.wxToken= loginInfo.wxToken;
  138. if (loginInfo.extraToken && loginInfo.extraToken.AdminAuthorization){
  139. options.header.AdminAuthorization = loginInfo.extraToken.AdminAuthorization.token
  140. }
  141. }
  142. wx.request({
  143. url: options.url,
  144. data: options.data,
  145. method: options.method,
  146. header: options.header,
  147. success: function (res) {
  148. if (res.header.RefreshAdminAuthorization){
  149. //todo 刷新本地token token值=res.header.RefreshAdminAuthorization
  150. const loginInfo=wx.getStorageSync('loginInfo');
  151. if(loginInfo.extraToken){
  152. loginInfo.extraToken={
  153. AdminAuthorization:{
  154. token:res.header.RefreshAdminAuthorization
  155. }
  156. }
  157. wx.setStorageSync('loginInfo',loginInfo)
  158. }
  159. }
  160. wx.hideLoading();
  161. if(res.statusCode>='500'){
  162. wx.showToast({
  163. title: res.data.message||"服务器异常",
  164. icon: 'none',
  165. duration: 3000,
  166. });
  167. reject('服务器异常');
  168. return
  169. }
  170. //登录过期
  171. if (res.data.code == "ACSDK10000003") {
  172. wx.removeStorageSync('loginInfo');
  173. that.getToken().then(res => {
  174. //console.log('登录过期重试',res);
  175. request(true);
  176. }).catch(error => {
  177. wx.showToast({
  178. title: '登录失败',
  179. icon: 'none',
  180. duration: 3000,
  181. });
  182. });
  183. } else if (res.data.code == "ACSDK10000005") {
  184. //接口未授权
  185. wx.removeStorageSync('loginInfo');
  186. that.getToken().then(res => {
  187. console.log('ACSDK10000005',res);
  188. //临时拦截
  189. console.log(typeof options.data.noLogin == 'undefined')
  190. if(typeof options.data.noLogin == 'undefined'){
  191. if(!res.auth){
  192. wx.navigateTo({
  193. url:"/pages/login/login"
  194. });
  195. }
  196. }
  197. }).catch(error => {
  198. wx.showToast({
  199. title: '登录失败',
  200. icon: 'none',
  201. duration: 3000,
  202. });
  203. });
  204. }else if(res.data.success==false){
  205. // wx.showToast({
  206. // title: res.data.message,
  207. // icon: 'none',
  208. // duration: 3000,
  209. // });
  210. reject(res);
  211. }else{
  212. resolve(res.data);
  213. }
  214. return false;
  215. },
  216. fail: function (e) {
  217. wx.hideLoading();
  218. wx.showToast({
  219. title: "网络错误",
  220. icon: 'none',
  221. duration: 3000,
  222. });
  223. reject('网络出错');
  224. }
  225. });
  226. };
  227. request();
  228. });
  229. return promise;
  230. })(options);
  231. },
  232. /** 微信request.get 封装 **/
  233. get: async function (url, data) {
  234. return this.request({
  235. url: url,
  236. data: data,
  237. method: 'GET',
  238. header: {
  239. 'content-type': 'application/json', // 默认值
  240. }
  241. })
  242. },
  243. /** 微信request.post 封装 **/
  244. post: async function (url, data={},opt) {
  245. let that=this;
  246. const peddingFun=async ()=>{
  247. //let postData;
  248. let options=Object.assign(
  249. {
  250. showLoading:true,
  251. needToken:true
  252. },
  253. opt);
  254. //console.log('loginInfo', loginInfo);
  255. let header = {
  256. 'content-type': 'application/json', // 默认值
  257. };
  258. let loginInfo = await this.getToken(options.needToken);
  259. header.wxToken= loginInfo.wxToken;
  260. if(options.needToken&&!loginInfo.auth){
  261. wx.navigateTo({
  262. url:"/pages/login/login"
  263. })
  264. return Promise.reject('未注册');
  265. }
  266. if (loginInfo.extraToken && loginInfo.extraToken.AdminAuthorization){
  267. //console.log('AdminAuthorization');
  268. header.AdminAuthorization = loginInfo.extraToken.AdminAuthorization.token
  269. }
  270. // postData = Object.assign({}, data);
  271. if(options.showLoading){
  272. wx.showLoading({
  273. title:"正在加载"
  274. });
  275. }
  276. //临时拦截
  277. data.noLogin = options.noLogin;
  278. return this.request({
  279. url: url,
  280. data: data,
  281. method: 'POST',
  282. header: header
  283. });
  284. };
  285. // login ing wait
  286. if(this.isLogin){
  287. this.loginCallBack.push(peddingFun)
  288. return
  289. }
  290. return peddingFun()
  291. },
  292. /** 微信request.post 封装 **/
  293. postForm: async function (url, data) {
  294. var openid = await this.getToken();
  295. return this.request({
  296. url:url,
  297. data: data,
  298. method: 'POST',
  299. header: {
  300. 'content-type': 'x-www-form-urlencoded', // 默认值
  301. 'X-Auth-Code': openid
  302. }
  303. });
  304. },
  305. /** connectSocket **/
  306. connectSocket:async function (url){
  307. let loginInfo = await this.getToken();
  308. let header = {
  309. [loginInfo.authHeaderName]:loginInfo.token
  310. };
  311. return new Promise(function(resolve ,reject){
  312. wx.connectSocket({
  313. url: url,
  314. header:header,
  315. success:(res)=>{
  316. console.log('socket连接成功',res)
  317. resolve(res)
  318. },
  319. fail:(error)=>{
  320. console.log('socket连接失败',error)
  321. reject(error)
  322. }
  323. });
  324. });
  325. },
  326. /**上传文件**/
  327. uploadFile:async function(options={}){
  328. return new Promise( (resolve ,reject)=>{
  329. wx.chooseImage({
  330. count: 1, // 默认9
  331. extension:options.extension?options.extension:['pdf','jpg','png','jpeg','gif'],
  332. success: async (res)=> {
  333. wx.showLoading({
  334. title:"正在上传文件..."
  335. })
  336. // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
  337. var tempFilePaths = res.tempFiles;
  338. var imgInfo = await this.getImageInfo(tempFilePaths[0].path);
  339. //验证图片
  340. if(options.validate){
  341. if(!options.validate(imgInfo)){
  342. reject(new Error('上传图片不符合规范'))
  343. return false
  344. }
  345. }
  346. const uploadTask = wx.uploadFile({
  347. url: api.upload, //仅为示例,非真实的接口地址
  348. filePath: tempFilePaths[0].path,
  349. name: 'file',
  350. success: (res)=>{
  351. resolve(res)
  352. },
  353. fail:(error)=>{
  354. resolve(error)
  355. },
  356. complete:(res)=>{
  357. wx.hideLoading();
  358. }
  359. })
  360. uploadTask.onProgressUpdate((res) => {
  361. wx.showLoading({
  362. title:`上传中${res.progress}%..`
  363. })
  364. })
  365. },
  366. fail:(error)=>{
  367. reject(error)
  368. }
  369. })
  370. });
  371. },
  372. /**获取图片基本信息**/
  373. getImageInfo(url){
  374. return new Promise((resolve,reject)=>{
  375. wx.getImageInfo({
  376. src: url,
  377. success : res => {
  378. resolve(res)
  379. },
  380. fail:error => {
  381. resolve(error)
  382. }
  383. })
  384. })
  385. },
  386. //从聊天中选择文件
  387. uploadFileMsg:async function(url,options={}){
  388. return new Promise((resolve ,reject)=>{
  389. wx.chooseMessageFile({
  390. count: 1, // 默认9,
  391. type:'file',
  392. extension:options.extension?options.extension:['pdf','jpg','png','jpeg'],
  393. success: (res)=> {
  394. wx.showLoading({
  395. title:"正在上传文件..."
  396. })
  397. // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
  398. var tempFilePaths = res.tempFiles;
  399. // console.log(tempFilePaths)
  400. const uploadTask = wx.uploadFile({
  401. url: api.upload, //仅为示例,非真实的接口地址
  402. filePath: tempFilePaths[0].path,
  403. name: 'file',
  404. success: (res)=>{
  405. resolve(res)
  406. },
  407. fail:(error)=>{
  408. resolve(error)
  409. },
  410. complete:(res)=>{
  411. wx.hideLoading();
  412. }
  413. });
  414. uploadTask.onProgressUpdate((res) => {
  415. wx.showLoading({
  416. title:`上传中${res.progress}%..`
  417. })
  418. })
  419. },
  420. fail:(error)=>{
  421. reject(error)
  422. }
  423. });
  424. });
  425. },
  426. globalData: {
  427. userInfo: null
  428. },
  429. //base64图片路径
  430. base64src: function(base64data, cb) {
  431. const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  432. if(!format) {
  433. return (new Error('ERROR_BASE64SRC_PARSE'));
  434. }
  435. const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
  436. const buffer = wx.base64ToArrayBuffer(bodyData);
  437. const fsm = wx.getFileSystemManager();
  438. fsm.writeFile({
  439. filePath,
  440. data: buffer,
  441. encoding: 'binary',
  442. success() {
  443. cb(filePath);
  444. },
  445. fail() {
  446. return (new Error('ERROR_BASE64SRC_WRITE'));
  447. },
  448. });
  449. },
  450. //预览文档
  451. openDocument:function(src){
  452. wx.showLoading({
  453. title:"正在加载文件..."
  454. })
  455. wx.downloadFile({
  456. url: src,
  457. success: (res)=> {
  458. const filePath = res.tempFilePath
  459. wx.openDocument({
  460. filePath: filePath,
  461. success: function (res) {
  462. console.log('打开文档成功')
  463. },
  464. fail:(e)=>{
  465. console.log('文件预览失败',e);
  466. wx.showToast({
  467. title:"预览失败",
  468. duration:2000,
  469. icon:"none"
  470. })
  471. }
  472. })
  473. },
  474. fail:e=>{
  475. console.log(e);
  476. wx.showToast({
  477. title:"预览失败",
  478. duration:2000,
  479. icon:"none"
  480. })
  481. },
  482. complete:(res)=>{
  483. wx.hideLoading();
  484. }
  485. })
  486. },
  487. //预览图片
  488. previewImg:function(imgs){
  489. wx.previewImage({
  490. current: imgs[0], // 当前显示图片的http链接
  491. urls: imgs // 需要预览的图片http链接列表
  492. })
  493. },
  494. //设置标题
  495. setNavTitle(title) {
  496. wx.setNavigationBarTitle({
  497. title: title
  498. })
  499. let pages = getCurrentPages() // 获取加载的页面
  500. let currentPage = pages[pages.length - 1] // 获取当前页面的对象
  501. currentPage.setData({
  502. navigationBarTitle: title
  503. })
  504. },
  505. })