如何使用 Python 验证 ReCaptcha 响应服务器端?

dbr*_*rrt 3 python recaptcha reactjs

我想检查react-google-recaptcha在我的注册表单中使用生成的客户端的响应。不幸的是,我不知道如何使用 Python 验证它的服务器端。

我试过recaptcha-clienthttps://pypi.python.org/pypi/recaptcha-client,但它似乎期待来自生成的 iframe 直接使用相同的库的响应。

dbr*_*rrt 5

它实际上非常简单,并且不需要库来执行此验证,遵循 Google 的文档:https : //developers.google.com/recaptcha/docs/verify

我只需要在地址中编码我的参数并向谷歌服务器发送请求,这是我的代码,请注意我使用的是 Flask,但任何 Python 后端的原理都是相同的:

from urllib.parse import urlencode
from urllib.request import urlopen
import json


        URIReCaptcha = 'https://www.google.com/recaptcha/api/siteverify'
        recaptchaResponse = body.get('recaptchaResponse', None)
        private_recaptcha = '6LdXXXXXXXXXXXXXXXXXXXXXXXX'
        remote_ip = request.remote_addr
        params = urlencode({
            'secret': private_recaptcha,
            'response': recaptchaResponse,
            'remote_ip': remote_ip,
        })

        # print params
        data = urlopen(URIReCaptcha, params.encode('utf-8')).read()
        result = json.loads(data)
        success = result.get('success', None)

        if success == True:
            print 'reCaptcha passed'
        else:
            print 'recaptcha failed'
Run Code Online (Sandbox Code Playgroud)