geqintan commited on
Commit
83a19e7
·
1 Parent(s): 3399ae9
Files changed (1) hide show
  1. app.py +19 -14
app.py CHANGED
@@ -527,28 +527,33 @@ def greet_json():
527
  WECHAT_TOKEN="Rzwl2024"
528
  @app.get("/token")
529
  async def wechat_token_check(
530
- signature: str = Query(...),
531
- timestamp: str = Query(...),
532
- nonce: str = Query(...),
533
- echostr: str = Query(...),
534
  ):
535
- token = WECHAT_TOKEN
536
- print (f'signature: {signature}')
537
- print (f'timestamp: {timestamp}')
538
- print (f'nonce: {nonce}')
539
- print (f'echostr: {echostr}')
540
- print (f'token: {token}')
541
- tmp_list = sorted([token, timestamp, nonce])
542
  tmp_str = "".join(tmp_list)
 
 
543
  sha1 = hashlib.sha1()
544
  sha1.update(tmp_str.encode("utf-8"))
545
  hashcode = sha1.hexdigest()
546
 
547
- return echostr
 
 
548
 
 
549
  if hashcode == signature:
550
- return echostr # 校验成功,返回 echostr
551
  else:
552
- return {"error": "Invalid signature"} # 校验失败
 
 
 
 
 
553
 
554
  app.include_router(api_router)
 
527
  WECHAT_TOKEN="Rzwl2024"
528
  @app.get("/token")
529
  async def wechat_token_check(
530
+ signature: str = Query(..., description="微信加密签名"),
531
+ timestamp: str = Query(..., description="时间戳"),
532
+ nonce: str = Query(..., description="随机数"),
533
+ echostr: str = Query(..., description="验证字符串"),
534
  ):
535
+ # 1. 参数排序与拼接
536
+ tmp_list = sorted([WECHAT_TOKEN, timestamp, nonce])
 
 
 
 
 
537
  tmp_str = "".join(tmp_list)
538
+
539
+ # 2. SHA1加密生成签名
540
  sha1 = hashlib.sha1()
541
  sha1.update(tmp_str.encode("utf-8"))
542
  hashcode = sha1.hexdigest()
543
 
544
+ # 3. 调试日志(可选)
545
+ print(f"token: {WECHAT_TOKEN}, timestamp: {timestamp}, nonce: {nonce}")
546
+ print(f"生成签名: {hashcode}, 微信签名: {signature}")
547
 
548
+ # 4. 校验签名并返回结果
549
  if hashcode == signature:
550
+ return echostr # 校验成功,返回echostr
551
  else:
552
+ # 校验失败返回401错误[4](@ref)[5](@ref)
553
+ raise HTTPException(
554
+ status_code=401,
555
+ detail="签名验证失败",
556
+ headers={"WWW-Authenticate": "Bearer"}
557
+ )
558
 
559
  app.include_router(api_router)