:passport_control: Helper for Google's new noCAPTCHA (reCAPTCHA v2 & v3)

Overview

noCAPTCHA (new reCAPTCHA) Packagist License For PHP

Github Workflow Status Coverage Status Scrutinizer Code Quality SensioLabs Insight Github Issues

Packagist Packagist Release Packagist Downloads

By ARCANEDEV©

What is reCAPTCHA?

reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis engine to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.

New Google reCAPTCHA

Features

  • Framework agnostic package.
  • v2 (+ Invisible) & v3 reCaptcha are supported.
  • Easy setup & configuration.
  • Well documented & IDE Friendly.
  • Well tested with maximum code quality.
  • Laravel 4.2 to 8.x are supported.
  • PSR-7 Support (ServerRequest verification).
  • Made with ❤️ & .

Table of contents

  1. Installation and Setup
  2. Configuration
  3. Usage
  4. Extras
  5. FAQ

Contribution

Any ideas are welcome. Feel free to submit any issues or pull requests, please check the contribution guidelines.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

Comments
  • Don't validate captcha in testing environment

    Don't validate captcha in testing environment

    Hi,

    This isn't really an issue, just a suggestion in case anyone cares :)

    I'm trying to test my code with Laravel's handy helpers and MailThief for intercepting e-mails... But getting past the captcha with an automated script is obviously not so easy...

    To get around this, I read that some people just disable the captcha for testing. So to do this, I copied your validator and changed it like this:

        Validator::extend('nocaptcha', function($attribute, $value, $parameters, $validator) {
            unset($attribute);
    
            if (app()->environment('testing')) {
                return true;
            }
    
            return app('arcanedev.no-captcha')->verify($value, request()->getClientIp());
        });
    

    So basically, I just check if the environment is set to testing, which is the default for Laravel, and if so I always let it pass.

    I don't know if this is something you would want to include in your package, perhaps with configurable environments that should be skipped or something...

    enhancement tests 
    opened by ivanvermeyen 17
  • Trouble with Form macro in Laravel 5.5

    Trouble with Form macro in Laravel 5.5

    • noCaptcha Version: 5.0
    • Laravel Version: 5.5.3
    • PHP Version: 7.1

    Description:

    Trying to use Form::captcha() with error.

    Steps To Reproduce:

    Set up captcha with Form::captcha() instead of Captcha::display()


    I have this in one other Laravel 5.4 projects without issue.

    The problem lies in Arcanedev\NoCaptcha\NoCaptchaServiceProvider

    Trying to import Arcanedev\LaravelHtml\Contracts\FormBuilder and not being able to find it.

    Also, using Captcha::display() doesn't break the page, but it also doesn't display the actual captcha, though the div does exist.

    need help laravel 
    opened by rappasoft 11
  • Multiple noCaptcha

    Multiple noCaptcha

    Hello,

    Firstly thanks for the plugin...

    I am trying to add multiple captchas on a single page with laravel 4.2 using:

     public function scriptWithCallback(array $captchas, $callbackName = 'captchaRenderCallback')
    

    It does work but i need to refresh/reload the page for the captchas to render/appear in the page... I tried grepcaptcha.reset(); with no luck...

    Any ideas on how to deal with this? Thank you

    bug fixed 
    opened by pns2050 10
  • How to reset multiple captchas?

    How to reset multiple captchas?

    Hi! How can I reset captcha by opt_widget_id (as they say on google captcha docs)?

    When I try to reset captcha by attribute 'id' in div with 'g-recaptcha' class, it does not work. On StackOverflow there is a answer with that solution:

    var widgetId = grecaptcha.render(container);
    grecaptcha.reset(widgetId);
    

    but in \Arcanedev\NoCaptcha\NoCaptcha::renderCaptchas function you do render captchas without saving widget ID to anywhere

    return implode(PHP_EOL, array_map(function($captcha) {
        return "if (document.getElementById('$captcha')) { grecaptcha.render('$captcha', {'sitekey' : '{$this->siteKey}'}); }";
    }, $captchas));
    

    Maybe there is some function to get widgetID?

    feature request 
    opened by madaolex 6
  • Fails to display google images

    Fails to display google images

    Clicking on the "I'm not a robot" button causes the "waiting" cursor to appear, but nothing else happens. This is after following the installation instructions for a Laravel 5.2 application.

    opened by DA40 5
  • No scriptWithCallback() output in Laravel 5.2

    No scriptWithCallback() output in Laravel 5.2

    Hi,

    I'm a bit clueless about this one... I have a page (Laravel 5.2 blade file) with 2 forms. Each form successfully renders a captcha div:

    {!! Captcha::display('captcha1', ['data-theme' => 'dark']) !!}
    {!! Captcha::display('captcha2', ['data-theme' => 'dark']) !!}
    

    This results in:

    <div class="g-recaptcha" data-sitekey="XXXX" id="captcha1" name="captcha1" data-theme="dark"></div>
    

    But at the bottom of the page, the script doesn't get echo'd out:

    {!! Captcha::scriptWithCallback(['captcha1', 'captcha2']) !!}
    

    However, when I call this method with php artisan tinker, I do get the following output:

    >>> Captcha::scriptWithCallback(['captcha1', 'captcha2']);
    => """
       <script>\n
       var captchaRenderCallback = function() {\n
       if (document.getElementById('captcha1')) { grecaptcha.render('captcha1', {'sitekey' : 'XXXX'}); }\n
       if (document.getElementById('captcha2')) { grecaptcha.render('captcha2', {'sitekey' : 'XXXX'}); }\n
       };\n
       </script>\n
       <script src="https://www.google.com/recaptcha/api.js?hl=nl&onload=captchaRenderCallback&render=explicit" async defer></script>
       """
    >>>
    

    If I paste this script on the page, the captchas work (although they don't have the dark theme).

    Do you have any ideas why I'm not getting any output?

    need help 
    opened by ivanvermeyen 5
  • Interface 'Illuminate\Contracts\Validation\Rule' not found

    Interface 'Illuminate\Contracts\Validation\Rule' not found

    • noCaptcha Version: ^5.0
    • Laravel Version: 5.4.35
    • PHP Version: 7.0.22

    Description:

    Error on validation Interface 'Illuminate\Contracts\Validation\Rule' not found - in CaptchaRule.php (line 12)

    Steps To Reproduce:

    Create a validatorRequest File in request directory and use the following rule : use Arcanedev\NoCaptcha\Rules\CaptchaRule;

    public function rules()
    {
        $rules = [
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
            'g-recaptcha-response' => ['required', new CaptchaRule],
        ];
    
        return $rules;
    }
    

    Processing :

    public function sendmail(ValidatorRequest $request)
    {
        $data = $request->all();
        dd($data);
    }
    
    duplicate need help laravel 
    opened by visualight 4
  • Your requirements could not be resolved to an installable set of packages.

    Your requirements could not be resolved to an installable set of packages.

    Problem 1 - Installation request for arcanedev/no-captcha ^10.1 -> satisfiable by arcanedev/no-captcha[10.1.0]. - Conclusion: remove laravel/framework v5.7.28 - Conclusion: don't install laravel/framework v5.7.28 - arcanedev/no-captcha 10.1.0 requires arcanedev/support ^5.0 -> satisfiable by arcanedev/support[5.0.0, 5.1.0, 5.1.1]. - arcanedev/support 5.1.0 requires illuminate/support ^6.0 -> satisfiable by laravel/framework[6.x-dev], illuminate/support[6.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0]. - arcanedev/support 5.1.1 requires illuminate/support ^6.0 -> satisfiable by laravel/framework[6.x-dev], illuminate/support[6.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0]. - arcanedev/support 5.0.0 requires illuminate/filesystem ~6.0.0 -> satisfiable by illuminate/filesystem[v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4]. - Can only install one of: laravel/framework[6.x-dev, v5.7.28]. - don't install illuminate/support 6.x-dev|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.0.0|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.0.1|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.0.2|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.0.3|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.0.4|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.1.0|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.2.0|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.3.0|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.4.1|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.5.0|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.5.1|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.5.2|don't install laravel/framework v5.7.28 - don't install illuminate/support v6.6.0|don't install laravel/framework v5.7.28 - don't install illuminate/filesystem v6.0.0|don't install laravel/framework v5.7.28 - don't install illuminate/filesystem v6.0.1|don't install laravel/framework v5.7.28 - don't install illuminate/filesystem v6.0.2|don't install laravel/framework v5.7.28 - don't install illuminate/filesystem v6.0.3|don't install laravel/framework v5.7.28 - don't install illuminate/filesystem v6.0.4|don't install laravel/framework v5.7.28 - Installation request for laravel/framework == 5.7.28.0 -> satisfiable by laravel/framework[v5.7.28].

    duplicate 
    opened by KumaChenGC 2
  • "Class 'Captcha' not found" AND "Call to undefined method Arcanedev\NoCaptcha\NoCaptchaV3::display()"

    • noCaptcha Version: 9.0
    • Laravel Version: 5.8
    • PHP Version: 7.3.1

    Description:

    If i use {!! Form::captcha() !!} in form i receive error Class 'Captcha' not found (View: ....) If i use {!! no_captcha()->display() !!} in form i receive error Call to undefined method Arcanedev\NoCaptcha\NoCaptchaV3::display()

    Also tried to switch from {!! Captcha::script() !!} to script()->toHtml(); ?> with same results.

    Steps To Reproduce:

    • composer install arcanedev/no-captcha
    • php artisan vendor:publish (published the Arcanedev\NoCaptcha\NoCaptchaServiceProvider )

    In Blade:

    {!! Form::open(array('class'=>'form contact-form', 'id'=>'contact-form')) !!}
    [...]
    {!! Form::captcha() !!} OR {!! no_captcha()->display() !!}
    [...]
    {!! Form::close() !!}
    
    
    @push('scripts')
    [...]
    {!! Captcha::script() !!} OR {!! no_captcha()->display() !!}
    [...]
    @endpush
    

    In Controller:

    use Arcanedev\NoCaptcha\Rules\CaptchaRule;
    [...]
            $this->validate($request, [
                [...]
                'g-recaptcha-response' => ['required', new CaptchaRule],
                ]);
    [...]
    {!! Form::close() !!}
    
    
    duplicate 
    opened by luigimarmo 2
  • reCAPTCHA v2 issue

    reCAPTCHA v2 issue

    • noCaptcha Version: 9.x
    • Laravel Version: 5.8.x
    • PHP Version: 7.3.x

    Description:

    The field validation keeps giving the error If you read this message, then you're a robot..

    I have the validation like in the docs: 'g-recaptcha-response' => ['required', new CaptchaRule],

    I add some ips to try and skip it, but it is not working too. I have them in the cfg like this:

    'skip-ips' => [
        'localhost',
        '127.0.0.1',
        '192.168.10.10'
    ],
    

    Any ideas of what might be the issue? Thanks.

    need help 
    opened by Morinohtar 2
  • Problem with using V2 driver

    Problem with using V2 driver

    • noCaptcha Version: 8.0.2
    • Laravel Version: 5.7.24
    • PHP Version: 7.1.22

    Description:

    Is it right to initialize V3 driver instead of V2 here?

    https://github.com/ARCANEDEV/noCAPTCHA/blob/cbef775f98be11199d5b953603b922db3fa3d116/src/NoCaptchaManager.php#L49-L56

    Steps To Reproduce:

    It's simple to reproduce, just use {!! no_captcha('v2')->display() !!} in blade template and you get an error that NoCapthcaV3 doesn't have display() method.

    bug laravel 
    opened by rwnet 2
  • RecaptchaV3. Error «incorrect-captcha-sol»

    RecaptchaV3. Error «incorrect-captcha-sol»

    • noCaptcha Version: 13.0.0
    • Laravel Version: 9.16.0
    • PHP Version: 8.1.5

    Description:

    When verifying the request, the error "incorrect-captcha-sol" is returned. I tried recreating recaptcha keys, different connection methods, clearing browser cookies, opening the site through a different browser.

    Steps To Reproduce:

    For example FeedbackController.php file:

    public function post(Request $request)
    {
        $captcha = new NoCaptchaV3(
            'RECAPTCHAV3_SECRET',
            'RECAPTCHAV3_SITEKEY'
        );
    
        if ($request->all() && $request['g-recaptcha-response']) {
            $response = $captcha->verify($request['g-recaptcha-response'] ?? null);
    
            if ($response->isSuccess()) {
                ...
            } else {
                dd($response);
            }
        }
    }
    

    feedback.blade.php:

    <form action="{{ route('feedback.post') }}" method="POST" name="formFeedback" class="contact-form contact__form">
        {{ csrf_field() }}
        <input type="hidden" value="{{$page}}" name="page" />
        <input class="contact-form__input" name="phone" type="text" placeholder="Телефон*">
        <input class="contact-form__input" name="name" type="text" placeholder="Имя">
        <textarea class="contact-form__input contact-form__area" name="msg" placeholder="Текст сообщения"></textarea>
        <span class="contact-form__policy">Нажимая "Отправить" вы соглашаетесь с политикой обработки персональных данных</span>
        <input class="contact-form__btn btn" type="submit" value="Отправить">
    
        {{ no_captcha()->input('g-recaptcha-response') }}
    </form>
    
    {{ no_captcha()->script() }}
    {{ no_captcha()->getApiScript() }}
    
    <script>
        grecaptcha.ready(() => {
            window.noCaptcha.render('formFeedback', (token) => {
                let recaptchaInputs = document.querySelectorAll('#g-recaptcha-response');
                recaptchaInputs.forEach(function (element) {
                    element.value = token;
                });
            });
        });
    </script>
    

    main.js:

    const recaptchaSitekey = 'RECAPTCHAV3_SITEKEY';
    
    $('.contact-form').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serializeArray().reduce(function(obj, item) {
            obj[item.name] = item.value;
            return obj;
        }, {});
    
        let url = $(this).attr('action');
        return axios
            .post(url, formData)
            .then(function(res) {
                if(res.data.status=='ok'){
                    notifier.success('Спасибо, ваше сообщение успешно отправлено!');
    
                    grecaptcha.reset(recaptchaSitekey);
                    grecaptcha.ready(() => {
                        window.noCaptcha.render('thatForm', (token) => {
                            var recaptchaInputs = document.querySelectorAll('#g-recaptcha-response');
                            recaptchaInputs.forEach(function (element) {
                                element.value = token;
                            });
                        });
                    });
                }
                else{
                    notifier.alert('Что-то пошло не так :( Попробуйте позже...')
                }
            })
            .catch(error => {
                notifier.alert('Что-то пошло не так :( Попробуйте позже...')
    
                console.error(error);
            });
    })
    
    opened by develop2-webalt 0
  • Laravel Dusk Testing not working

    Laravel Dusk Testing not working

    • noCaptcha Version: 13.0.0
    • Laravel Version: 9.9
    • PHP Version: 8.1

    Using Vue for the form submission.

    Also left the same comment in a topic that was already closed #39

    Cant seem to make the test work with Dusk, though the Feature Test works fine. Dont think the mock is working in Dusk...

    If i log the response from the rule, it spits this:

    `{"Arcanedev\\NoCaptcha\\Utilities\\ResponseV2":{"success":false,"hostname":null,"challenge_ts":null,"apk_package_name":null,"error-codes":["invalid-input-response"]}}`
    

    So, the rule response comes as false.

    Code:

    
        protected function ignoreCaptcha(string $name = 'g-recaptcha-response'): void
        {
            NoCaptchaFacade::shouldReceive('display')
                ->andReturn('<input type="textarea"  value="anything, really" name="' . $name . '">');
                
            NoCaptchaFacade::shouldReceive('script')
                ->andReturn('<script src="captcha.js"></script>');
                
            NoCaptchaFacade::shouldReceive('verify')
                ->andReturn(NoCaptchaFacade::getFacadeRoot());
                
            NoCaptchaFacade::shouldReceive('isSuccess')
                ->andReturn(true);
        }
    
        /** @test */
        public function it_submits_contact_form()
        {
            $this->ignoreCaptcha();
    
            $this->browse(function (Browser $browser) {
                $browser->visitRoute('contact')
                    ->type('name', $this->faker->name)
                    ->type('email', $this->faker->safeEmail)
                    ->type('message', $this->faker->paragraphs(3, true))
                    ->fillHidden('g-recaptcha-response', '1')
                    ->pressAndWaitFor('Submit', 3)
                    ->assertSee('Message sent!');
            });
        }
    
    opened by Morinohtar 0
Releases(13.0.0)
Owner
ARCANEDEV
ARCANEDEV
Integrate reCAPTCHA using async HTTP/2, making your app fast with a few lines.

ReCaptcha Integrate reCAPTCHA using async HTTP/2, making your app fast with a few lines. use Illuminate\Support\Facades\Route; Route::post('login', f

Laragear 14 Dec 6, 2022
Yab copy to new - A Textpattern plugin. Copies the current article content to a new one.

yab_copy_to_new Displays a new button in article write tab to copy the current article to a new one. Version: 0.2 Table of contents Plugin requirement

Tommy Schmucker 2 Dec 15, 2017
A simple helper to generate and display pagination navigation links

Intro to CHocoCode Paginator Friendly PHP paginator to paginate everything This package introduces a different way of pagination handling. You can rea

faso-dev 3 Aug 24, 2021
Helper to automatically load various Kirby extensions in a plugin

Autoloader for Kirby Helper to automatically load various Kirby extensions in a plugin Commerical Usage This package is free but if you use it in a co

Bruno Meilick 13 Nov 9, 2022
MODX Helper for Tailwind

TailwindHelper MODX Helper for Tailwind Features This MODX Extra adds a Tailwind helper to the MODX installation: Write a safelist.json on base on chu

Thomas Jakobi 3 Jan 10, 2022
🪃 Zero-dependency global `kirbylog()` helper for any content

Kirbylog The most simple, Kirby-esque way to log content to file. Most of the time, I just want to log some string or array to a file. That's what thi

Johann Schopplich 11 Nov 9, 2022
Helper for countries laravel package

Countries helper Helper for countries laravel package Installation You can install the package via composer: composer require eliseekn/countries-helpe

Kouadio Elisée N'GUESSAN 1 Oct 15, 2021
AlphaID Helper - Basic, Simple and Lightweight

AlphaID Helper - Basic, Simple and Lightweight

Hung Nguyen 1 Oct 18, 2021
Traits used primarily in the v6 package but also available as a helper package for applications

Phalcon Traits This package contains traits with methods that are used for Phalcon v6 onward. It can also be useful to others that want short snippets

The Phalcon PHP Framework 5 Oct 7, 2022
Plivo PHP Helper Library

plivo-php The Plivo PHP SDK makes it simpler to integrate communications into your PHP applications using the Plivo REST API. Using the SDK, you will

Plivo 107 May 9, 2022
Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network address

Darsyn 224 Dec 28, 2022
Laravel-hours-helper - Creates a Collection of times with a given interval.

Laravel Hours Helper With laravel-hours-helper you can create a collection of dates and/of times with a specific interval (in minutes) for a specific

Label84 220 Dec 29, 2022
Magento-bulk - Bulk Import/Export helper scripts and CLI utilities for Magento Commerce

Magento Bulk Bulk operations for Magento. Configuration Copy config.php.sample to config.php and edit it. Product Attribute Management List All Attrib

Bippo Indonesia 23 Dec 20, 2022
Magento 2 Debug Helper Module for easy debugging with Xdebug and PHPStorm or any other IDE

Magento 2 Debug Helper Information and Usage Magento 2 Debug Helper Module usage with PHPStorm and Xdebug Installation To install the Magento 2 Debug

Dmitry Shkoliar 13 May 24, 2022
Helper script to aid upgrading magento 2 websites by detecting overrides. Now supports third party module detections

ampersand-magento2-upgrade-patch-helper Helper scripts to aid upgrading magento 2 websites, or when upgrading a magento module This tool looks for fil

Ampersand 242 Dec 18, 2022
A PHP 7 value objects helper library.

valueobjects Requirements Requires PHP >= 7.1 Installation Through Composer, obviously: composer require funeralzone/valueobjects Extensions This lib

Funeral Zone 56 Dec 16, 2022
Helper plugin to install SilverStripe recipes

SilverStripe recipe-plugin Introduction This plugin enhances composer and allows for the installation of "silverstripe-recipe" packages. These recipes

Silverstripe CMS 10 Oct 4, 2022
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
Simple opinionated framework agnostic PHP 8.1 enum helper

Enum Helper A simple and opinionated collections of PHP 8.1 enum helpers inspired by archtechx/enums and BenSampo/laravel-enum. This package is framew

Datomatic 52 Jan 1, 2023