关于javascript:Python接入微信公众号Token验证

35次阅读

共计 1391 个字符,预计需要花费 4 分钟才能阅读完成。

留神点

  1. 官网示例是 Pthon2 版本的,如果是 Python3 版本须要有改变
  2. 验证胜利返回 echostr 要是 数字格局的

公众号侧配置(公众号后盾 – 根本配置)

服务器侧配置

  1. 代码局部

官网示例(python2)

# -*- coding: utf-8 -*-
# filename: handle.py

import hashlib
import web

class Handle(object):
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "hello, this is handle view"
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "xxxx" #请依照公众平台官网 \ 根本配置中信息填写

            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print "handle/GET func: hashcode, signature:", hashcode, signature
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception, Argument:
            return Argument

python3 版本(Django)

class WeChatTokenViewSet(viewsets.ViewSet):
    def list(self, request):
        try:
            token = 'pTpKJrLR1qwaNat6mzUWXvVblHB1uZS3'
            timestamp = request.query_params.get('timestamp')
            nonce = request.query_params.get('nonce')
            echostr = request.query_params.get('echostr')
            signature = request.query_params.get('signature')
            list = [token, timestamp, nonce]
            list.sort()
            temp = ''.join(list)
            sha1 = hashlib.sha1(temp.encode('utf-8'))
            hashcode = sha1.hexdigest()
            print("handle/GET func: hashcode, signature:", hashcode, signature)
            if hashcode == signature:
                return Response(int(echostr), status=status.HTTP_200_OK)
            else:
                print('微信 Token 校验失败')
                return Response('', status=status.HTTP_200_OK)
        except Exception as e:
            print('微信 Token 解析失败', e)
            return Response('', status=status.HTTP_200_OK)

实现 Token 校验后

须要减少 IP 白名单 将服务器 IP 退出白名单

本文由一文多发经营工具平台 EaseWriting 公布

正文完
 0