Code Monkey home page Code Monkey logo

laravelgeetest's Introduction

Laravel Geetest

Build Status DUB Support Release

Laravel Geetest is a package for Laravel 5 developed by Germey. It provides simple usage for laravel of Geetest.

Geetest Demo: Geetest

Installation

Laravel 5.0 or later is required.

This Package now supports Geetest 3.0.

For Geetest 2.0, please see LaravelGeetest 2.0

To get the latest version of Laravel Geetest, simply require the project using Composer:

$ composer require germey/geetest

Or you can add following to require key in composer.json:

"germey/geetest": "~3.0"

then run:

$ composer update

Next, You should need to register the service provider. Open up config/app.php and add following into the providers key:

Germey\Geetest\GeetestServiceProvider::class

And you can register the Geetest Facade in the aliases of config/app.php :

'Geetest' => Germey\Geetest\Geetest::class

Configuration

To get started, you need to publish vendor assets using the following command:

$ php artisan vendor:publish --tag=geetest

This will create a config file named config/geetest.php which you can configure geetest as you like.

It will also generate a views folder named resources/views/vendor/geetest, there will be a view file named geetest.blade.php. Here you can configure styles of geetest. For example, you can change the script alert() as you like.

Usage

Firstly, You need to register in Geetest. Creating an app and get ID and KEY.

For example. You can see app ID and KEY after you added an app in Geetest Admin Page

Then configure them in your .env file because you'd better not make them public.

Add them to .env as follows:

GEETEST_ID=0f1097bef7xxxxxx9afdeced970c63e4
GEETEST_KEY=c070f0628xxxxxxe68e138b55c56fb3b

Then, You can use render() in views like following, It will render a geetest code captcha:

{!! Geetest::render() !!}

For example, you can use it in form like this:

<form action="/" method="post">
    <input name="_token" type="hidden" value="{{ csrf_token() }}">
    <input type="text" name="name" placeholder="name">
    {!! Geetest::render() !!}
    <input type="submit" value="submit">
</form>

It will render like this:

When you click the submit button, it will verify the Geetest Code. If you didn't complete the validation, it will alert some text and prevent the form from submitting.

Or you can set other style of Geetest:

{!! Geetest::render('float') !!}
{!! Geetest::render('bind') !!}
{!! Geetest::render('popup') !!}
{!! Geetest::render('custom') !!}

Then it will be embed or popup style in the website. Default to float.

If the validation is completed, the form will be submitted successfully.

Server Validation

What's the reason that Geetest is safe? If it only has client validation of frontend, can we say it is complete? It also has server validation to ensure that the post request is validate.

First I have to say that you can only use Geetest of Frontend. But you can also do simple things to achieve server validation.

You can use $this->validate() method to achieve server validation. Here is an example:

use Illuminate\Http\Request;

class BaseController extends Controller 
{
    /**
     * @param Request $request
     */
    public function postValidate(Request $request)
    {
        $this->validate($request, [
            'geetest_challenge' => 'geetest',
        ], [
            'geetest' => config('geetest.server_fail_alert')
        ]);
        return true;
    }
} 

If we use Geetest, the form will post three extra parameters geetest_challenge geetest_validate geetest_seccode. Geetest use these three parameters to achieve server validation.

If you use ORM, we don't need to add these keys to Model, so you should add following in Model:

protected $guarded = ['geetest_challenge', 'geetest_validate', 'geetest_seccode'];

You can define alert text by altering server_fail_alert in config/geetest.php

Also you can use Request to achieve validation:

<?php namespace App\Http\Requests;
use App\Http\Requests\Request;

class ValidationRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'geetest_challenge' => 'geetest'
        ];
    }

    /**
     * Get validation messages.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'geetest' => 'Validation Failed'
        ];
    }
}

We can use it in our Controller by Request parameter:

use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;
use App\Http\Requests\ValidationRequest;

class BaseController extends Controller 
{
    /**
     * @param Request $request
     */
    public function postValidate(ValidationRequest $request)
    {
        // is Validate
    }
} 

Options

Change Ajax Url

If you want to change the Geetest Ajax Url, you can configure it in config/geetest.php, change url as you like, but at this time you need to add extra routes in your routes.php (Laravel 5.2 or former ) or routes/web.php (Laravel 5.3 or later). And you need to add a triat in your controller.

For example, If you add this route:

Route::get('auth/geetest','Auth\AuthController@getGeetest');

you need to add Germey\Geetest\GeetestCaptcha in your AuthController:

use Germey\Geetest\GeetestCaptcha;
class AuthController extends Controller {
    use GeetestCaptcha;
}

Then an Ajax url is configured successfully.

Also you can use this Trait in other Controller but you need to configure url in config/geetest.php.

Configure Url while rendering

Also, you can set Geetest Ajax Url by following way:

{!! Geetest::setGeetestUrl('/auth/geetest')->render() !!}

By setGeetestUrl method you can set Geetest Ajax Url. If it is configured, it will override url configured in config/geetest.php.

Configure Alert Message

You can configure alert message by configure client_fail_alert and server_fail_alert in config/geetest.php.

Configure Language

Geetest supports different language:

  • Simplified Chinese
  • Traditional Chinese
  • English
  • Japanese
  • Korean

You can configure it in config/geetest.php .

Here are key-values of Languge Configuration:

  • zh-cn (Simplified Chinese)
  • zh-tw (Traditional Chinese)
  • en (English)
  • ja (Japanese)
  • ko (Korean)

for example, If you want to use Korean, just change lang key to ko:

'lang' => 'ko'

Configure Protocol

You can configure protocol in config/geetest.php .

for example, If you want to use https, just change protocol key to https:

'protocol' => 'https'

Configure Default Product

You can configure default product in config/geetest.php .

for example, If you want to use popup product, just change product key to popup:

'product' => 'popup'

Mind that it only works when you use like this:

{!! Geetest::render() !!}

If you use like this:

{!! Geetest::render('bind') !!}

It will override the configuration in config/geetest.php.

Contribution

If you find something wrong with this package, you can send an email to [email protected]

Or just send a pull request to this repository.

Pull Requests are really welcomed.

Author

Germey , from Beijing China

License

Laravel Geetest is licensed under The MIT License (MIT).

laravelgeetest's People

Contributors

a-ceo avatar cheerego avatar germey avatar kangkang66 avatar vladyslavstartsev 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

laravelgeetest's Issues

服务端验证

根据教程的服务端验证部分,

  1. app/Http/Requests建立ValidationRequest.php

    <?php namespace App\Http\Requests;
    use App\Http\Requests\Request;
    
    class ValidationRequest extends Request
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'geetest_challenge' => 'geetest'
            ];
        }
    
        /**
         * Get validation messages.
         *
         * @return array
         */
        public function messages()
        {
            return [
                'geetest' => 'Validation Failed'
            ];
        }
    }
  2. app/Http/Controllers/Auth/AuthController.php 添加:postValidate

    class AuthController extends Controller
    {
        use AuthenticatesAndRegistersUsers, ThrottlesLogins;
        use CaptchaGeetest;
    
    ....
    
    public function postValidate(ValidationRequest $request)
        {
            // is Validate
            $result = $this->validate($request, [
                'geetest_challenge' => 'geetest',
            ], [
                'geetest' => Config::get('geetest.server_fail_alert')
            ]);
            if ($result) {
                return 'success';
            }
        }
    
    ....
    
    }

请问,步骤2对吗?
或者有服务器验证这部分的Demo?
我只需要实现登陆页面进行验证码校验就可以了。

不支持Vue

不支持Vue,然后验证不行,不知道是不是我配置问题,按照教程都配置了,然后我不插入验证代码,直接validation验证直接被跳过。。。。。。

疑似不兼容 PHP5.6

在 PHP5.6 的平台上运行会出现下列错误

FatalErrorException in GeetestController.php line 13: 
syntax error, unexpected '::'  (T_PAAMAYIM_NEKUDOTAYIM)

在 PHP7.0 的平台上正常使用,且单独在 PHP5.6 平台执行 app()::VERSION 也报错

Psy Shell v0.7.2 (PHP 5.6.33-0+deb8u1 — cli) by Justin Hileman
>>> app()::VERSION
PHP Parse error: Syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM on line 1

同样在 PHP7 平台正常

Support laravel 6

Hi! There is no laravel 6 support at the moment, can you please add it?

请支持极验的3.0验证码

极验现在出了新版本的验证码,点击一下按钮就识别完了,用户体验很好
希望可以集成一下,感谢。

BTW,极验那边好像是说免费用户不支持HTTPS?不知可否解决?

Laravel 5.4无法使用

Trait 'Germey\Geetest\CaptchaGeetest' not found

安装了包,config.pgp也加了providers和aliases,路由也配置好了,页面报错:

GET /auth/geetest?t=1488270023191 500 (Internal Server Error)

session不保存

我直接调用render时一直过不了验证码。debug了好久,发现session没有保存成功。
我不知道是否
有必要
增加个 session的forceSave的配置项,默认是false。
我在自己的项目里面,session是手动save一下子,不然过不了验证码呀。
到现在没明白为什么不能在laravel生命周期末的时候,自动保存geetest的session

出现两个登陆按钮

我在form中添加{!! Geetest::render('popup') !!}
代码如下:

<form class="m-t" role="form" method="POST" action="{{ url('/login') }}">
    {{ csrf_field() }}
    <input name="_token" type="hidden" value="{{ csrf_token() }}">
    <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
        <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="账号" >
        @if ($errors->has('email'))
            <span class="help-block">
                    <strong>{{ $errors->first('email') }}</strong>
                </span>
        @endif
    </div>
    <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
        <input id="password" type="password" class="form-control" name="password" placeholder="密码">
        @if ($errors->has('password'))
            <span class="help-block">
                    <strong>{{ $errors->first('password') }}</strong>
                </span>
        @endif
    </div>
    <div class="form-group">
        <div class="checkbox">
            <label>
                <input type="checkbox" name="remember"> 记住我
            </label>
        </div>
    </div>
    <button type="submit" class="btn btn-primary block full-width m-b">登陆</button>
    {!! Geetest::render('popup') !!}
</form>
  • 加载中...

qq20160829-4 2x

- 加载完成

qq20160829-5 2x

### 问题 - 如何不出现这个`正在加载验证码...`? - 怎么出现两个登陆按钮?

Configuration is not working

Hello,

php artisan vendor:publish --tag=geetest, this command is not doing what supposed to do and the class is not recognize at views.

Regards!

在 Service 端中的校验失败的问题

我在我的 Project 中使用了您的包,但是我在进行服务端校验时遇到了一点小问题,我使用了 Ajax 请求来提交我的 Form 表单,但是一直得到验证失败的返回。我查看了一下源码,觉得可能与 Session 相关,于是我在我的控制器里启用了 Session (起先是在 Api 路由中进行的校验),但是得到的结果还是校验失败,查看了一下官方的SDK代码,在离线校验时是使用的MD5值对比,我不知道出了什么问题,你可以给我一点建议吗?

Client Code

            $.ajax({
                cache: false,
                type: "POST",
                url: '{{ route('auth.send_verify_code') }}',
                data: $('#auth-register').serialize(),
                async: false,
                error: function (respond) {
                    return failedMessage('获取验证码失败,请刷新重试!')
                },

                success: function (respond) {
                    if (!respond.status) {
                        return failedMessage(respond.msg)
                    }
                }

            })

Service Code

    public function checkMobileIsAllow($mobile = null)
    {
        $validator = Validator::make(
            ['mobile' => $mobile],
            ['mobile' => 'required|digits:11|unique:member|geetest'],
            ['geetest' => config('geetest.server_fail_alert')]
        );

        if ($validator->fails()) {
            throw new ValidatorException($validator->errors()->first());
        }

        return true;
    }

修复后的代码,麻烦新增个 tag

你好, 我是昨天在 github 提交代码的. 可以麻烦您增加个 tag 吗? 我好拉取最新的包. 因为我这边 laravel 中正在使用这个扩展. 谢谢麻烦了

Tasks for 4.0

As it may need to break things in 4.0 (which I will try not to do) some things should be added to this package

  • phpstan (max level)
  • psalm (level 1)
  • 100% coverage
  • support for latest versions only (php and composer require)
  • declare(strict_types=1)
  • do not use helpers and facades (but provide them, since some people will like to use it). Try to use interfaces

the list may be expanded...

Usage in the doc not working

I supposed that the usage in the readme was wrong.

  /**
   * @param Request $request
   */
  public function postValidate(Request $request)
  {
    $result = $this->validate($request, [
      'geetest_challenge' => 'geetest',
    ], [
      'geetest' => config('geetest.server_fail_alert')
    ]);
    if ($result) {
      return 'success';
    }
  }

A prompt will be shown by phpstorm that function validate is a void function. And this code did fail to work, it returns false even if I properly dealed with the captcha.

In fact, in laravel doc,

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

Indeed I cannot found a usage like that.

I suppose, by any chance, a proper use should be like this,

    /**
     * @param Request $request
     * @return bool
     */
    private function geetestValidate(Request $request)
    {
        $this->validate($request, [
            'geetest_challenge' => 'geetest',
        ], [
            'geetest' => config('geetest.server_fail_alert')
        ]);
        return true;
    }

And this did work for me.

Regards.

ajax服务端异常

看到3.0的更新,升级完毕之后,发现验证码无法加载,F12看到JS报错如下:

Uncaught Error: 初始化gt传参错误
    at new c (static.geetest.com/static/js/geetest.0.0.0.js:1)
    at new d (static.geetest.com/static/js/geetest.0.0.0.js:1)
    at init (gt.js:255)
    at gt.js:275
    at gt.js:167
    at gt.js:109

ajax返回的数据为"success":0,"gt":null,因为gt为null所以传参错误。
检查了API信息正确,同一机器使用2.0旧版正常。

功能正常但一直显示"正在加载验证码..."

如图:

image

功能没有问题,只是多了一个显示,感觉有些不舒服,我使用的laravel5.6,同一个项目,只是前后台是不同表实现的认证,所以有两个登陆界面,后台是我自己找的基于booterstrap的后台模板,那个界面没有问题,因为bootstrap里已经有一个.hide,而且样式是display:none !important,但laravel自带的认证登陆页面上没有。查看了下样式,.hide类是加上去了,但是display:none没有生效,也就是你在geetest.blade.php模板里设置的样式没有起作用。

后来做了下修改,如下:

captchaObj.onReady(function() {
      $("#wait-{{ $captchaid }}")[0].className = "hide";
 });

//change to 

captchaObj.onReady(function() {
       $("#wait-{{ $captchaid }}").hide();
});

在laravel 5.1中不能用。

运行php artisan route:list 报 Call to undefined method Germey\Geetest\GeetestController::getMiddleware()

需要将germey/geetest/src/GeetestController.php 改为

<?php

namespace Germey\Geetest;


use Illuminate\Routing\Controller;

class GeetestController extends Controller
{
	use GeetestCaptcha;
}

同时,解决 http://homestead.app/auth/geetest?t=1473062275344 500 (Internal Server Error)

不完善的插件!你们北京人屁眼长头上

**人还整个自动翻译成英文不说,各种不全,你们北京人是不是都屁眼长头上!

英文不好就别整,什么破英文的文档?各种不全,按你的步骤能显示验证码?SB!

Maybe change a CI server

I used travis CI for this package before, but I no longer use it for a long time, I don't know what you are using, you can also feel free to change che CI server such as GitHub Actions, Jekins? @vladyslavstartsev

在laravel5.3上使用报错

PHP Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Undefined class constant 'class,' in /var/www/laravel/config/app.php:183
Stack trace:
#0 /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(60): require()
#1 /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php(38): Illuminate\Foundation\Bootstrap\LoadConfiguration->loadConfigurationFiles(Object(Illuminate\Foundation\Application), Object(Illuminate\Config\Repository))
#2 /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(203): Illuminate\Foundation\Bootstrap\LoadConfiguration->bootstrap(Object(Illuminate\Foundation\Application))
#3 /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(251): Illuminate\Foundation\Application->bootstrapWith(Array)
#4 /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(109): Illuminate\Foundation\Console\Kernel->bootstra in /var/www/laravel/config/app.php on line 183

在前端校验成功,Service 端校验失败

Laravel5.5框架中,前端校验成功,service校验失败,追了一下源代码,在这一段位置,session读取不到,望尽快修复:

Validator::extend('geetest', function () use ($request) {
			list($geetest_challenge, $geetest_validate, $geetest_seccode) = array_values($request->only('geetest_challenge', 'geetest_validate', 'geetest_seccode'));
			$data = [
				'user_id' => @Auth::user()?@Auth::user()->id:'UnLoginUser',
				'client_type' => 'web',
				'ip_address' => $request->ip()
			];

			if (session()->get('gtserver') == 1) {
				if (Geetest::successValidate($geetest_challenge, $geetest_validate, $geetest_seccode, $data)) {
					return true;
				}
				return false;
			} else {
				if (Geetest::failValidate($geetest_challenge, $geetest_validate, $geetest_seccode)) {
					return true;
				}
				return false;
			}
		});

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.