import md5 from "js-md5"; import store from "@/store"; import config from '@/config'; import { getSupportData, getSiteServicePhone } from "@/api/public"; import { COOKIE_KEY } from '@/constants/storage-keys'; import MathX from "@/utils/math"; import { getWxAppIsPay, aliPayApp, aliPayWap } from "@/api/special"; import Routine from '@/libs/routine'; import { SET_LOGIN } from "@/store/types/muations-types"; import { isForceBinding } from "@/api/user"; import { VALID_LOGIN_STATUS } from "@/store/types/action-types"; import userInfo from "@/mixins/userInfo"; const { HTTP_REQUEST_URL, Url_SCHEMES } = config; import {getIndexData } from "@/api/index"; const systemInfo = uni.getSystemInfoSync(); export default { ...MathX, getFullPath(otherParams = {}) { const pages = getCurrentPages(); const page = pages[pages.length - 1]; const { route, options } = page; const params = this.objToParam({ ...options, ...otherParams }); return { full_path: route, scene: params || "" } }, delCookie(key) { let cookies = this.getStorage(COOKIE_KEY); if (cookies) { cookies = cookies.trim(); let date = new Date(); //获取当前时间 date.setTime(date.getTime() - 10000); //格式化为cookie识别的时间 const data = key + "=v;expires=" + date.toGMTString(); //设置cookie if (cookies[cookies.length - 1] === ";") { cookies += data; } else { cookies = cookies + ";" + data; } // #ifndef MP document.cookie = cookies; // #endif this.setStorage(COOKIE_KEY, cookies); } }, dateFormat(time) { let date = new Date(time); let year = date.getFullYear(); // 在日期格式中,月份是从0开始的,因此要加0,使用三元表达式在小于10的前面加0,以达到格式统一 如 09:11:05 let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); // 拼接 // return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds; return year + "-" + month + "-" + day + ' ' + hours + ":" + minutes; }, mergeLaunchParams(options) { const app = getApp(); if (app.globalData.pre_data) { const data = { ...app.globalData.pre_data, options }; app.globalData.pre_data = undefined; return data; } return options; }, parseScene(scene) { if (scene) scene = decodeURIComponent(scene); let pre_data; const list = scene?.split("&"); if (list?.length) { pre_data = {}; list.forEach(e => { try { let [k, v] = e.trim().split('='); pre_data[k?.trim()] = v?.trim(); } catch { } }); } return pre_data; }, getCookie(key) { let cookies = this.getStorage(COOKIE_KEY); let params = {} if (cookies) { cookies?.split(';').forEach(e => { try { let [k, v] = e.trim().split('='); x[k?.trim()] = v?.trim(); } catch { } }); } return params[key]; }, setCookie(key, val, time) { let cookies = this.getStorage(COOKIE_KEY); if (cookies) { cookies = cookies.trim(); let date = new Date(); //获取当前时间 if (!time) time = 1; //将date设置为n天以后的时间 date.setTime(date.getTime() + time * 24 * 3600 * 1000); //格式化为cookie识别的时间 const data = key + "=" + val + ";expires=" + date.toGMTString(); //设置cookie if (cookies[cookies.length - 1] === ";") { cookies += data; } else { cookies = cookies + ";" + data; } // #ifndef MP document.cookie = cookies; // #endif this.setStorage(COOKIE_KEY, cookies); } }, getURLSearchParams(url) { let requestParams = {}; if (url.indexOf("?") !== -1) { let str = url.substr(url.indexOf("?") + 1); //截取?后面的内容作为字符串 // console.log(str, '?后面的内容'); let strs = str.split("&"); //将字符串内容以&分隔为一个数组 // console.log(strs, '以&切割的数组'); for (let i = 0; i < strs.length; i++) { requestParams[strs[i].split("=")[0]] = decodeURI( strs[i].split("=")[1] ); // 将数组元素中'='左边的内容作为对象的属性名,'='右边的内容作为对象对应属性的属性值 } } return requestParams; }, getClientRect(selector, target) { return new Promise((resolve) => { let query = uni.createSelectorQuery(); if (target) { query = query.in(target); }; query .select(selector) .boundingClientRect((res) => { resolve(res); }) .exec(); }); }, /** * * @param {int} support_type 咨询内容类型 * @param {int} id 商品/订单ID * @param {int} type 商品/订单类型 */ goSupport(support_type = 0, type = 0, id = 0 ,mer_id = 0) { this.checkLogin(() => { uni.navigateTo({ url: "/pages/customer/chat?" + this.objToParam({ support_type, id, type, mer_id }), }); }, true); }, asyncNextTick(vm) { return new Promise((resolve) => { vm.$nextTick(() => { resolve(); }); }); }, getImagePath(path) { // #ifdef H5 path = HTTP_REQUEST_URL + "/wap/public_api/proxy_img?path=" + encodeURIComponent(path); // #endif return new Promise((resolve, reject) => { uni.downloadFile({ url: path, success: ({ tempFilePath }) => { resolve(tempFilePath); }, fail: (err) => { reject(err); } }); }); }, SplitArray(list, sp) { if (typeof list != 'object') return []; if (sp === undefined) sp = []; for (let i = 0; i < list.length; i++) { sp.push(list[i]); } return sp; }, getSystemInfo(force = false) { if (!force) return systemInfo; return uni.getSystemInfoSync(); }, styleToStr(obj) { return Object.keys(obj) .map(k => `${k}: ${obj[k]}`) .join(';'); }, objToParam(obj) { return Object.keys(obj) .map(k => `${k}=${obj[k]}`) .join('&'); }, hexMd5(str) { return md5.hex(str); }, isForceBinding() { return isForceBinding() }, async checkLogin(fn, noLoginFn, BindPhone = 0) { console.log(store.getters.isLogin, noLoginFn); if (store.getters.isLogin) { let { data } = await this.isForceBinding() if (data.is_force_binding != 2 && !store.getters.userInfo.phone && !BindPhone) { return uni.navigateTo({ url: "/pages/login/index" }); } fn(); } else { if (noLoginFn === true) { // #ifdef H5 if (this.isWeixin()) return uni.redirectTo({ url: "/pages/login/wechat" }); // #endif // #ifdef MP-TOUTIAO setTimeout(() => { this.showMsg("请点击头像登录") }, 1000); return uni.switchTab({ url: "/pages/mine/index" }); // #endif uni.navigateTo({ url: "/pages/login/index" }); } else { noLoginFn && noLoginFn(); } } }, isWeixin() { return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1; }, showMsg(msg, icon = "none") { uni.showToast({ title: msg, icon, duration: 1500, fail: function (err) { console.log(err); } }); }, showModal(msg, content, fuc) { uni.showModal({ title: msg, content: content, success: fuc }); }, wrapFn(fn, options) { return new Promise((resolve, reject) => { fn({ ...options, success: (...args) => { resolve(...args); }, fail: (...err) => { reject(...err); } }); }); }, //新用户登录完成后修改用户头像和名称 updategetUserInfo(data, vm) { const header = { 'X-Requested-With': "XMLHttpRequest", 'X-Version': 'next' }; return new Promise((reslove, reject) => { uni.request({ url: HTTP_REQUEST_URL + "/wap" + "/auth_api/updateUserInfo", method: 'POST', header, data: data || {}, success: (res) => { vm.tipIsVisable = false vm.$store.dispatch("app/" + VALID_LOGIN_STATUS); }, fail: (err) => { reject(err); } }) }); }, uploadImg(filePath) { return this.wrapFn(uni.uploadFile, { url: HTTP_REQUEST_URL + "/wap" + "/auth_api/upload", filePath, name: "file", header: { Authorization: 'Bearer ' + store.getters.token, 'X-Version': 'next' } }).then(res => { const result = JSON.parse(res.data); if (result.code === 200 && result.data.url) { return result.data.url; } throw new Error(result.msg || "上传失败!"); }); }, pickerOneImg() { return new Promise(async (resolve, reject) => { const { tempFilePaths } = await this.wrapFn(uni.chooseImage, { count: 1, extension: ["png", "jpg", "jpeg"], }); const path = tempFilePaths[0]; uni.showLoading({ mask: true, }); try { const result = await this.uploadImg(path); uni.hideLoading(); resolve(result); } catch (err) { uni.hideLoading(); this.$util.showMsg(err.msg || err); reject(); } }); }, getStorage(k) { try { return uni.getStorageSync(k); } catch (err) { } }, setStorage(k, v) { try { uni.setStorageSync(k, v); } catch (err) { } }, removeStorage(k) { try { uni.removeStorageSync(k); } catch (err) { } }, debounce(fn, delay = 200) { let time = 0; console.log(delay, time); return (...args) => { console.log(...args); if (Date.now() - time < delay) return; time = Date.now(); fn(...args); } }, wxh5Pay(jsConfig) { const platform = uni.getSystemInfoSync().platform; let path = jsConfig.mweb_url + "&redirect_url=" + encodeURIComponent(Url_SCHEMES + "://") const webview = plus.webview.create('', HTTP_REQUEST_URL); switch (platform) { case 'android': webview.loadURL(path, { 'Referer': HTTP_REQUEST_URL }); break; case 'ios': //解决ios支付完成后,打开safari浏览器的bug res = webview.loadURL(path, { 'Referer': Url_SCHEMES }); break; default: webview.loadURL(path, { 'Referer': upload }); break; } }, getCallBackUrl() { return HTTP_REQUEST_URL + '/wap/callback/pay_success_synchro' }, aliPay(msn, type, vm) { // #ifdef APP-PLUS aliPayApp(msn, type).then(res => { this.aliAppPay(res.msg, vm) }).catch(err => { this.showMsg(err.msg) }) //#endif // #ifdef H5 aliPayWap(msn, type).then((res) => { this.aliWapPay(res) }).catch(err => { if (err.code = 400) { return this.showMsg(err.msg) } this.aliWapPay(err) }) //#endif }, toutiaoPay: function (jsConfig, vm) { let that = this tt.pay({ orderInfo: jsConfig, service: 5, success(res) { if (res.code == 0) { uni.hideLoading(); vm.successOrder() return that.showMsg(res.msg); } }, fail(res) { console.log(e); uni.hideLoading(); vm.extendOrder() return that.showMsg("取消支付"); }, }); }, kuaishouPay: function (jsConfig, vm) { vm.isOpenWeixing = true let that = this ks.pay({ serviceId: 1, orderInfo: jsConfig, success(res) { if (res.code == 0) { uni.hideLoading(); vm.successOrder() return that.showMsg(res.msg); } }, fail(e) { console.log(e); uni.hideLoading(); vm.extendOrder() return that.showMsg("取消支付"); }, }) }, aliWapPay(res) { document.querySelector('body').innerHTML = res.msg; document.forms[0].submit() }, aliAppPay(jsConfig, vm) { uni.showLoading({ title: '支付中' }); if (jsConfig.search('&') != -1) jsConfig = jsConfig.replace(/&/g, '&'); uni.requestPayment({ provider: 'alipay', orderInfo: jsConfig, success: function (res) { vm.successOrder(); }, fail: function (err) { vm.extendOrder() }, complete: () => { uni.hideLoading(); }, }) }, //刷新页面或关闭当前页面并跳转 refreshPage(url, timeout = 3000) { setTimeout(() => { uni.redirectTo({ url: url[0] === '/' ? url : '/' + url }); }, timeout); }, wxh5PayIsSuccess(orderId, type, vm) { uni.showLoading({ title: '支付中' }); setTimeout(() => { getWxAppIsPay(orderId, type).then(({ data }) => { uni.hideLoading() if (data.is_pay) vm.successOrder(); else vm.extendOrder(); }) }, 1000); }, weixinpay(config, vm) { WeixinJSBridge.invoke( 'getBrandWCPayRequest', config, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { vm.successOrder() } else if (res.err_msg == "get_brand_wcpay_request:cancel") { vm.extendOrder() } else { vm.extendOrder() } } ) }, //微信小程序支付 wechatRoutinePay: function (jsConfig, vm) { let that = this uni.requestPayment({ timeStamp: jsConfig.timeStamp, nonceStr: jsConfig.nonceStr, package: jsConfig.package, signType: jsConfig.signType, paySign: jsConfig.paySign, success: function (res) { uni.hideLoading(); vm.successOrder() return that.showMsg(res.msg); }, fail: function (e) { uni.hideLoading(); vm.extendOrder() return that.showMsg("取消支付"); }, complete: function (e) { uni.hideLoading(); if (e.errMsg == 'requestPayment:cancel') { vm.extendOrder() return that.showMsg("取消支付"); } } }); }, //微信APP wechatH5Pay: function (jsConfig, vm) { // #ifdef APP-PLUS vm.isOpenWeixing = true this.wxh5Pay(jsConfig) //#endif // #ifdef H5 let callbackUrl = this.getCallBackUrl() + "?type=2&id=0"; let mwebUrl = jsConfig.mweb_url + "&redirect_url=" + encodeURIComponent(callbackUrl); window.location.href = mwebUrl; //#endif }, //微信小程序登录 getUserProfile(vm,currentAvatar,username) { const app = getApp(); let code = '' Routine.getCode() .then(codes => { code = codes }) uni.showLoading({ title: '正在登录中' }); return Routine.getUserProfile() .then(res => { let userInfo = res.userInfo; userInfo.code = code; userInfo.spread_spid = app.globalData.spid || 0; //获取推广人ID userInfo.currentAvatar = currentAvatar || ''; userInfo.username = username || ''; userInfo.agent_id=app.globalData.agent_id || 0 console.log(userInfo) Routine.authUserInfo(userInfo).then(res => { uni.hideLoading(); store.commit("app/" + SET_LOGIN, { token: res.data.token, userInfo: res.data.userInfo }); var name = res.data.userInfo.nickname; getIndexData().then(res =>{ if(name == res.data.login_nickname){ vm.tipIsVisable = true } }) }) .catch(res => { uni.hideLoading(); uni.showToast({ title: res.msg, icon: 'none', duration: 2000 }); }); }) .catch(res => { uni.hideLoading(); }); }, //快手小程序登录 async getKSUserProfile(vm) { let that = this const app = getApp(); uni.showLoading({ title: '正在登录中' }); let provider = "kuaishou" uni.checkSession({ success(res) { return uni.getUserInfo({ provider: provider, withCredentials: true, success: function (res) { uni.login({ provider: provider, success: function (loginRes) { let userInfo = res; userInfo.code = loginRes.code; userInfo.spread_spid = app.globalData.spid || 0; //获取推广人ID userInfo.agent_id=app.globalData.agent_id || 0 userInfo.type = provider Routine.authUserInfo(userInfo).then(res => { uni.hideLoading(); store.commit("app/" + SET_LOGIN, { token: res.data.token, userInfo: res.data.userInfo }); }).catch(res => { uni.hideLoading(); uni.showToast({ title: res.msg, icon: 'none', duration: 2000 }); }); }, fail: function (err) { uni.hideLoading(); uni.showToast({ title: err.msg, icon: 'none', duration: 2000 }); } }); }, fail: function (err) { uni.hideLoading(); console.log(err); } }) }, fail: function (err) { uni.hideLoading(); uni.login({ provider: provider, success: function () { that.getKSUserProfile() }, fail: function (err) { uni.hideLoading(); uni.showToast({ title: err.msg, icon: 'none', duration: 2000 }); } }); } }) }, //抖音小程序登录 async getDYUserProfile(vm, userInfo) { const app = getApp(); let provider = 'toutiao'; uni.showLoading({ title: '正在登录中' }); uni.login({ provider: provider, success: function (loginRes) { console.log(loginRes); userInfo.code = loginRes.code; userInfo.spread_spid = app.globalData.spid || 0; //获取推广人ID userInfo.agent_id=app.globalData.agent_id || 0 userInfo.type = provider Routine.authUserInfo(userInfo).then(res => { uni.hideLoading(); store.commit("app/" + SET_LOGIN, { token: res.data.token, userInfo: res.data.userInfo }); }).catch(res => { uni.hideLoading(); uni.showToast({ title: res.msg, icon: 'none', duration: 2000 }); }); }, fail: function (err) { uni.hideLoading(); uni.showToast({ title: err.msg, icon: 'none', duration: 2000 }); } }); }, /* 微信APP登录 */ wxAppLogin(vm) { const app = getApp(); let provider = 'weixin'; uni.showLoading({ title: '正在登录中' }); uni.login({ provider: provider, success: function (loginRes) { // 获取用户信息 uni.getUserInfo({ provider: provider, success: function (infoRes) { let userInfo = {}; userInfo.encryptedData = JSON.stringify(infoRes.userInfo) userInfo.code = loginRes.code; userInfo.spread_spid = app.globalData.spid || 0; //获取推广人ID userInfo.agent_id=app.globalData.agent_id || 0; // #ifdef MP-WEIXIN userInfo.type = 'weixin' // #endif // #ifndef MP-WEIXIN userInfo.type = 'wxapp' // #endif Routine.authUserInfo(userInfo).then(res => { uni.hideLoading(); store.commit("app/" + SET_LOGIN, { token: res.data.token, userInfo: res.data.userInfo }); vm.$emit("login-close"); }).catch(res => { console.log(res); uni.hideLoading(); uni.showToast({ title: res.msg, icon: 'none', duration: 2000 }); }); }, fail() { uni.showToast({ title: `获取用户信息失败`, icon: 'none', duration: 2000 }) }, complete() { uni.hideLoading() } }); }, fail: function (err) { console.log(err); uni.hideLoading(); uni.showToast({ title: err.msg, icon: 'none', duration: 2000 }); } }); }, jumpLogin(vm,currentAvatar,username) { /*#ifdef MP-WEIXIN */ // return this.getUserProfile(vm,currentAvatar,username); uni.navigateTo({ url: "/pages/login/index" }); /* #endif */ /*#ifdef MP-KUAISHOU */ return this.getKSUserProfile(vm) /* #endif */ // #ifdef APP-PLUS console.log('APP-PLUS'); // vm.loginShow = true; uni.navigateTo({ url: "/pages/login/index" }); //#endif // #ifdef H5 console.log('H5', this.isWeixin(), vm.loginShow === undefined); uni.navigateTo({ url: "/pages/login/index" }); // if (this.isWeixin()) { // return uni.redirectTo({ // url: "/pages/login/wechat" // }); // } else if (vm.loginShow === undefined) { // uni.navigateTo({ // url: "/pages/login/index" // }); // } else { // vm.loginShow = true; // } // #endif }, isAndroid() { let u = navigator.userAgent; return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; } }