为了实现代码的复用、以后好维护和管理代码,这里我们将目录进行重新管理
目录
目录
功能
config
index
主要保存一些配置
wechat
:这里主要放一些核心的功能库auth
:验证服务器的有效性
index
:入口文件
代码
config/index
// 存储相关配置
module.exports = {
appID:"wxf560f88100c1ae3b",
appsecret:"5d455f6c239b9ee76931129f525330bd",
token:"caicaicai"
}
wechat/auth.js
const sha1 = require("sha1")
const config = require("../config")
module.exports = () => {
return (req,res,next) => {
console.log(req.query);
/*
{
signature: '7e95c539aa7bff5bb1df5e6d99532154a52e7daa',
echostr: '7627813802972540923',
timestamp: '1653959538',
nonce: '38116457'
}
*/
const {signature,echostr,timestamp,nonce} = req.query
const {token} = config
// 1. 将`token`、`timestamp`、`nonce`三个参数进行字典序排序
const str = [token,timestamp,nonce].sort().join("")
// 2. 将三个参数字符串拼接成一个字符串进行`sha1`加密
const sha1str = sha1(str)
// 3. 开发者获得加密后的字符串可与 `signature` 对比,标识该请求来源于微信
if(sha1str == signature){
console.log(sha1str);
console.log(signature);
// 设置头,返回的类型为纯文本
res.set("Content-Type","text/plain");
res.send(echostr);
}else{
res.send(false)
}
}
}
index.js
const express = require("express")
const app = express()
const auth = require("./wechat/auth")
// 应用中间件
app.use(auth())
app.listen(4000, () => {
console.log("服务器启动成功");
});