当前位置:网站首页>Node - generate wechat permission verification configuration
Node - generate wechat permission verification configuration
2022-07-02 00:20:00 【A walking sheep】
1. Load required dependencies
cnpm i -S sha1 axios
2. establish 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"
/* Get wechat access_token */
async getAccessToken() {
if ((Date.now() - tokenUpdateTime || 0) < (1000 * 60 * 60 * 2)) {
console.log("token It hasn't failed yet :", 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 Acquisition failure :" + errcode);
}
if (access_token) {
accessToken = access_token;
tokenUpdateTime = Date.now();
return accessToken;
}
}
/* obtain jsapi_ticket */
async getJsapiTicket() {
if ((Date.now() - ticketUpdateTime || 0) < (1000 * 60 * 60 * 2) && (Date.now() - tokenUpdateTime || 0) < (1000 * 60 * 60 * 2)) {
console.log("ticket It hasn't failed yet :", 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;
}
}
/* Generate random string */
createNonceStr() {
return Math.random().toString(36).substring(2, 15);
}
/* Get the current timestamp */
createTimestamp() {
return parseInt(new Date().getTime() / 1000) + '';
}
/* Sort splicing */
raw(args,isToLowerCase = true) {
let keys = Object.keys(args).sort(); // obtain args The key value array of the object , And for all parameters to be signed, according to the field name ASCII Code order from small to large ( Dictionary order )
let newArgs = {
}
keys.forEach(key => {
newArgs[isToLowerCase ? key.toLowerCase() : key] = args[key];
})
let string = '';
for (let k in newArgs) {
// Loop new object , Concatenate into strings
string += `&${
k}=${
newArgs[k]}`
}
string = string.substring(1)// Intercept the string after the first character ( Remove the first one '&')
return string;
}
/** * WeChat jssdk Signature algorithm * @param url For signature url , Note that it must be obtained dynamically * @param nonceStr Random string * @param timestamp Time stamp * @return sha1 Algorithm encrypted string */
async jssdkSign(url, nonceStr, timestamp) {
let ret = {
jsapi_ticket: await this.getJsapiTicket(),
nonceStr, timestamp, url,
}
let str = this.raw(ret) // Sort and splice into strings
return sha1(str) // return sha1 Encrypted string
}
/* Generate jssdk To configure */
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. Use
const WxJsApiService = require("wxJsApiService.js")
let url = "http://location:8080" // The address of the web page , You need to access the Internet
new WxJsApiService().createJssdkConfig(url).then(res=>{
console.log(res)
})
// or
let config = await new WxJsApiService().createJssdkConfig(url)
// Returns the parameter
//{ appid, sign, timestamp, nonceStr }
TIP Refer to this article for configuration injection https://blog.csdn.net/qq812457115/article/details/125043544
边栏推荐
- [QT] solve the problem that QT MSVC 2017 cannot compile
- Which app is better and more secure for stock mobile account opening
- Using SqlCommand objects in code
- GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
- const // It is a const object... class nullptr_ t
- Talents come from afar, and Wangcheng district has consolidated the intellectual base of "strengthening the provincial capital"
- Data analysis methodology and previous experience summary [notes dry goods]
- UDS bootloader of s32kxxx bootloader
- Qt5.12.9 migration tutorial based on Quanzhi H3
- LeetCode中等题题分享(5)
猜你喜欢
Linux CentOS7安装Oracle11g的超完美新手教程
![[cmake] cmake configuration in QT Creator](/img/e3/1cf76f88eaddb5d32184523dfb049c.png)
[cmake] cmake configuration in QT Creator
![[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

如何提升数据质量

What is ThreadLocal memory leak and how to solve it

Mysql database driver (JDBC Driver) jar package download

Qt5.12.9 migration tutorial based on Quanzhi H3

Review data desensitization system

Relatively easy to understand PID understanding

Openvino model performance evaluation tool DL workbench
随机推荐
Flow control statement of SQL data analysis [if, case... When detailed]
Practical calculation of the whole process of operational amplifier hysteresis comparator
Qt5.12.9 migration tutorial based on Quanzhi H3
13 MySQL constraint
微信小程序缓存过期时间的相关设置(推荐)
【opencv】train&test HOG+SVM
Linux centos7 installation Oracle11g super perfect novice tutorial
Dongge cashes in and the boss retires?
Node——添加压缩文件
Pytorch learning record
起床困难综合症(按位贪心)
[CTF] bjdctf 2020 Bar _ Bacystack2
九州云与英特尔联合发布智慧校园私有云框架,赋能教育新基建
Openvino model performance evaluation tool DL workbench
【QT】Qt 使用MSVC2017找不到编译器的解决办法
Accelerator systems initiative is an independent non-profit organization
Relatively easy to understand PID understanding
ERP项目施行计划的目的是什么?
From 20s to 500ms, I used these three methods
leetcode96不同的二叉搜索樹