Code Monkey home page Code Monkey logo

recaptcha's Introduction

reCAPTCHA PHP client library

Build Status Coverage Status Latest Stable Version Total Downloads

reCAPTCHA is a free CAPTCHA service that protects websites from spam and abuse. This is a PHP library that wraps up the server-side verification step required to process responses from the reCAPTCHA service. This client supports both v2 and v3.

Installation

Composer (recommended)

Use Composer to install this library from Packagist: google/recaptcha

Run the following command from your project directory to add the dependency:

composer require google/recaptcha "^1.3"

Alternatively, add the dependency directly to your composer.json file:

"require": {
    "google/recaptcha": "^1.3"
}

Support for earlier versions of PHP

The 1.3 release moves to PHP 8 and up. For earlier versions, you will need to stay with the 1.2 releases.

Direct download

Download the ZIP file and extract into your project. An autoloader script is provided in src/autoload.php which you can require into your script. For example:

require_once '/path/to/recaptcha/src/autoload.php';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);

The classes in the project are structured according to the PSR-4 standard, so you can also use your own autoloader or require the needed files directly in your code.

Usage

First obtain the appropriate keys for the type of reCAPTCHA you wish to integrate for v2 at https://www.google.com/recaptcha/admin or v3 at https://g.co/recaptcha/v3.

Then follow the integration guide on the developer site to add the reCAPTCHA functionality into your frontend.

This library comes in when you need to verify the user's response. On the PHP side you need the response from the reCAPTCHA service and secret key from your credentials. Instantiate the ReCaptcha class with your secret key, specify any additional validation rules, and then call verify() with the reCAPTCHA response (usually in $_POST['g-recaptcha-response'] or the response from grecaptcha.execute() in JS which is in $gRecaptchaResponse in the example) and user's IP address. For example:

<?php
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com')
                  ->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
    // Verified!
} else {
    $errors = $resp->getErrorCodes();
}

The following methods are available:

  • setExpectedHostname($hostname): ensures the hostname matches. You must do this if you have disabled "Domain/Package Name Validation" for your credentials.
  • setExpectedApkPackageName($apkPackageName): if you're verifying a response from an Android app. Again, you must do this if you have disabled "Domain/Package Name Validation" for your credentials.
  • setExpectedAction($action): ensures the action matches for the v3 API.
  • setScoreThreshold($threshold): set a score threshold for responses from the v3 API
  • setChallengeTimeout($timeoutSeconds): set a timeout between the user passing the reCAPTCHA and your server processing it.

Each of the set*() methods return the ReCaptcha instance so you can chain them together. For example:

<?php
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com')
                  ->setExpectedAction('homepage')
                  ->setScoreThreshold(0.5)
                  ->verify($gRecaptchaResponse, $remoteIp);

if ($resp->isSuccess()) {
    // Verified!
} else {
    $errors = $resp->getErrorCodes();
}

You can find the constants for the libraries error codes in the ReCaptcha class constants, e.g. ReCaptcha::E_HOSTNAME_MISMATCH

For more details on usage and structure, see ARCHITECTURE.

Examples

You can see examples of each reCAPTCHA type in examples/. You can run the examples locally by using the Composer script:

composer run-script serve-examples

This makes use of the in-built PHP dev server to host the examples at http://localhost:8080/

These are also hosted on Google AppEngine Flexible environment at https://recaptcha-demo.appspot.com/. This is configured by app.yaml which you can also use to deploy to your own AppEngine project.

Contributing

No one ever has enough engineers, so we're very happy to accept contributions via Pull Requests. For details, see CONTRIBUTING

recaptcha's People

Contributors

8ctopus avatar akashhansda avatar anprok avatar brianteeman avatar cabloo avatar danielruf avatar dseguy avatar fbonzon avatar felipevolpatto avatar indygriffiths avatar ircmaxell avatar jajodiaraghav avatar jakubsvestka avatar kasimtan avatar luspa avatar marioblazek avatar orlitzky avatar pgrimaud avatar redian avatar rowan-m avatar seast avatar simonschaufi avatar sjinks avatar studiomax avatar xthiago avatar yingliu-google avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

recaptcha's Issues

Does not work with Google Charts

I prepared sample page... http://plnkr.co/edit/2oioaxLaFJnJ78oSxChh

  1. reCaptcha does not work on this page. You can find error "TypeError: Cannot read property 'register' of undefined" in console.
  2. If you comment this line " google.load("visualization", "1", {packages: ["corechart"],"callback":drawVisualization});" all works as expected.

Please advise what to do.
Thank you

Captcha is not repsonsive

The captcha is too wide for sidebars. The default login form for Drupal is in a sidebar. Please see the screenshot.

2015-05-14_102154

Iphone Recaptcha v2 have issue

Hello

I have seen when i open the recaptcha v2 in iPhone select the image it will show keyboard every time one selection of the image.

Like if there are four images in recaptcha then it will open the keyboard four times. every image selection open the image.

I have checked in iPhone 6

Use without composer?

Is it possible to use this script without using composer? Its not installed on my webspace, but I need the recaptcha php script...

Thank you

3rd Party Libraries Not Required for Recaptcha Example, But They Complicate Implementation of Recaptcha

The example works perfectly. It's even better after removing doctrine and reflection-docblock from the vendor directory.

Call me a retard, but the fact that the example at examples/example-captcha.php runs without doctrine and reflection-docback makes me think those libraries are not required.

Why are those libraries included in this sample?

I really don't want to add libraries that are not needed. I am bringing this up as an issue because the sample code should include only essential code, to avoid propagating libraries for no reason.

No response in some environments

Thank you for making reCAPTCHA available.
In my WordPress plugin I have it integrated, first the prior version, and just this week the current version. Some users are reporting problems however. Upon debugging, everything seem okay. The $params that are being sent to the service are all in order. However, there is no response from the reCAPTCHA service. The JSON string is empty when running print_r on it.
I don't really know how to debug this further, since on my setups everything works. The latest bugreport is here:
https://wordpress.org/support/topic/recaptcha-key-error?replies=24
In my testsetup I used the user's key with their domainname, and it just works. It reports success. Is there anyway that you can help?

Add cURL request method

I'm working on a locked-down server that disallows both file_get_contents and fsockopen, but it does support cURL. I've hacked together a Curl class that implements RequestMethod—it seems to work well for my purposes.

Is this something that would be appropriate for the project? If this makes sense I can write the tests for it as well, with a bit of guidance (I admit!—I've never written PHPUnit tests before...).

Force ipv4 on a dual stack machine.

I need to force ipv4 requests for recaptcha on a dual stack machine. Right now I do this using a copy of the Post RequestMethod by doing something like:

$host = gethostbyname('www.google.com';
$uri = sprintf('https://%s/recaptcha/api/siteverify', $host);
return file_get_contents($uri, false, $context);

Is this something worth submitting a PR for or would it be better as an option for the CURL RequestMethod I saw someone working on?

Multiple reCaptcha not working.

For some reasons I need to use two recaptchas instances in the same page. With the argument 'explicit' in URL that calls the API, I can render the two recaptchas, but, when I try to submit the second form is sent the first. I has checked all html markup and tryed to create triggers using submit values in POST to send the right form after submit, but the results are not good.

Any help will be appreciated! Thank you!

I think there is some issue here

when I tried to write the following on my script manually
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);

The response of captcha never be true
then I tried to replace it by:
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $remoteIp);

Is it true now, or there are there something errors?

recaptcha__en.js:161 Uncaught TypeError: Cannot read property 'postMessage' of null

Hi all,
I'm experiencing the following error on callback:

recaptcha__en.js:161 Uncaught TypeError: Cannot read property 'postMessage' of null

I have 1 recaptchas on my page and both point to the same callback which simply hides the recaptcha containers ($el.hide(), does not remove anything). The error only appears when interacting with the second recaptcha (support-contact-form).

Screenshare:
http://recordit.co/hjkJe4GNDl

Code:

var recaptchaEmail;
var recaptchaContactForm;
var myCallBack = function() {
//Render the recaptchaEmail on the element with ID "recaptcha-email"
recaptchaEmail = grecaptcha.render('recaptcha-email', {
  'sitekey' : 'xxxxxx',
  'theme' : 'dark',
  'callback' : recaptchaCallback,
});

//Render the recaptchaContactForm on the element with ID "recaptcha-contact-form"
recaptchaContactForm = grecaptcha.render('recaptcha-contact-form', {
  'sitekey' : 'xxxxxx',
  'theme' : 'dark',
  'callback' : recaptchaCallback,
});

var recaptchaCallback = function(e) {
  // remove recaptcha
  $('div.g-recaptcha').hide();

  showEmail();
  showSubmitForm();
};

// show email address
var showEmail = function() {
  var emailLink = $('<a href="mailto:[email protected]?Subject=THERMS - Support" target="_top">[email protected]</a>')
  $('#emailContainer').html(emailLink);
};

// show submit contact form button
var showSubmitForm = function() {
  var submitButton = $('<button class="btn btn-primary" id="submitContactusForm">Submit</button>');
  $('#submitContactButtonContainer').html(submitButton);
};

Proxy support

Older (ver 1.0) has proxy support -

define("RECAPTCHA_HTTP_PROXY", "proxy.foo.com");
define("RECAPTCHA_USE_PROXY", true);

do you plan to have this in ver 2.0?

composer.json

implementing be installed and used by composer.json

reCaptcha missing problem

Hi,
I use JaObelisk template on my site. I use ReCaptcaha and all properly configured. When you try to register using modules Ja Login (top right corner) all works.
But if you mess up the registration, module redirects you to the registration page and there is a problem. ReCaptcha does not appear and it is impossible to complete the registration.
I try to open registration page http://planinarenje.ba/registracija, but ReCaptcha missing. On this page ReCaptcha missing in ja Login module too. On all other pages Ja Login works properly.
I try with default Protostar template but is same
screen shot 2015-06-22 at 12 13 32

How can I solve it?
Thanks,
Midhat

How to integrate to phpBB 3.0.14 and others

I will describe how to install Google reCaptcha 2.0.

1. Get google codes from GitHub

https://github.com/google/recaptcha

2. Upload files

Upload files like this:

root@ :/var/www/phpBB3/includes/captcha/plugins# ls
autoload.php
・・・・
ReCaptcha

3. /var/www/phpBB3/styles/prosilver/template/captcha_recaptcha.html

<!-- IF S_TYPE == 1 -->
<div class="panel">
    <div class="inner"><span class="corners-top"><span></span></span>

    <h3>{L_CONFIRMATION}</h3>
    <p>{L_CONFIRM_EXPLAIN}</p>

    <fieldset class="fields2">
<!-- ENDIF -->

<!-- IF S_RECAPTCHA_AVAILABLE -->
    <dl>
    <dt><label>{L_CONFIRM_CODE}</label>:<br /><span>{L_RECAPTCHA_EXPLAIN}</span></dt>
    <dd>
        <script type="text/javascript">
        // <![CDATA[
        var RecaptchaOptions = {
            lang : '{LA_RECAPTCHA_LANG}',
            theme : 'clean',
            tabindex : <!-- IF $CAPTCHA_TAB_INDEX -->{$CAPTCHA_TAB_INDEX}<!-- ELSE -->10<!-- ENDIF -->
        };
        // ]]>
        </script>

                <div class="g-recaptcha" data-sitekey="{RECAPTCHA_PUBKEY}"></div>
                <script src='https://www.google.com/recaptcha/api.js'></script>

        <noscript>
        <div>

        </div>
        </noscript>

    </dd>
    </dl>
<!-- ELSE -->
{L_RECAPTCHA_NOT_AVAILABLE}
<!-- ENDIF -->

<!-- IF S_TYPE == 1 -->
    </fieldset>
    <span class="corners-bottom"><span></span></span></div>
</div>
<!-- ENDIF -->

4. /var/www/phpBB3/adm/style/captcha_recaptcha.html

<!-- IF S_RECAPTCHA_AVAILABLE -->
    <dl>
    <dd>
        <script type="text/javascript">
        // <![CDATA[
        var RecaptchaOptions = {
            lang : '{LA_RECAPTCHA_LANG}',
            theme : 'clean'
        };
        // ]]>
        </script>

            <div class="g-recaptcha" data-sitekey="{RECAPTCHA_PUBKEY}"></div>
                <script src='https://www.google.com/recaptcha/api.js'></script>

    <noscript>
    <div>
    </div>
    </noscript>

    </dd>
    </dl>
<!-- ELSE -->
{L_RECAPTCHA_NOT_AVAILABLE}
<!-- ENDIF -->

5. /var/www/phpBB3/includes/captcha/plugins/phpbb_recaptcha_plugin.php

@@ -22,6 +22,8 @@
    include($phpbb_root_path . 'includes/captcha/plugins/captcha_abstract.' . $phpEx);
 }

+require_once 'autoload.php';
+
 /**
 * @package VC
 */
@@ -33,10 +35,11 @@
    // We are opening a socket to port 80 of this host and send
    // the POST request asking for verification to the path specified here.
    var $recaptcha_verify_server = 'www.google.com';
-   var $recaptcha_verify_path = '/recaptcha/api/verify';
+        var $recaptcha_verify_path = '/recaptcha/api/siteverify';

    var $challenge;
    var $response;
+        var $g_recaptcha_response;

    // PHP4 Constructor
    function phpbb_recaptcha()
@@ -50,8 +53,7 @@

        $user->add_lang('captcha_recaptcha');
        parent::init($type);
-       $this->challenge = request_var('recaptcha_challenge_field', '');
-       $this->response = request_var('recaptcha_response_field', '');
+                $this->g_recaptcha_response = request_var('g-recaptcha-response', '');
    }

    function &get_instance()
@@ -213,80 +215,8 @@
        }
    }

-// Code from here on is based on recaptchalib.php
-/*
- * This is a PHP library that handles calling reCAPTCHA.
- * - Documentation and latest version
- *       http://recaptcha.net/plugins/php/
- * - Get a reCAPTCHA API Key
- *       http://recaptcha.net/api/getkey
- * - Discussion group
- *       http://groups.google.com/group/recaptcha
- *
- * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
- * AUTHORS:
- *   Mike Crawford
- *   Ben Maurer
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */

    /**
-   * Submits an HTTP POST to a reCAPTCHA server
-   * @param string $host
-   * @param string $path
-   * @param array $data
-   * @param int port
-   * @return array response
-   */
-   function _recaptcha_http_post($host, $path, $data, $port = 80)
-   {
-       $req = $this->_recaptcha_qsencode ($data);
-
-       $http_request  = "POST $path HTTP/1.0\r\n";
-       $http_request .= "Host: $host\r\n";
-       $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
-       $http_request .= "Content-Length: " . strlen($req) . "\r\n";
-       $http_request .= "User-Agent: reCAPTCHA/PHP/phpBB\r\n";
-       $http_request .= "\r\n";
-       $http_request .= $req;
-
-       $response = '';
-       if (false == ($fs = @fsockopen($host, $port, $errno, $errstr, 10)))
-       {
-           trigger_error('Could not open socket', E_USER_ERROR);
-       }
-
-       fwrite($fs, $http_request);
-
-       while (!feof($fs))
-       {
-           // One TCP-IP packet
-           $response .= fgets($fs, 1160);
-       }
-       fclose($fs);
-       $response = explode("\r\n\r\n", $response, 2);
-
-       return $response;
-   }
-
-   /**
    * Calls an HTTP POST function to verify if the user's guess was correct
    * @param array $extra_params an array of extra variables to post to the server
    * @return ReCaptchaResponse
@@ -296,23 +226,17 @@
        global $config, $user;

        //discard spam submissions
-       if ($this->challenge == null || strlen($this->challenge) == 0 || $this->response == null || strlen($this->response) == 0)
+                if ($this->g_recaptcha_response == null || strlen($this->g_recaptcha_response) == 0 )
        {
            return $user->lang['RECAPTCHA_INCORRECT'];
        }

-       $response = $this->_recaptcha_http_post($this->recaptcha_verify_server, $this->recaptcha_verify_path,
-           array(
-               'privatekey'    => $config['recaptcha_privkey'],
-               'remoteip'      => $user->ip,
-               'challenge'     => $this->challenge,
-               'response'      => $this->response
-           ) + $extra_params
-       );

-       $answers = explode("\n", $response[1]);

-       if (trim($answers[0]) === 'true')
+        $recaptcha = new ReCaptcha\ReCaptcha($config['recaptcha_privkey']);
+        $resp = $recaptcha->verify($this->g_recaptcha_response, $user->ip);
+
+        if ($resp->isSuccess())
        {
            $this->solved = true;
            return false;
@@ -323,23 +247,6 @@
        }
    }

-   /**
-   * Encodes the given data into a query string format
-   * @param $data - array of string elements to be encoded
-   * @return string - encoded request
-   */
-   function _recaptcha_qsencode($data)
-   {
-       $req = '';
-       foreach ($data as $key => $value)
-       {
-           $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
        }

-       // Cut the last '&'
-       $req = substr($req, 0, strlen($req) - 1);
-       return $req;
-   }
-}
-

6. Clear cache

root@ # rm /var/www/phpBB3/cache/*

7. Select reCaptcha in ACP

Select reCaptcha in ACP.
In the config page, set your public and private key.

Reference site:
http://forum.fujicoin.org/

Mailhide support?

  • Why has the mailhide support removed from the library?
  • Will it be added back soon?

Can't add new domain for existing key of v.1

Hi,
I'm currently using the previous version (v.1) and i just found out that apparently it has been updated and i have a trouble when i want to add new domain to my key.

In the previous version, i can easily add new domains with a form within apikey management page.
But now all i can find is this form at the bottom of the page, and I can't even understand how to use it (not even a friendly blue button to submit the change!?) and also when i hit enter, nothing happened.
screen shot 2016-01-14 at 3 44 51 pm

Well, what do i do now?
been looking through the doc but got no clue.
am i missed something?

I hope there's someone that point me out how to add new domain with the old version.
Or do i really need to upgrade?

Thanks

failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

in my website I have heavy request for reCaptcha,
and the captcha works fine for certain time, then I get the following error:

PHP Warning:  file_get_contents(https://www.google.com/recaptcha/api/siteverify): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
 in /home/ally/public_html/includes/library/ReCaptcha/RequestMethod/Post.php on line 68

then after half hour it works fine again..

How can I solve this issue?

FYI: allow_url_fopen is on

Photos are culturally insensitive

I am frustrated with the decision to move to a recaptcha strategy that asks the user to choose among different photos of food. I am building a website for use in Senegal, where the official language is French. How do I know someone in Senegal is going to recognize the foods shown to French language users? I have a hard enough time myself recognizing the pictures of hamburgers and sushi given the small size and low resolution of the photos. I dread to think how a vegan would react to having to pick out pictures of steak or the effects of separating pictures of food from pictures of beer and liquor on a recovering alcoholic. Please go back to using pictures of numbers, or at least provide a choice of the type of captcha test to give the user.

invalid-json response

I'm getting a response of invalid-json when I use the test example and the default send option (\ReCaptcha\ReCaptcha($secret)).

\ReCaptcha\RequestMethod\SocketPost() doesn't work on this server (error: Warning: fsockopen(): unable to connect to ssl://www.google.com:443 (Connection timed out)).

\ReCaptcha\RequestMethod\CurlPost() just runs and finally quits without a response from the server.

PHP 5.4.28
Linux server
I can post the info.php if needed.

Create proxy handlers for China.

I don't know where to start this discussion so I will start it here.

China has blocked recaptcha. The service is awesome, so I'd like to attempt to workaround this.

My idea would be this.

  1. All network requests are proxies through a server handler. "http://mydomain.com/recpatcha/http://google.com/recpatcha/image.jpeg" and "http://mydomain.com/recpatcha/http://google.com/recpatcha/script.js" would be proxied and served as if the content came from "mydomain.com".
  2. There may need to by some "live" modification of the scripts and styles returned from the proxy so that all urls and domains have the "http://mydomain.com/recaptcha" preappended to them.

What do you guys think? I haven't tried it yet, but does anyone know if there would be any hangups with this approach?

Injected Chars on reCaptcha's Responses

'Sup guys, how are you?

I've tried some diffrent sites, in different browsers and different OS's, computers and Access Points:

The reCaptcha's response returns the following characters BEFORE the correct response, thus invalidating the JSON: )]}'

Attached screenshot
screenshot from 2016-03-18 10-52-17

BTW: It was fine untill some days ago, and the webpage shown in the screenshot is not mine: I just found it on google for testing, after finding the problem in the sites I work on

missing autoload.php

There is line #34 in file /examples/example-captcha.php:
require_once __ DIR __ . '/../vendor/autoload.php';
But there is no such file in the library.

data-callback not firing

data-callback not getting called

The following is a very simple implementation of Google ReCaptcha using ReactJS. The attrs data-type and data-theme work, however the data-callback and data-expired-callback never get called. There are no errors thrown either.
Google Chrome Version 45.0.2454.101 (64-bit)

screen shot 2015-10-14 at 9 06 43 am

## Footer HTML
<script src='https://www.google.com/recaptcha/api.js'></script>

Javascript/JSX

(function() {
"use strict";

/**
 * Represents a Google ReCaptcha
 */
class Captcha extends COS.Input.Base
{

    getCaptchaResponse(response) {
        alert('working: ', response);
    }

    renderEdit()
    {
        return (
            <div
                ref="captcha"
                id="captcha"
                name="captcha"
                data-type="audio"
                data-theme="dark"
                data-sitekey="6Lc9fg4TAAAAAGYyFskow-g2b4IQ_rLvsLkHicuS"
                data-callback={this.getCaptchaResponse}
                className="g-recaptcha"></div>
        );
    }

}

    Captcha.makeDefaultProps({
        // Extend Default Props here
    });

    COS.Input.Captcha = Captcha;
})();

How it renders in the HTML

<div id="captcha" name="captcha" data-type="audio" data-theme="dark" data-sitekey="6Lc9fg4TAAAAAGYyFskow-g2b4IQ_rLvsLkHicuS" data-callback="function (response) {
        alert('working: ', response);
    }" class="g-recaptcha" data-reactid=".2.$29.8.$39.1.$60.1.1.$83.1.0.1.1:$311.1"><div>

Error code messages?

I'm wondering why the responds do not have a "error-message" that contains "The response parameter is invalid or malformed." just as one example.

e.g.

{
"success": false,
"error-codes": ["invalid-response"],
"error-message": "The response parameter is invalid or malformed." 
}

I have a case open at https://www.drupal.org/node/2599804 we need to catch and handle where the HTTP connection may fail, too. I think error handling could be optimized in the library as it seems very inflexible or at least I'm not sure where to place the error handling.

If the submit post the content in Drupal7Post class it may return these predefined error codes, but drupal_http_request can also fail like fsocket does and may return a http status code like stdClass Object ( [code] => -101 [error] => Network is unreachable ). In such a case the libary tells the user invalid-json = "The json response is invalid or malformed" what is highly misleading to the root cause. The issue is the http request and not the responds from google.

I could now add a lot of error handling inside RequestMethod->submit(), but it looks strange that error handling is done in submit() and fromJson().

Where would you add it?

callback method not firing in grecaptcha.render()

I am trying to have my callback fire once recaptacha i loaded however it won't load the callback.

Taken from https://developers.google.com/recaptcha/docs/display#example

        grecaptcha.render('example3', {
          'sitekey' : 'your_site_key',
          'callback' : verifyCallback,
          'theme' : 'dark'
        });

In my example I am doing:

            grecaptcha.render('recaptcha', {
                'sitekey': config.recaptcha.id,
                'callback': function(){
                      console.info('something'); 
                 }
            });

The callback function will never execute. reCacptcha will however load in the page.

Latest version of Chrome.

IE8 and earlier broken due to indexOf issue

The line:
return a.ua?0<=U(a.ua,5).indexOf("JS_THIRDEYE"):!1

Fails in IE8 and earlier with the error:
Object doesn't support property or method 'indexOf'

Adding in the usual indexOf polyfill does not fix the issue, maybe this is something handled internally.

Lots of reports of errors over the last 10 days or so on google groups about it.

Initial load sometimes doesnt load the callback

I've noticed that after I clear my cache and visit my website sometimes the Google reCaptcha doesnt load. I receive an error saying that my reCaptcha container div doesn't exist. Here is how i have it setup on my website.

I have an external javascript file with the following in it:

var CaptchaCallback = function(){

"use strict";

// var formIDs = [];
$("form").each(function() {
    var formID = $(this).data("formid"); 
    grecaptcha.render('sem-captcha-'+formID, {'sitekey' : '[site_key]'});
});

};

In my footer file, I am calling the scripts like this:

<script src='https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit' async defer></script>
<script async type="text/javascript" src="<?php echo $this->getThemePath(); ?>/js/site.reCaptcha.js"></script>

I'm loading these scripts inside of concrete5 page. Should i put the recaptcha/api.js call in my header file? Is there i can check to make sure that the api is loaded and my container div is available. I would also like to fire my callback only after the api and the site.reCaptcha.js file have completely loaded.

I think i want the page to load first, then the api and then my callback. That should guarantee everything is where it needs to be before the callback is fired.

Don't localize the widget automatically

This is very inconvenient, for example I'm from Sri Lanka and here we use 3 languages. (English, Sinhala, Tamil)

By default the ReCaptcha renders in Sinhala and majority of Tamil people don't understand Sinhala and there is no easy option to switch the language either.

I know the developer has option to override the language but this is really getting frustrated. The captcha itself is a difficult thing to solve sometimes and this makes things even more complicated for international users.

Another example is: Android startup screen, language is automatically chosen.

Why don't we let the developer decide the localization rather than setting it automatically because it's a functional part of the UI/UX?

Thanks

Seems like other users also have the same problem: https://groups.google.com/forum/#!topic/recaptcha/KQC8oN0-2sA
https://groups.google.com/forum/#!topic/recaptcha/Z9-DNgt447Y
https://groups.google.com/forum/#!topic/recaptcha/9ec6tVmk59w

image

Secure token support?

This is missing secure token support? I've so far been unable to generate a secure token in PHP which works with the recaptcha.

Anyone know how to generate AES/ECB/pdkdf2 token?!

fallback does not fire callback

The code below produces a recaptcha box with multiple images and checkboxes and "Select all images with pies." instructions and a "Verify" button.

    <script>
        function recaptcha_callback (){
            console.log('RECAPTCHA CALLBACK!!',arguments);
        }
    </script>
    <script src="https://www.google.com/recaptcha/api.js?fallback=true" async defer></script>
    <div class="g-recaptcha" data-sitekey="KEYKEYKEYKEY" data-callback="recaptcha_callback"></div>

The expected behavior is that after clicking all the checkboxes associated with images of pies, and then clicking "Verify", the console will log "'RECAPTCHA CALLBACK!!" . This fails. Instead, the recaptcha box refreshes with a new set of images.

If I remove the "?fallback=true" string then the script produces a more advanced recaptcha screen, and it has the expected behavior with its callback.

The reason I'm using "fallback=true" is because I'm trying to debug my Android 2.3 use case. Android 2.3 uses the fallback by default because it doesn't meet recaptcha's minimum requirements. My 2.3 users are unable to get past the recaptcha because of this issue.

symfony2 error

when I execute

$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

the app crash...

mode 1:

$recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_privatekey);

Warning: file_get_contents():
500 Internal Server Error - ContextErrorException
in vendor/google/recaptcha/src/ReCaptcha/RequestMethod/Post.php at line 68
...vendor\google\recaptcha\src\ReCaptcha\RequestMethod\Post.php', '68', array('params' => object(RequestParameters), 'peer_key' => 'CN_name', 'options' => array('http' => array('header' => 'Content-type: application/x-www-form-urlencoded ', 'method' => 'POST', 'content' => 'secret=************************&response=03AHJ_Vuu9kYDTuTfBDI26JBqZ0oUZpaX2P3DKycIbaheF4p9Xy1ZjayGfP6lzUqq95LTvi1mZyC0ds8P48umLA8yS7l_fyRHHKRlJo7IWjlCUN315QcIuAxxszqPBkOq3ZzAHEmmr89OFR39c5JIYQC_LPWiD-V9jrKyBH_6hB08oy5gmwlUoW-BqwXIHPdtc1uwo87dKZ-R4e4Om2qxzcP0Fa6E3sIBmAEs5A1AP7gYUoMkYI-Q3uUZfiPhqLKgXW3pgSlSYsjryWed-wAloVn6bTGP_ECA3kqjLDijl6SsULZp2RHBQ94cbS7QmjuHG6uO1QHJkYRHs7D5cAN4koqw39YHrtSwkDynFSMtPKOX8--3gOFuJCqYskjAvHjInU0JbgTlR6jJT_69cFnqjMcWIEeHOHK6h3HRW5T0c4-Css_7_AanpX-QOoMvyAAQY9wgFXij2PBJR&remoteip=127.0.0.1&version=php_1.1.0', 'verify_peer' => true, 'CN_name' => 'www.google.com')), 'context' => resource))

and mode 2:

$recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_privatekey, new \ReCaptcha\RequestMethod\SocketPost());

Warning: fsockopen():
500 Internal Server Error - ContextErrorException
in vendor/google/recaptcha/src/ReCaptcha/RequestMethod/Socket.php at line 50
...vendor\google\recaptcha\src\ReCaptcha\RequestMethod\Socket.php', '50', array('hostname' => 'ssl://www.google.com', 'port' => '443', 'errno' => '0', 'errstr' => '', 'timeout' => '30'))

suggestion?

Argument 2 passed to ReCaptcha\ReCaptcha::__construct() must be an instance of ReCaptcha\RequestMethod, instance of ReCaptcha\RequestMethod\Curl given

I encountered this interesting error with recaptcha while developing for Silex (Symfony2). The error reads:

Catchable fatal error: Argument 2 passed to ReCaptcha\ReCaptcha::__construct() must be an instance of ReCaptcha\RequestMethod, instance of ReCaptcha\RequestMethod\Curl given

The error is caused by:
$recaptcha = new \ReCaptcha\ReCaptcha( CAPTCHA_SECRET_KEY, new \ReCaptcha\RequestMethod\Curl() );

The fix is to modify the class definition, google/recaptcha/src/ReCaptcha/RequestMethod/Curl.php:
Original:

class Curl
{...}

Fixed:

class Curl extends Post
{...}

It appears that it must either "implements RequestMethod" or "extend" something that does.

Error on file_get_contents()

I get errors, when I upload the code on web server, with the php variable allow_url_fopen that is set 0 for prevent ddos attacks, I've tried using cURL instead of file_get_contents but my codes doesn't works, so I'm asking for help with that and I think that this problem occurred with other people.
Sorry for my bad english.

How to add multiple recaptchas

If I have 2 or 3 forms on the page, and I want to add recaptcha in every one of them, this will not work with this library, because only first added DIV with g-recaptcha class will be converted and the others will not. Can you please provide example on how to add multiple captchas to a page?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.