定制 anam/captcha 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

anam/captcha

Composer 安装命令:

composer require anam/captcha

包简介

reCAPTCHA and invisible reCAPTCHA for Laravel. reCAPTCHA protects your app against spam and bot.

README 文档

README

reCAPTCHA protects your app against spam and bot. This package is tested with Laravel 5.5.

recaptcha

Requirements

  • PHP 7.0+

Installation

Captcha is available via Composer:

$ composer require anam/captcha

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

"require": {
    "anam/captcha": "~1.0"
}

Integrations

Laravel 5.5+ integrations

Package Discovery

Anam\Captcha utilize the Laravel's package auto discovery feature. So, you don't need to add manually Service provider and Facade in Laravel application's config/app.php. Laravel will automatically register the service provider and facades for you.

Laravel < 5.5 integrations

Captcha comes with a Service provider and Facade for easy integration.

After you have installed the anam/captcha, open the config/app.php file which is included with Laravel and add the following lines.

In the $providers array add the following service provider.

'Anam\Captcha\ServiceProvider\CaptchaServiceProvider'

Add the facade of this package to the $aliases array.

'Captcha' => 'Anam\Captcha\Facade\Captcha'

You can now use this facade in place of instantiating the converter yourself in the following examples.

Configuration

First, register keys for your site at https://www.google.com/recaptcha/admin

Add RECAPTCHA_SITE_KEY and RECAPTCHA_SECRET in .env file :

RECAPTCHA_SITE_KEY=site_key
RECAPTCHA_SECRET=secret

Run vendor publish to add the captcha.php file to config:

php artisan vendor:publish --tag=CaptchaConfig

By default, The package will try to load keys from environment. However, you can set them manually:

$captcha = new \Anam\Captcha\Captcha('recaptcha_secret');

Blade directives:

// reCAPTCHA v2
@captcha(site_key)

// Invisible reCAPTCHA
@invisiblecaptcha(site_key)

Usage

Client side

reCAPTCHA V2:

Just add @captcha() blade directive to the form.

<form method="POST" action="/captcha" id="captcha-form">
  {{ csrf_field() }}
  <label>Name</label>
  <input type="text" name="name">
  <label>Your message</label>
  <textarea name="message" rows="5"></textarea>
  <br>
  @captcha()
  <br>
  <input type="submit" value="Submit">
</form>

For more advanced integration, Please visit the following link: https://developers.google.com/recaptcha/docs/display

Invisible reCAPTCHA:

Add @invisiblecaptcha() directive to the form where you want to appear the submit button. Please note, The @invisiblecaptcha directive will inject the submit button for you. If you want to style the submit button, .g-recaptcha class available for you.

<form method="POST" action="/captcha" id="captcha-form">
  {{ csrf_field() }}
  <label>Name</label>
  <input type="text" name="name">
  <label>Your message</label>
  <textarea name="message" rows="5"></textarea>
  <br>
  @invisiblecaptcha()
</form>

Caveat: If view has more than one forms, the @invisiblecaptcha() might not work as it will submit the first form. In these cases, you have to integrate the reCAPTCHA manually.

Please visit the following link: https://developers.google.com/recaptcha/docs/invisible

Server side

Handling the request:

use Anam\Captcha\Captcha;
use Illuminate\Http\Request;

class CaptchaController extends Controller
{
/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Anam\Captcha\Captcha  $captcha
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Captcha $captcha)
    {
        $response = $captcha->check($request);

        if (! $response->isVerified()) {
            dd($response->errors());
        }
        
        dd($response->hostname());
    }
}

Example

Laravel User Registration Controller

app\Http\Controllers\Auth\RegisterController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use App\Rules\GoogleRecaptcha;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $messages = [
            'g-recaptcha-response.required' => 'You must verify that you are not a robot.',
        ];
		
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'g-recaptcha-response' => ['required', new GoogleRecaptcha]
        ], $messages);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

app\Rules\GoogleRecaptcha.php

<?php

namespace App\Rules;

use Anam\Captcha\Captcha;
use Illuminate\Contracts\Validation\Rule;

class GoogleRecaptcha implements Rule
{

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $captcha = new Captcha();
        $response = $captcha->check(request());
        return $response->isVerified();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Are you a robot?';
    }
}

Credits

License

The MIT License (MIT). Please see LICENSE for more information.

anam/captcha 适用场景与选型建议

anam/captcha 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 44.53k 次下载、GitHub Stars 达 28, 最近一次更新时间为 2017 年 10 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「recaptcha」 「captcha」 「Laravel Captcha」 「reCAPTCHA V2」 「Invisible reCAPTCHA」 「Invisible captcha」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 anam/captcha 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 anam/captcha 我们能提供哪些服务?
定制开发 / 二次开发

基于 anam/captcha 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 44.53k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 29
  • 点击次数: 34
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 28
  • Watchers: 2
  • Forks: 6
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-10-22