1.公众号->基本配置->服务器配置
在配置服务器完成后,点击提交的前提下,需要在服务器部署一小段代码,用来认证服务器。
但是官方给出的示例代码有问题,附连接
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
下面的连接是本人在官网翻到的另外的代码示例,但同样有问题
https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html#_2-5-%E7%A0%81%E4%BB%A3%E7%A0%81
上述连接部署后都会显示认证失败!
2.解决办法
本人使用python,因为比较懒,方便快捷。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2024/01/24 下午6:26
@file: test
@author: nothing4any
Description:
"""
import asyncio
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import os
from fastapi.requests import Request
from pydantic import BaseModel
import hashlib
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
async def hadnle_token(signature: str, echostr: str, timestamp: str, nonce: str):
try:
signature = signature
timestamp = timestamp
nonce = nonce
echostr = echostr
token = ''
al = [token, timestamp, nonce]
al.sort()
str = ''.join(al)
hashcode = hashlib.sha1(str.encode("utf-8")).hexdigest()
print(hashcode)
if hashcode == signature:
return echostr
else:
return False
except Exception as e:
return False
# app对象
app = FastAPI()
@app.get("/")
async def heart(request: Request, signature: str, echostr: str, timestamp: str, nonce: str):
res = await hadnle_token(signature, echostr, timestamp, nonce)
return int(res)
if __name__ == '__main__':
# uvicorn.config = None
uvicorn.run("app:app", host="0.0.0.0", port=80)
3.步骤
前提:使用python3版本
- 安装需要的运行包,依赖
pip install fastapi
pip install uvicorn
- 运行
假设代码文件为app.py
注意:代码文件名称有变,代码中最后一行中"app:app",冒号前的部分需要与文件名称一致
python3 app.py
4.公众号服务器配置认证
点击提交,等待1秒即可。