12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- const axios = require("axios");
- const cache = require("memory-cache");
- const crypto = require("crypto");
- const APPID = "wxaebc7f284686a36f";
- const APPSECRET = "44d74fc4e8c6a97a79c2eef23ca50123";
- /**
- * 获取 access_token(缓存 7000 秒)
- */
- async function getAccessToken() {
- const key = "access_token";
- let token = cache.get(key);
- if (!token) {
- const { data } = await axios.get(
- `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`
- );
- if (data.errcode) throw new Error(JSON.stringify(data));
- token = data.access_token;
- console.log("🚀 ~ getAccessToken ~ token:", token);
- cache.put(key, token, 7000 * 1000); // 毫秒
- }
- return token;
- }
- /**
- * 获取 jsapi_ticket(缓存 7000 秒)
- */
- async function getJsapiTicket() {
- const key = "jsapi_ticket";
- let ticket = cache.get(key);
- if (!ticket) {
- const token = await getAccessToken();
- const { data } = await axios.get(
- `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
- );
- if (data.errcode !== 0) throw new Error(JSON.stringify(data));
- ticket = data.ticket;
- cache.put(key, ticket, 7000 * 1000);
- }
- return ticket;
- }
- /**
- * 生成签名
- */
- function createSignature(ticket, url) {
- const nonceStr = Math.random().toString(36).substr(2, 15);
- const timestamp = Math.floor(Date.now() / 1000);
- const raw = `jsapi_ticket=${ticket}&noncestr=${nonceStr}×tamp=${timestamp}&url=${url}`;
- const signature = crypto.createHash("sha1").update(raw).digest("hex");
- return { appId: APPID, timestamp, nonceStr, signature };
- }
- /**
- * 验证微信服务器 Token(用于公众号后台配置)
- * @param {string} token - 公众号后台配置的 Token
- * @param {string} signature - 微信请求中的签名
- * @param {string} timestamp - 微信请求中的时间戳
- * @param {string} nonce - 微信请求中的随机数
- * @returns {boolean} 是否验证通过
- */
- function verifyWechatToken(token, signature, timestamp, nonce) {
- const arr = [token, timestamp, nonce].sort().join("");
- const sha1 = crypto.createHash("sha1").update(arr).digest("hex");
- return sha1 === signature;
- }
- module.exports = { getJsapiTicket, createSignature, verifyWechatToken };
|