wechat.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const axios = require("axios");
  2. const cache = require("memory-cache");
  3. const crypto = require("crypto");
  4. const APPID = "wxaebc7f284686a36f";
  5. const APPSECRET = "44d74fc4e8c6a97a79c2eef23ca50123";
  6. /**
  7. * 获取 access_token(缓存 7000 秒)
  8. */
  9. async function getAccessToken() {
  10. const key = "access_token";
  11. let token = cache.get(key);
  12. if (!token) {
  13. const { data } = await axios.get(
  14. `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`
  15. );
  16. if (data.errcode) throw new Error(JSON.stringify(data));
  17. token = data.access_token;
  18. console.log("🚀 ~ getAccessToken ~ token:", token);
  19. cache.put(key, token, 7000 * 1000); // 毫秒
  20. }
  21. return token;
  22. }
  23. /**
  24. * 获取 jsapi_ticket(缓存 7000 秒)
  25. */
  26. async function getJsapiTicket() {
  27. const key = "jsapi_ticket";
  28. let ticket = cache.get(key);
  29. if (!ticket) {
  30. const token = await getAccessToken();
  31. const { data } = await axios.get(
  32. `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
  33. );
  34. if (data.errcode !== 0) throw new Error(JSON.stringify(data));
  35. ticket = data.ticket;
  36. cache.put(key, ticket, 7000 * 1000);
  37. }
  38. return ticket;
  39. }
  40. /**
  41. * 生成签名
  42. */
  43. function createSignature(ticket, url) {
  44. const nonceStr = Math.random().toString(36).substr(2, 15);
  45. const timestamp = Math.floor(Date.now() / 1000);
  46. const raw = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
  47. const signature = crypto.createHash("sha1").update(raw).digest("hex");
  48. return { appId: APPID, timestamp, nonceStr, signature };
  49. }
  50. /**
  51. * 验证微信服务器 Token(用于公众号后台配置)
  52. * @param {string} token - 公众号后台配置的 Token
  53. * @param {string} signature - 微信请求中的签名
  54. * @param {string} timestamp - 微信请求中的时间戳
  55. * @param {string} nonce - 微信请求中的随机数
  56. * @returns {boolean} 是否验证通过
  57. */
  58. function verifyWechatToken(token, signature, timestamp, nonce) {
  59. const arr = [token, timestamp, nonce].sort().join("");
  60. const sha1 = crypto.createHash("sha1").update(arr).digest("hex");
  61. return sha1 === signature;
  62. }
  63. module.exports = { getJsapiTicket, createSignature, verifyWechatToken };