python3实现微信公众号确认己方服务器

def wechat_auth_required(log_base='[wechat_api]'):

    def decorator(view_func):
        @wraps(view_func)
        def wrapper(instance, request, *args, **kwargs):
            signature = request.GET.get('signature', None)
            echostr = request.GET.get('echostr', None)
            nonce = request.GET.get('nonce', None)
            timestamp = request.GET.get('timestamp', None)
            valid_flag = False
            if signature \
                    and nonce \
                    and timestamp:
                _list = sorted((
                    timestamp,
                    nonce,
                    'qeoi2mri13kr5jn42oorw'  #自己随便编一个,和微信公众号后台配置一致即可
                ))
                sha1 = hashlib.sha1()
                for item in _list:
                    sha1.update(item.encode('utf8'))
                hashcode = sha1.hexdigest()
                if hashcode == signature:
                    valid_flag = True
            if not valid_flag:
                logger.error(
                    '%s invalid param: [signature: %s] '
                    '[echostr: %s] [nonce: %s] [timestamp: %s]',
                    log_base, signature, echostr,
                    nonce, timestamp
                )
                return JsonResponse({'status': 1})
            else:
                return view_func(instance, request, *args, **kwargs)

        return wrapper

    return decorator


class WxCallbackView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    @wechat_auth_required('[WXRobot] [GET]')
    def get(self, request):
        echostr = request.GET.get('echostr')
        return HttpResponse(echostr)


你可能感兴趣的:(python,web,微信公众号)