当前位置:网站首页>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
边栏推荐
- How to realize parallel replication in MySQL replication
- Linux centos7 installation Oracle11g super perfect novice tutorial
- SQL数据分析之子查询的综合用法和案例题【耐心整理】
- Shell process control
- 记录一下大文件上传偶然成功偶然失败问题
- UVM tutorial
- Jielizhi, production line assembly link [chapter]
- ADO. Net SqlDataAdapter object
- Vue force cleaning browser cache
- Practical calculation of the whole process of operational amplifier hysteresis comparator
猜你喜欢
![Jielizhi, production line assembly link [chapter]](/img/1d/d1736fad33c428e61f450aad512ce0.png)
Jielizhi, production line assembly link [chapter]

时间复杂度与空间复杂度

数据分析方法论与前人经验总结【笔记干货】

Use vb Net to convert PNG pictures into icon type icon files

Leetcode 96 différents arbres de recherche binaires

leetcode96不同的二叉搜索樹

Kubernetes resource object introduction and common commands (III)

RPA tutorial 01: Excel automation from introduction to practice

USB-IF协会与各种接口的由来

GCC compilation
随机推荐
PWN attack and defense world cgpwn2
【mysql 07】GPG key retrieval failed: “Couldn‘t open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql-2022“
Is it safe and reliable to open an account in Caixue school and make new debts?
GCC compilation
Selectively inhibiting learning bias for active sampling
ADO. Net SqlCommand object
ADO. Net SqlConnection object usage summary
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
const // It is a const object... class nullptr_ t
UDS bootloader of s32kxxx bootloader
启牛学院开户安全的吗?开户怎么开?
使用VB.net将PNG图片转成icon类型图标文件
Using SqlCommand objects in code
ADO. Net SqlDataAdapter object
Difficult to get up syndrome (bit by bit greed)
S32Kxxx bootloader之UDS bootloader
Niuke - Practice 101 - reasoning clown
Windows 7 install MySQL error: 1067
[QT] solve the problem that QT MSVC 2017 cannot compile
leetcode96不同的二叉搜索樹