How to validate a ReCaptcha response server side w

2019-05-30 10:01发布

问题:

I'd like to check a response from client generated using react-google-recaptcha in my Signup form. Unfortunately, I don't see how to validate it server side with Python.

I tried recaptcha-client : https://pypi.python.org/pypi/recaptcha-client, but it seems that it's expecting a response from a generated iframe directly with the same library.

回答1:

It was actually quite straightforward, and no library is required to perform this verification, following Google's documentation : https://developers.google.com/recaptcha/docs/verify

I just had to encode my parameters in the address and send a request to Google servers, here's my code, note that I'm using Flask, but the principle remains the same for any Python back-end :

import urllib
import json


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

        # print params
        data = urllib.urlopen(URIReCaptcha, params).read()
        result = json.loads(data)
        success = result.get('success', None)

        if success == True:
            print 'reCaptcha passed'
        else:
            print 'recaptcha failed'