Files
oil-client-wechat/utils/api.js
2025-12-19 11:20:59 +08:00

99 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

const app = getApp()
function getCode(obj) {
var md4 = objKeySort(obj)
console.log(md4)
var md5 = require("md5.js");
console.log(md5.hex_md5(md4).toUpperCase());
var md5 = md5.hex_md5(md4).toUpperCase();
return md5;
}
function getTimestamp() {
var myDate = new Date();
var timestamp = formatTime(myDate.getTime(), "YMDHMS");
console.log(timestamp);
return timestamp;
}
function formatTime(value, type) {
// console.log("............" + value);
var dataTime = "";
var data = new Date();
data.setTime(value);
var year = data.getFullYear();
var month = addZero(data.getMonth() + 1);
var day = addZero(data.getDate());
var hour = addZero(data.getHours());
var minute = addZero(data.getMinutes());
var second = addZero(data.getSeconds());
if (type == "YMD") {
dataTime = year + "-" + month + "-" + day;
} else if (type == "YMDHMS") {
dataTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
} else if (type == "MDHMS") {
dataTime = month + "-" + day + " " + hour + ":" + minute + ":" + second;
// dataTime =123;
} else if (type == "HMS") {
dataTime = hour + ":" + minute + ":" + second;
} else if (type == "YM") {
dataTime = year + "-" + month;
}
return dataTime; //灏嗘牸寮忓寲鍚庣殑瀛楃涓茶緭鍑哄埌鍓嶇鏄剧ず
};
function addZero(val) {
if (val < 10) {
return "0" + val;
} else {
return val;
}
};
function apiHeader(obj) {
var timestamp = getTimestamp();
var sign = getCode(obj);
var data = {
appkey: 'mini_program_7ece3406-77f7-4939-8772-6918910f1c9f',
version: '2.0',
timestamp: timestamp,
sign: sign,
"Content-Type": "application/x-www-form-urlencoded"
}
return data
}
function objKeySort(obj) {//排序的函数
var timestamp = getTimestamp();
obj.appkey = 'mini_program_7ece3406-77f7-4939-8772-6918910f1c9f';
obj.version = '2.0';
obj.timestamp = timestamp;
var newkey = Object.keys(obj).sort();
  //先用Object内置类的keys方法获取要排序对象的属性名再利用Array原型上的sort方法对获取的属性名进行排序newkey是一个数组
var newObj = {};//创建一个新的对象,用于存放排好序的键值对
for (var i = 0; i < newkey.length; i++) {//遍历newkey数组
newObj[newkey[i]] = obj[newkey[i]];//向新创建的对象中按照排好的顺序依次增加键值对
}
console.log(newObj)
var objToStr=""
for (var key in newObj) {
objToStr = objToStr+ key + newObj[key]
}
delete obj.appkey;
delete obj.version;
delete obj.timestamp;
return objToStr;//返回排好序的新对象
}
// var obj = { name: "zhangsan", age: 8, ace: 5, nbme: "lisi" };//要排序的对象
// objKeySort(obj); //函数执行
module.exports = {
objKeySort: objKeySort,
apiHeader: apiHeader
}