基于Express的微信公众号开发

手机APP/开发
63
0
0
2024-05-08

image.png

JS-SDK鉴权流程

步骤一:绑定域名

微信公众号配置

微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

需要事先下载一个MP_verify_aCUsGn8IMhTP8vyx.txt文件,放在我们自己填写的域名的静态资源文件夹下去 保证我们可以通过域名路径+MP_verify_aCUsGn8IMhTP8vyx.txt的方式可以访问到该文件,已做验证
例如:我们想要配置aifoosen.applinzi.com域名>则我们要保证通过http://aifoosen.applinzi.com/MP_verify_aCUsGn8IMhTP8vyx.txtundefined可以访问到服务器上的这个文件

如图所示:

image.png

image.png

在服务上添加微信域名校验文件

上述第二步需要将文件下载好后上传到public目录下。因为我是使用的Express构建的服务。如图:

image.png

添加公众号IP白名单配置
微信公众平台进入“安全中心"的“IP白名单"里填写,跟js-sdk鉴权相关的所有ip 新浪云相关IP的位置:文档中心----入口与出口IP-----外网访问出口IP列表

如图:

image.png

步骤二:引入JS文件

在需要调用Js接口的页面引l入如下Js文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.4.0.js 官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

我在项目目录public中添加了index.html文件,并在该文件中引入了js文件。具体文件如下:

<html>

<head>
    <title>Express</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <!-- <script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->

    <script src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
</head>

<body>
    <h1>Express</h1>
    <p>Welcome to Express</p>
</body>

<script>
    axios.get('https://wx.ibitly.cn/jsapi', {
        url: encodeURIComponent(location.href.split('#')[0])
    }).then((res)=>{
        wx.config({
            debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: '', // 必填,公众号的唯一标识
            timestamp: '', // 必填,生成签名的时间戳
            nonceStr: '', // 必填,生成签名的随机串
            signature: '',// 必填,签名
            jsApiList: [] // 必填,需要使用的JS接口列表
        });
    })
    
</script>


</html>

项目层级:

image.png

步骤三、微信公众号服务器配置

编写公众号鉴权接口
参考文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

express-vercle/routes/index.js

var express = require('express');
var router = express.Router();
// 通过命令 npm i sha1 安装 sha1
var sha1 = require('sha1');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


/* weixin-鉴权接口 参考文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html*/
router.get('/wx-auth', function(req, res, next) {
  let {signature, timestamp, nonce, echostr} = req.query;
  let token = 'paidaxing';
  let array = [timestamp, nonce, token];
  array.sort(); // 字典排序
  let str = array.join('');
  let resultStr = sha1(str) // 对字符串str进行sha1进行加密
  if(resultStr === signature) {
    res.set('Content-Type', 'text/plain')
    res.send(echostr);
  }else {
    res.send('Error!!!!!!')
  }
});

module.exports = router;
配置公众号的服务器

如图所示:

image.png

image.png

好了,本章节到此告一段落。希望对你有所帮助,祝学习顺利。