当前位置:网站首页>Node——生成微信权限验证配置
Node——生成微信权限验证配置
2022-07-02 00:15:00 【一只漫步前行的羊】
1. 加载所需依赖
cnpm i -S sha1 axios
2. 创建wxJsApiService.js
const sha1 = require("sha1")
const axios = require("axios")
let accessToken = null
let jsapiTicket = null
let tokenUpdateTime = null
let ticketUpdateTime = null
class WxJsApiService {
appid = "appid"
secret = "secret"
/* 获取微信access_token */
async getAccessToken() {
if ((Date.now() - tokenUpdateTime || 0) < (1000 * 60 * 60 * 2)) {
console.log("token还没失效:", accessToken);
return accessToken;
}
const {
access_token, errcode } = await new Promise((resolve, reject) => {
axios.get("https://api.weixin.qq.com/cgi-bin/token", {
params: {
grant_type: "client_credential",
appid: this.appid,
secret: this.secret
}
}).then(response => {
resolve(response.data);
}).catch(err => {
reject(err);
})
})
if (errcode) {
return new Error("token获取失败:" + errcode);
}
if (access_token) {
accessToken = access_token;
tokenUpdateTime = Date.now();
return accessToken;
}
}
/* 获取jsapi_ticket */
async getJsapiTicket() {
if ((Date.now() - ticketUpdateTime || 0) < (1000 * 60 * 60 * 2) && (Date.now() - tokenUpdateTime || 0) < (1000 * 60 * 60 * 2)) {
console.log("ticket还没失效:", jsapiTicket);
return jsapiTicket;
}
const {
ticket } = await new Promise(async (resolve, reject) => {
axios.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket", {
params: {
access_token: await this.getAccessToken(),
type: "jsapi"
}
}).then(response => {
resolve(response.data);
}).catch(err => {
reject(err);
})
})
if (ticket) {
jsapiTicket = ticket;
ticketUpdateTime = Date.now();
return jsapiTicket;
}
}
/* 生成随机字符串 */
createNonceStr() {
return Math.random().toString(36).substring(2, 15);
}
/* 获取当前时间戳 */
createTimestamp() {
return parseInt(new Date().getTime() / 1000) + '';
}
/* 排序拼接 */
raw(args,isToLowerCase = true) {
let keys = Object.keys(args).sort(); //获取args对象的键值数组,并对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)
let newArgs = {
}
keys.forEach(key => {
newArgs[isToLowerCase ? key.toLowerCase() : key] = args[key];
})
let string = '';
for (let k in newArgs) {
// 循环新对象,拼接为字符串
string += `&${
k}=${
newArgs[k]}`
}
string = string.substring(1)// 截取第一个字符以后的字符串(去掉第一个'&')
return string;
}
/** * 微信jssdk签名算法 * @param url 用于签名的 url ,注意必须动态获取 * @param nonceStr 随机字符串 * @param timestamp 时间戳 * @return sha1算法加密的字符串 */
async jssdkSign(url, nonceStr, timestamp) {
let ret = {
jsapi_ticket: await this.getJsapiTicket(),
nonceStr, timestamp, url,
}
let str = this.raw(ret) // 排序拼接为字符串
return sha1(str) // 返回sha1加密的字符串
}
/* 生成jssdk配置 */
async createJssdkConfig(url) {
const timestamp = this.createTimestamp()
const nonceStr = this.createNonceStr()
return {
appid:this.appid,
sign: await this.jssdkSign(url,nonceStr,timestamp),
timestamp,
nonceStr
}
}
}
module.exports = WxJsApiService
3. 使用
const WxJsApiService = require("wxJsApiService.js")
let url = "http://location:8080" //网页访问的地址,需外网可访问
new WxJsApiService().createJssdkConfig(url).then(res=>{
console.log(res)
})
//或
let config = await new WxJsApiService().createJssdkConfig(url)
//返回参数
//{ appid, sign, timestamp, nonceStr }
TIP 配置注入可参考这个文章https://blog.csdn.net/qq812457115/article/details/125043544
边栏推荐
- 数据库--SqlServer详解
- It's nothing to be utilitarian!
- Kubernetes resource object introduction and common commands (III)
- Relatively easy to understand PID understanding
- 智能运维实战:银行业务流程及单笔交易追踪
- 北京炒股开户选择手机办理安全吗?
- Guide d'installation du serveur SQL
- SQL Server 安裝指南
- 实例讲解将Graph Explorer搬上JupyterLab
- Is it safe to buy funds in a securities account? Where can I buy funds
猜你喜欢
![Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]](/img/3a/cced28a2eea9f9a0d107baabd01119.png)
Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]

Using multithreaded callable to query Oracle Database

RPA教程01:EXCEL自动化从入门到实操

Heketi record

How to solve the image pop-up problem when pycharm calls Matplotlib to draw

【QT】對於Qt MSVC 2017無法編譯的問題解决

leetcode96不同的二叉搜索樹
![[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler](/img/35/e458fd437a0bed4bace2d6d65c9ec8.png)
[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler

Asp . Text of automatic reply to NETCORE wechat subscription number

毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
随机推荐
E-commerce RPA robot helps brand e-commerce to achieve high traffic
leetcode96不同的二叉搜索树
Windows installation WSL (II)
. env. XXX file, with constant, but undefined
数据分析方法论与前人经验总结【笔记干货】
在证券账户上买基金安全吗?哪里可以买基金
How excel opens CSV files with more than one million lines
Mysql database driver (JDBC Driver) jar package download
EMC circuit protection device for surge and impulse current protection
[C #] dependency injection and Autofac
[cmake] cmake configuration in QT Creator
Relatively easy to understand PID understanding
Is it safe to choose mobile phone for stock trading account opening in Beijing?
时间复杂度与空间复杂度
如何提升数据质量
Niuke - Practice 101 - reasoning clown
Linux centos7 installation Oracle11g super perfect novice tutorial
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
Openwrt enable kV roaming
Soft exam information system project manager_ Compiled abbreviations of the top ten management processes to help memory recitation - -- software test advanced information system project manager 054