123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524 |
- //app.js
- import api from './api'
- let mta = require('/utils/mta_analysis.js')
- import regeneratorRuntime from '/utils/runtime'
- const FILE_BASE_NAME = 'tmp_base64src';
- App({
- onLaunch: function (options) {
- wx.removeStorageSync("loginInfo");
- // this.getToken();
- const scene = decodeURIComponent(options.query.scene);
- mta.App.init({
- "appID": "500719713",
- "eventID": "500719847",
- "autoReport": true,
- "statParam": true,
- "ignoreParams": [],
- "statPullDownFresh": true,
- "statShareApp": true,
- "statReachBottom": true
- });
- if(scene){
- const sceneQuery=scene.split(':');
- if(sceneQuery.length==2){
- mta.Event.stat(sceneQuery[0],{
- [sceneQuery[1]]:'true'
- })
- }
- }
- },
- api:api,
- isLogin:false,
- loginCallBack:[],
- onShow:function(){
- //this.post(api.findSale)
- //this.post(api.querySale)
- },
- /**获取用户登录的后的一些信息**/
- getToken: function (isJump=true) {
- var loginInfo = wx.getStorageSync("loginInfo");
- //console.log('loginInfo',loginInfo);
- return new Promise((resolve, reject) => {
- var that=this;
- //登录成功回调
- let SuccessBack = function (res, loginType){
- // 发送 res.code 到后台换取 openId, sessionKey, unionId
- let code = res.code;
- //console.info("微信请求token1"+code);
- that.request({
- url:api.code,
- data:{
- code: code,
- // uuid:new Date().getTime(),
- wxAppId:"wxe0bc848feb0176a9"
- },
- method: 'POST',
- header:{
- 'content-type': 'application/json'
- }, // 默认值
- }).then((data)=>{
- //console.log(data);
- return Promise.resolve(data)
- }).then(res=>{
- //console.log('userToken3',res);
- // let isGoLogin=false;
- /* if(isJump&&!res.data.auth){
- //reject('未注册');
- isGoLogin=true
- wx.navigateTo({
- url:"/pages/login/login"
- });
- //return false
- }*/
- //res.data.auth=false; //测试未注册状态
- wx.setStorageSync("loginInfo",res.data)
- that.isLogin=false;
- resolve(res.data);
- while (that.loginCallBack.length>0){
- that.loginCallBack.pop()()
- }
- }).catch(error=>{
- console.log('登录失败',error);
- /* reject(error)*/
- });
- }
- //个人微信登录逻辑
- let LoginWx = function(){
- wx.login({
- success: res=>SuccessBack(res,1),
- fail:error=>{
- that.isLogin=false;
- console.info("wx.login error={}",JSON.stringify(error));
- reject(error);
- }
- });
- };
- wx.checkSession({
- success:r=> {
- //console.log('wx.checkSession')
- if (loginInfo) {
- resolve(loginInfo);
- return;
- }
- this.isLogin=true;
- LoginWx();
- },
- fail:e=>{
- console.log('checkSession',false)
- this.isLogin=true;
- LoginWx();
- }
- });
- });
- },
- //判断用户是否注册
- authorization: async function () {
- const userInfo = await this.getToken();
- if (!userInfo.auth) {
- wx.navigateTo({
- url: "/pages/login/login"
- })
- return Promise.resolve(false)
- }
- return Promise.resolve(true)
- },
- /** 微信request 封装 **/
- request: function (options) {
- var that = this;
- return (function (options) {
- var promise = new Promise((resolve, reject) => {
- //init
- let i=0, maxRequest=3;
- let request=function(refres=false){
- i++;
- //登录过期刷新headerToekn
- if(refres){
- const loginInfo=wx.getStorageSync('loginInfo');
- options.header.wxToken= loginInfo.wxToken;
- if (loginInfo.extraToken && loginInfo.extraToken.AdminAuthorization){
- options.header.AdminAuthorization = loginInfo.extraToken.AdminAuthorization.token
- }
- }
- wx.request({
- url: options.url,
- data: options.data,
- method: options.method,
- header: options.header,
- success: function (res) {
- if (res.header.RefreshAdminAuthorization){
- //todo 刷新本地token token值=res.header.RefreshAdminAuthorization
- const loginInfo=wx.getStorageSync('loginInfo');
- if(loginInfo.extraToken){
- loginInfo.extraToken={
- AdminAuthorization:{
- token:res.header.RefreshAdminAuthorization
- }
- }
- wx.setStorageSync('loginInfo',loginInfo)
- }
- }
- wx.hideLoading();
- if(res.statusCode>='500'){
- wx.showToast({
- title: res.data.message||"服务器异常",
- icon: 'none',
- duration: 3000,
- });
- reject('服务器异常');
- return
- }
- //登录过期
- if (res.data.code == "ACSDK10000003") {
- wx.removeStorageSync('loginInfo');
- that.getToken().then(res => {
- //console.log('登录过期重试',res);
- request(true);
- }).catch(error => {
- wx.showToast({
- title: '登录失败',
- icon: 'none',
- duration: 3000,
- });
- });
- } else if (res.data.code == "ACSDK10000005") {
- //接口未授权
- wx.removeStorageSync('loginInfo');
- that.getToken().then(res => {
- console.log('ACSDK10000005',res);
- //临时拦截
- console.log(typeof options.data.noLogin == 'undefined')
- if(typeof options.data.noLogin == 'undefined'){
- if(!res.auth){
- wx.navigateTo({
- url:"/pages/login/login"
- });
- }
- }
- }).catch(error => {
- wx.showToast({
- title: '登录失败',
- icon: 'none',
- duration: 3000,
- });
- });
- }else if(res.data.success==false){
- // wx.showToast({
- // title: res.data.message,
- // icon: 'none',
- // duration: 3000,
- // });
- reject(res);
- }else{
- resolve(res.data);
- }
- return false;
- },
- fail: function (e) {
- wx.hideLoading();
- wx.showToast({
- title: "网络错误",
- icon: 'none',
- duration: 3000,
- });
- reject('网络出错');
- }
- });
- };
- request();
- });
- return promise;
- })(options);
- },
- /** 微信request.get 封装 **/
- get: async function (url, data) {
- return this.request({
- url: url,
- data: data,
- method: 'GET',
- header: {
- 'content-type': 'application/json', // 默认值
- }
- })
- },
- /** 微信request.post 封装 **/
- post: async function (url, data={},opt) {
- let that=this;
- const peddingFun=async ()=>{
- //let postData;
- let options=Object.assign(
- {
- showLoading:true,
- needToken:true
- },
- opt);
- //console.log('loginInfo', loginInfo);
- let header = {
- 'content-type': 'application/json', // 默认值
- };
- let loginInfo = await this.getToken(options.needToken);
- header.wxToken= loginInfo.wxToken;
- if(options.needToken&&!loginInfo.auth){
- wx.navigateTo({
- url:"/pages/login/login"
- })
- return Promise.reject('未注册');
- }
- if (loginInfo.extraToken && loginInfo.extraToken.AdminAuthorization){
- //console.log('AdminAuthorization');
- header.AdminAuthorization = loginInfo.extraToken.AdminAuthorization.token
- }
- // postData = Object.assign({}, data);
- if(options.showLoading){
- wx.showLoading({
- title:"正在加载"
- });
- }
- //临时拦截
- data.noLogin = options.noLogin;
- return this.request({
- url: url,
- data: data,
- method: 'POST',
- header: header
- });
- };
- // login ing wait
- if(this.isLogin){
- this.loginCallBack.push(peddingFun)
- return
- }
- return peddingFun()
- },
- /** 微信request.post 封装 **/
- postForm: async function (url, data) {
- var openid = await this.getToken();
- return this.request({
- url:url,
- data: data,
- method: 'POST',
- header: {
- 'content-type': 'x-www-form-urlencoded', // 默认值
- 'X-Auth-Code': openid
- }
- });
- },
- /** connectSocket **/
- connectSocket:async function (url){
- let loginInfo = await this.getToken();
- let header = {
- [loginInfo.authHeaderName]:loginInfo.token
- };
- return new Promise(function(resolve ,reject){
- wx.connectSocket({
- url: url,
- header:header,
- success:(res)=>{
- console.log('socket连接成功',res)
- resolve(res)
- },
- fail:(error)=>{
- console.log('socket连接失败',error)
- reject(error)
- }
- });
- });
- },
- /**上传文件**/
- uploadFile:async function(options={}){
- return new Promise( (resolve ,reject)=>{
- wx.chooseImage({
- count: 1, // 默认9
- extension:options.extension?options.extension:['pdf','jpg','png','jpeg','gif'],
- success: async (res)=> {
- wx.showLoading({
- title:"正在上传文件..."
- })
- // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
- var tempFilePaths = res.tempFiles;
- var imgInfo = await this.getImageInfo(tempFilePaths[0].path);
- //验证图片
- if(options.validate){
- if(!options.validate(imgInfo)){
- reject(new Error('上传图片不符合规范'))
- return false
- }
- }
- const uploadTask = wx.uploadFile({
- url: api.upload, //仅为示例,非真实的接口地址
- filePath: tempFilePaths[0].path,
- name: 'file',
- success: (res)=>{
- resolve(res)
- },
- fail:(error)=>{
- resolve(error)
- },
- complete:(res)=>{
- wx.hideLoading();
- }
- })
- uploadTask.onProgressUpdate((res) => {
- wx.showLoading({
- title:`上传中${res.progress}%..`
- })
- })
- },
- fail:(error)=>{
- reject(error)
- }
- })
- });
- },
- /**获取图片基本信息**/
- getImageInfo(url){
- return new Promise((resolve,reject)=>{
- wx.getImageInfo({
- src: url,
- success : res => {
- resolve(res)
- },
- fail:error => {
- resolve(error)
- }
- })
- })
- },
- //从聊天中选择文件
- uploadFileMsg:async function(url,options={}){
- return new Promise((resolve ,reject)=>{
- wx.chooseMessageFile({
- count: 1, // 默认9,
- type:'file',
- extension:options.extension?options.extension:['pdf','jpg','png','jpeg'],
- success: (res)=> {
- wx.showLoading({
- title:"正在上传文件..."
- })
- // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
- var tempFilePaths = res.tempFiles;
- // console.log(tempFilePaths)
- const uploadTask = wx.uploadFile({
- url: api.upload, //仅为示例,非真实的接口地址
- filePath: tempFilePaths[0].path,
- name: 'file',
- success: (res)=>{
- resolve(res)
- },
- fail:(error)=>{
- resolve(error)
- },
- complete:(res)=>{
- wx.hideLoading();
- }
- });
- uploadTask.onProgressUpdate((res) => {
- wx.showLoading({
- title:`上传中${res.progress}%..`
- })
- })
- },
- fail:(error)=>{
- reject(error)
- }
- });
- });
- },
- globalData: {
- userInfo: null
- },
- //base64图片路径
- base64src: function(base64data, cb) {
- const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
- if(!format) {
- return (new Error('ERROR_BASE64SRC_PARSE'));
- }
- const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
- const buffer = wx.base64ToArrayBuffer(bodyData);
- const fsm = wx.getFileSystemManager();
- fsm.writeFile({
- filePath,
- data: buffer,
- encoding: 'binary',
- success() {
- cb(filePath);
- },
- fail() {
- return (new Error('ERROR_BASE64SRC_WRITE'));
- },
- });
- },
- //预览文档
- openDocument:function(src){
- wx.showLoading({
- title:"正在加载文件..."
- })
- wx.downloadFile({
- url: src,
- success: (res)=> {
- const filePath = res.tempFilePath
- wx.openDocument({
- filePath: filePath,
- success: function (res) {
- console.log('打开文档成功')
- },
- fail:(e)=>{
- console.log('文件预览失败',e);
- wx.showToast({
- title:"预览失败",
- duration:2000,
- icon:"none"
- })
- }
- })
- },
- fail:e=>{
- console.log(e);
- wx.showToast({
- title:"预览失败",
- duration:2000,
- icon:"none"
- })
- },
- complete:(res)=>{
- wx.hideLoading();
- }
- })
- },
- //预览图片
- previewImg:function(imgs){
- wx.previewImage({
- current: imgs[0], // 当前显示图片的http链接
- urls: imgs // 需要预览的图片http链接列表
- })
- },
- //设置标题
- setNavTitle(title) {
- wx.setNavigationBarTitle({
- title: title
- })
- let pages = getCurrentPages() // 获取加载的页面
- let currentPage = pages[pages.length - 1] // 获取当前页面的对象
- currentPage.setData({
- navigationBarTitle: title
- })
- },
- })
|