目录
三、经过我的一波疯狂骚操作,完成了前端的签名操作,顺利进入到了wx配置,那么接下来就开始wx api的走秀吧!!!!
一、用到的方法封装
(1)生成UUI
// 生成一个随机的UUID作为动态值
export const UUID = (len?: number, radix?: number) => {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
const uuid: any[] = [];
let i: any = 0;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
} else {
let r;
// 中间用特殊字符链接
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '';
uuid[14] = '4';
// 长度不长于32位
for (i = 0; i < 32; i++) {
if (!uuid[i]) {
r = 0 | (Math.random() * 16);
uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
(2)生成时间戳或时间
const formatNumber = (n: any) => {
n = n.toString();
return n[1] ? n : `0${n}`;
};
export const formatTime = (date: { getFullYear: () => any; getMonth: () => number; getDate: () => any; getHours: () => any; getMinutes: () => any; getSeconds: () => any }, type: any) => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
switch (type) {
case 'YY':
return `${[year].map(formatNumber).join('-')}`;
case 'MM':
return `${[year, month].map(formatNumber).join('-')}`;
case 'DD':
return `${[year, month, day].map(formatNumber).join('-')}`;
case 'HH':
return `${[year, month, day].map(formatNumber).join('-')} ${[hour].map(formatNumber).join(':')}`;
case 'mm':
return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute].map(formatNumber).join(':')}`;
case 'ss':
return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
case 'HHmmss':
return `${[hour, minute, second].map(formatNumber).join(':')}`;
case 'unix':
const unix = `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
return Math.round(new Date(unix).getTime() / 1000);
default:
return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
}
};
(3)按ascii码从小到大排序
// 按ascii码从小到大排序
const sort_ascii = (obj: any) => {
let arr = [];
let num = 0;
for (let i in obj) {
arr[num] = i;
num++;
}
let sortArr = arr.sort();
//let sortObj = {}; //完成排序值
let str = ''; //自定义排序字符串
for (let i in sortArr) {
str += sortArr[i] + '=' + obj[sortArr[i]] + '&';
//sortObj[sortArr[i]] = obj[sortArr[i]];
}
//去除两侧字符串
let char = '&';
str = str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
return str;
//return sortObj;
};
(4)获取app当前页面对应的url
// 获取app当前页面对应的url
function getConfigUrl() {
let u = window.navigator.userAgent;
let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
//安卓需要使用当前URL进行微信API注册(即当场调用location.href.split('#')[0])
//iOS需要使用进入页面的初始URL进行注册,(即在任何pushstate发生前,调用location.href.split('#')[0])
let url = '';
if (isiOS) {
url = `${window.localStorage.getItem('_iosWXConfig_') || window.location.href.split('#')[0]}`; //获取初始化的url相关参数
} else {
url = window.location.href.split('#')[0];
}
return url;
}
二、获取微信配置的相关数据完成签名
(1)变量值
import { reactive } from 'vue';
const gridParams = reactive<any>({
timestamp: formatTime(new Date(), 'unix') + '',
noncestr: UUID(),
agentid: '',
corpid: '',
corpsecret: '',
jsApiList: ['checkJsApi', 'chooseImage'],
});
(2)获取access_token、通过access_token获取jsapi_ticket,拿到签名所需要的数据进行ASCII排序后SHA1加密
// apiGetAccessToken、apiGetSignature为接口封装的api
import { apiGetAccessToken, apiGetSignature } from '../封装api的路径';
const queryAccessToken = async () => {
let { timestamp, noncestr, corpid, corpsecret } = gridParams;
// 获取access_token
const { access_token } = await apiGetAccessToken({ corpid, corpsecret });
// 获取jsapi_ticket
const { ticket } = await apiGetSignature({ access_token });
// js判断是否js判断是否Android or IOS #之前的url
console.log('Android或IOS的URL: ', getConfigUrl());
// 拿到签名相关的数据obj
let result = { noncestr, jsapi_ticket: ticket, timestamp, url: getConfigUrl() };
console.log('签名相关的数据: ', result);
// 按ascii码从小到大排序
let ascii = await sort_ascii(result);
// sha1进行加密得到signature
let set_sha1 = await sha1(ascii);
// 获取到了signature,然后配置微信
handleStateGrid(set_sha1);
};
(3)拿到签名后进行微信配置
import wx from 'weixin-js-sdk';
const handleStateGrid = (signature: any) => {
const { timestamp, noncestr, corpid, jsApiList } = gridParams;
wx.config({
beta: true, // 调用wx.invoke形式的接口值时,该值必须为true。
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: corpid, // 必填,政务微信的cropID
timestamp, // 必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature, // 必填,签名,见附录1
jsApiList, // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function () {
console.log('wx.ready: success');
wx.checkJsApi({
jsApiList, // 需要检测的JS接口列表,所有JS接口列表见附录2,
success: function (res) {
console.log('wx.checkJsApi: ', res);
},
});
});
wx.error(function (res: { errMsg: any }) {
console.log('wx.error: ', res.errMsg);
});
};
三、经过我的一波疯狂骚操作,完成了前端的签名操作,顺利进入到了wx配置,那么接下来就开始wx api的走秀吧!!!!
wx.ready(function () {
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
quality: 0.8, //压缩质量,范围0~1,数值越小,质量越低,压缩率越高(仅对jpg有效)
success: function (res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表
console.log('拍照列表:', res, localIds);
},
});
});