当前位置:网站首页>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
边栏推荐
- Digital transformation has a long way to go, so how to take the key first step
- USB-IF协会与各种接口的由来
- Guide d'installation du serveur SQL
- Windows installation WSL (II)
- 一个实习生的CnosDB之旅
- Kyushu cloud and Intel jointly released the smart campus private cloud framework, enabling new infrastructure for education
- cookie、session、tooken
- Node——生成微信权限验证配置
- Regular expression collection
- [QT] solve the problem that QT MSVC 2017 cannot compile
猜你喜欢
Practical calculation of the whole process of operational amplifier hysteresis comparator
Flow control statement of SQL data analysis [if, case... When detailed]
Ldr6035 smart Bluetooth audio can continuously charge and discharge mobile devices
Guide d'installation du serveur SQL
回顾数据脱敏系统
[QT] solve the problem that QT MSVC 2017 cannot compile
S32Kxxx bootloader之UDS bootloader
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
heketi 记录
起床困难综合症(按位贪心)
随机推荐
【QT】Qt 使用MSVC2017找不到编译器的解决办法
Difficult to get up syndrome (bit by bit greed)
Guide d'installation du serveur SQL
微信小程序缓存过期时间的相关设置(推荐)
【模板】自适应辛普森积分
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
- Oui. Env. Fichier XXX, avec constante, mais non spécifié
Regular expression collection
【QT】QtCreator卸载与安装(非正常状态)
GCC compilation
Timer和ScheduledThreadPoolExecutor的区别
USB-IF协会与各种接口的由来
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
比较通俗易懂的PID理解
Node——Egg 创建本地文件访问接口
Use the htaccess file to prohibit the script execution permission in the directory
Shell custom function
Comprehensive usage and case questions of sub query of SQL data analysis [patient sorting]
SQL Server Installation Guide
[QT] test whether QT can connect to the database