python中使用flask接收对方get请求过来的参数 python开发微信公众号接口来自微信服务器的请求

python中使用flask接收对方get请求过来的参数
使用reqeust.args接收
from flask import Flask, request
myargs = request.args.to_dict()
signature = myargs.get("signature")
timestamp = myargs.get("timestamp")
nonce = myargs.get("nonce")
echostr = myargs.get("echostr")python编写来自微信公众号服务器的请求
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序
2)将三个参数字符串拼接成一个字符串进行sha1加密
3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
以下是python编写的事例:
wxapi_config = {
"token": "efsfsdfdsfsfdsfsfsdf",
"appID": "wx4bfsfssb",
"appsecret": "e043sfsfsfsfd464ef85f6",
}
# 微信公众号开发 - 微信请求的服务器
@app.route("/getwxtoken", methods=["get", "post"])
def getwxtoken():
# 获取微信服务器的请求参数,四个
myargs = request.args.to_dict()
signature = myargs.get("signature")
timestamp = myargs.get("timestamp")
nonce = myargs.get("nonce")
echostr = myargs.get("echostr")
myarr = [timestamp, nonce, wxapi_config.get("token")]
myarr.sort()
print(
"%s:%s"
% (
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"字典序排序后 %s " % (myarr),
)
)
mystr = "".join(myarr)
print(
"%s:%s"
% (
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"加密前的字符串 %s" % (mystr),
)
)
# 进行sha1加密
sha1 = hashlib.sha1()
sha1.update(mystr.encode("utf-8"))
sha1_digest = sha1.hexdigest()
print(
"%s:%s"
% (
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"sha1 后的十六进制结果 %s" % (sha1_digest),
)
)
if sha1_digest == signature:
return echostr
else:
return None















