alipay-emulator/utils/globalMethods.js

308 lines
7.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import CryptoJS from "crypto-js";
import * as uuid from "uuid";
import {
postJson
} from "@/utils/requests.js"
import pageData from "@/static/json/page.json"
import {
jsonString
} from "../uni_modules/uv-ui-tools/libs/function/test";
import '@batiao/batiao-sdk-uniapp-unimp';
export default {
install(app, options) {
// 水印
app.config.globalProperties.$watermark = () => {
// if(app.config.globalProperties.$isChristmasPeriod()){
// return "/static/lottie/christmas.json"
// }else{
return "/static/lottie/watermark.json"
// }
}
app.config.globalProperties.$apiUserEvent = async (type, adminData, uniData) => {
if (type != 'uni') {
if (!adminData.prefix) {
adminData.prefix = ".uni.alipay."
}
await postJson('a', 'api/user/event', {
type: adminData.type,
key: adminData.type + adminData.prefix + adminData.key,
value: adminData.value,
extra: JSON.stringify({
uni_version: app.config.globalProperties.$version,
...adminData.extra
}),
})
}
}
app.config.globalProperties.$toFiexd = (num, index = 2) => { //保留小数
return Number(num).toFixed(index)
}
// 跳转页面方法
app.config.globalProperties.$goRechargePage = (type, source = 'uni_alipay_other') => { //保留小数
let pages = getCurrentPages();
let currentPage = pages[pages.length - 1];
let currentUrl = currentPage.route;
currentUrl = pageData[currentUrl]
if (type) {
// 点击水印
app.config.globalProperties.$apiUserEvent('all', {
type: "click",
key: type,
value: type != "watermark" ? "关闭水印" : "点击右下角水印图标",
extra: {
page: currentUrl
}
}, {
type: 'click_' + type,
data: {
page: currentUrl
}
})
}
// 进入页面
app.config.globalProperties.$apiUserEvent('all', {
type: "event",
key: "payment_onload",
value: "进入充值页面",
extra: {
from: currentUrl
}
}, {
type: 'payment_onload',
data: {
from: currentUrl
}
})
uni.navigateTo({
url: '/pages/common/recharge/index?source=' + source
});
}
app.config.globalProperties.$isVip = () => {
let user = uni.getStorageSync('userInfo')
if (user.vip >= 2) {
return false
} else {
return true
}
}
//解密
const deCode = (str) => {
const key = CryptoJS.enc.Utf8.parse(uni.getStorageSync('decrypt'));
const iv = key.clone();
iv.sigBytes = 16;
iv.clamp();
let res = CryptoJS.AES.decrypt(str, key, {
iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
}).toString(CryptoJS.enc.Utf8);
res = JSON.parse(res);
return res;
};
// 加密签名
const sign = (config) => {
let key = uni.getStorageSync('encrypt')
const method = config.method;
if (!config.data) {
config.data = {};
}
config.data.timestamp = Math.floor(new Date().getTime() / 1000);
config.data.nonce = uuid.v4();
if (
method === "GET" ||
method === "DELETE" ||
method === "get" ||
method === "delete"
) {
const keys = Object.keys(config.data);
keys.sort();
for (const i in keys) {
keys[i] = keys[i] + "=" + encodeURIComponent(config.data[keys[i]]);
}
const temp = keys.join("&") + "&" + CryptoJS.MD5(key).toString();
config.data.signature = CryptoJS.MD5(temp).toString();
} else if (
method === "POST" ||
method === "PUT" ||
method === "post" ||
method === "put"
) {
if (!config.data) {
config.data = {};
}
const keys = Object.keys(config.data);
keys.sort();
for (const i in keys) {
keys[i] = keys[i] + "=" + encodeURIComponent(config.data[keys[i]]);
}
let temp = keys.join("&");
temp += "&" + JSON.stringify(config.data);
temp += "&" + CryptoJS.MD5(key).toString();
config.data.signature = CryptoJS.MD5(temp).toString();
}
console.log("config:", config)
return config
};
// 请求
app.config.globalProperties.$requestPromise = async (data,isCode=true) => {
let isTest = uni.getStorageSync('isTest')
//头部header浅拷贝避免改到 storage 缓存对象)
let header = { ...(uni.getStorageSync('header') || {}) }
//请求地址
let host
// #ifdef H5
host = data.url
// #endif
// #ifndef H5
host = uni.getStorageSync('host') + data.url
// #endif
// 签名
if(isCode){
if(isTest){
data = sign(data)
}
}else{
host="http://10.3.0.24:9209/"+ data.url
header['x-token']="bdf87a98-eef0-47df-9faf-41d547b0457e"
}
// 排序
const sortedKeys = Object.keys(data.data).sort();
let str = ''
for (const key of sortedKeys) {
str += '&' + key + '=' + encodeURIComponent(
data.data[key] == null ? '' : String(data.data[key])
);
}
str = str.replace('&', '?')
// 拼接URL
if(isTest){
host = host + str
}
// 鸿蒙 GET/DELETE 若再传 data 会二次拼进 query导致参数异常参数已在 URL 中
let requestData = data.data
// #ifdef APP-HARMONY
const method = (data.method || 'GET').toUpperCase()
if (method === 'GET' || method === 'DELETE') {
requestData = {}
}
// #endif
// 测试环境用 uni.request正式环境用宿主 nativeRequest
const api = isTest
? uni.request
: (uni.nativeRequest || uni.request)
const response = await new Promise((resolve, reject) => {
api({
url: host,
method: data.method,
data: requestData,
params: requestData,
header,
success: res => {
try {
if(isCode&&isTest){
res.data = deCode(res.data.data)
}
} catch (err) {
}
resolve(res.data);
},
fail: e => {
reject(e);
}
});
});
return response;
};
app.config.globalProperties.$getUserInfo = async () => {
try {
let user = await app.config.globalProperties.$requestPromise({
url: 'api/user',
method: "GET",
data: {}
})
console.log("模拟请求:", JSON.stringify(user))
if (user.code == 0) {
uni.setStorageSync('AppUser', user.data)
uni.setStorageSync('userInfo', user.data)
}
} catch (error) {
//TODO handle the exception
}
}
// 上传图片
app.config.globalProperties.$uploadImage = async (filePath) => {
//头部header
let header = uni.getStorageSync('header')
//请求地址
let host = uni.getStorageSync('host') + 'api/image/segment'
header['content-type'] = "multipart/form-data"
// // 排序
let data = {
method: 'POST',
data: {},
url: 'api/image/segment'
}
data = sign(data)
const sortedKeys = Object.keys(data.data).sort();
let str = ''
for (const key of sortedKeys) {
str += '&' + key + '=' + encodeURIComponent(data.data[key]);
}
str = str.replace('&', '?')
// 拼接URL
host = host + str
console.log(host);
console.log(data);
uni.uploadFile({
url: host, // 完整URL
filePath: filePath,
name: 'file',
method: "POST",
header: header,
formData: {
...data.data
},
success: (res) => {
console.log('1.上传成功:', JSON.stringify(res));
},
fail: (err) => {
console.error('2. 错误详情:', JSON.stringify(err));
},
complete: (res) => {
console.log('3. 上传完成');
}
});
};
app.config.globalProperties.$imageUpload = async (imagePath) => {
return new Promise((resolve, reject) => {
postJson('a', 'api/image/segment/base64', {
file: imagePath
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
};
}
};