微信公众号开发之工程化

为了实现代码的复用、以后好维护和管理代码,这里我们将目录进行重新管理

目录

目录

在这里插入图片描述

功能

  • 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("服务器启动成功");
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值