当前位置:网站首页>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
边栏推荐
- 【CMake】Qt creator 里面的 cmake 配置
- 4. Object mapping Mapstercover
- Various global files related to [.Net core] program
- Jielizhi Bluetooth headset quality control and production skills [chapter]
- PHP reads ini or env type configuration
- 攻防演练复盘
- 启牛学院开户安全的吗?开户怎么开?
- GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
- Key points of security agreement
- 使用htaccess文件禁止目录里的脚本执行权限
猜你喜欢

Ldr6035 smart Bluetooth audio can be charged and released (5.9.12.15.20v) fast charging and fast releasing device charging

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

Windows10 install WSL (I) (wslregisterdistribution error)

Leetcode medium question sharing (5)

LDR6035智能蓝牙音响可对手机设备持续充放电方案

GCC compilation

Material design component - use bottomsheet to show extended content (I)

Asp .NetCore 微信订阅号自动回复之文本篇
![Jielizhi, production line assembly link [chapter]](/img/1d/d1736fad33c428e61f450aad512ce0.png)
Jielizhi, production line assembly link [chapter]

Relatively easy to understand PID understanding
随机推荐
实例讲解将Graph Explorer搬上JupyterLab
leetcode96不同的二叉搜索树
数据分析方法论与前人经验总结【笔记干货】
SQL Server 安装指南
[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler
Linux centos7 installation Oracle11g super perfect novice tutorial
Selectively inhibiting learning bias for active sampling
[embedded system course design] a single key controls the LED light
B tree and b+tree of MySQL
【CMake】Qt creator 里面的 cmake 配置
Shell process control
UDS bootloader of s32kxxx bootloader
微信小程序缓存过期时间的相关设置(推荐)
Digital transformation has a long way to go, so how to take the key first step
- Oui. Env. Fichier XXX, avec constante, mais non spécifié
SecurityUtils. getSubject(). How to solve the problem that getprincipal() is null
Regular expression collection
多表操作-一对一,一对多与多对多
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
Leetcode 96 différents arbres de recherche binaires