当前位置:网站首页>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
边栏推荐
- 【CMake】Qt creator 里面的 cmake 配置
- Kyushu cloud and Intel jointly released the smart campus private cloud framework, enabling new infrastructure for education
- I want to ask, which is the better choice for securities companies? I don't understand. Is it safe to open an account online now?
- Database -- sqlserver details
- Example explanation: move graph explorer to jupyterlab
- vs2015 AdminDeployment. xml
- SQL Server 安装指南
- 使用htaccess文件禁止目录里的脚本执行权限
- [QT] test whether QT can connect to the database
- - Oui. Env. Fichier XXX, avec constante, mais non spécifié
猜你喜欢

Shell process control

Windows10 install WSL (I) (wslregisterdistribution error)

基于全志H3的QT5.12.9移植教程

【QT】Qt 使用MSVC2017找不到编译器的解决办法
![[opencv450] hog+svm and hog+cascade for pedestrian detection](/img/55/cdf0bb8231ee59e34c8d5a9d6def23.png)
[opencv450] hog+svm and hog+cascade for pedestrian detection

S32Kxxx bootloader之UDS bootloader
![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]

. env. XXX file, with constant, but undefined

leetcode96不同的二叉搜索树

UDS bootloader of s32kxxx bootloader
随机推荐
cookie、session、tooken
mysql之B tree 以及 B+tree
Pytorch learning record
使用 ES 实现疫情地图或者外卖点餐功能(含代码及数据)
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
Database -- sqlserver details
如何提升数据质量
Which app is better and more secure for stock mobile account opening
13 MySQL constraint
使用htaccess文件禁止目录里的脚本执行权限
Jielizhi Bluetooth headset quality control and production skills [chapter]
Use pair to do unordered_ Key value of map
E-commerce RPA robot helps brand e-commerce to achieve high traffic
Niuke - Practice 101 - reasoning clown
Use the htaccess file to prohibit the script execution permission in the directory
. env. XXX file, with constant, but undefined
【CMake】Qt creator 里面的 cmake 配置
北京炒股开户选择手机办理安全吗?
USB-IF协会与各种接口的由来
I would like to ask, which securities is better for securities account opening? Is it safe to open a mobile account?