漆黑天使复活 2023-03-31 20:13 采纳率: 44.4%
浏览 45
已结题

微信公众号接python/django服务器验证token问题

微信公众号,想要接python/django的服务器,卡在了第一步,验证token上,按照文档,获取signature 、timestamp 、nonce 后,验证是否一致,一致的话返回echostr,

def test(request):

    signature = request.GET.get("signature","")
    timestamp = request.GET.get("timestamp","")
    nonce = request.GET.get("nonce","")
    echostr=request.GET.get("echostr","")
    result={}
    result['signature']=signature
    result['timestamp']=timestamp
    result['nonce']=nonce
    result['echostr']=echostr
    tmpArr = [TOKEN, timestamp, nonce]
    tmpArr.sort()
    tmpStr = "".join(tmpArr) 
    tmpStr = hashlib.sha1(tmpStr.encode()).hexdigest() 
    if tmpStr == signature: 
        return echostr

    else: 
        return False

测试结果反馈
AttributeError: 'bool' object has no attribute 'get'

后来一步一步排查,发现,只要把最后return 改成return httpresponse或者return jsonresponse,他就可以正常反馈结果(用本地服务在浏览器直接输入请求连接做测试),但这样一来,在微信公众号的认证token中又没法认证,因为返回的是httpresponse/jsonresponse

怎么解决?

    if tmpStr == signature: 
        return httpresponse(echostr)


    else: 
        return httpresponse(echostr)

  • 写回答

5条回答 默认 最新

  • 77374067 2023-03-31 21:16
    关注

    该答案引用ChatGPT的部分内容:您可以尝试在返回 HttpResponse 或 JsonResponse 前,先将它们的实例化对象存储在变量中,并将该变量的值传递给后续的 if 和 else 语句,例如:

    from django.http import HttpResponse, JsonResponse
    
    def test(request):
        signature = request.GET.get("signature","")
        timestamp = request.GET.get("timestamp","")
        nonce = request.GET.get("nonce","")
        echostr = request.GET.get("echostr","")
    
        tmpArr = [TOKEN, timestamp, nonce]
        tmpArr.sort()
        tmpStr = "".join(tmpArr) 
        tmpStr = hashlib.sha1(tmpStr.encode()).hexdigest() 
    
        if tmpStr == signature: 
            response = HttpResponse(echostr)
        else: 
            response = HttpResponse(False)
        
        return response
    

    在上面的代码中,我们先实例化了 HttpResponse 对象并将其存储在 response 变量中。然后,我们将 response 变量传递给后续的 if 和 else 语句,以便根据条件进行相应的操作。

    请注意,在此示例中,我们使用 HttpResponse 对象将 echostr 或 False 返回给微信公众号。如果您需要返回 JSON 格式的数据,请使用 JsonResponse 替换 HttpResponse。

    希望这可以帮助您解决问题。

    评论

报告相同问题?

问题事件

  • 系统已结题 4月8日
  • 创建了问题 3月31日

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看