Skip to content

Commit

Permalink
added background script support
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanDaDeng committed Jan 26, 2019
1 parent efb9e9d commit 9dce2d5
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 60 deletions.
89 changes: 35 additions & 54 deletions README.md
Expand Up @@ -74,6 +74,7 @@ Please check Google site: https://developers.google.com/recaptcha/docs/faq
- Support custom implementation on request method interface
- Fully supported Vue component
- IP skip list supported
- Support script to be placed in the background of pages for analytics

## Requirement

Expand All @@ -92,7 +93,7 @@ This package requires the following dependencies:
Via Composer

``` sh
$ composer require timehunter/laravel-google-recaptcha-v3 "~2.2.0" -vvv
$ composer require timehunter/laravel-google-recaptcha-v3 "~2.2.5" -vvv
```

If your Laravel framework version <= 5.4, please register the service provider under your config file: /config/app.php, otherwise please skip it.
Expand Down Expand Up @@ -129,7 +130,7 @@ After installation, you should see a googlerecaptchav3.php in your app/config fo
## Configurations <a name="settings" />
### Setting up your Google reCAPTCHA details in config file

Please register all details in config for site_key and secret_key.
Please register all details in config for host_name, site_key, secret_key and site_verify_url.

Specify your Score threshold and action in 'setting', e.g.
``` php
Expand All @@ -138,12 +139,21 @@ Specify your Score threshold and action in 'setting', e.g.
'action' => 'contact_us', // Google reCAPTCHA required paramater
'threshold' => 0.2, // score threshold
'is_enabled' => false // if this is true, the system will do score comparsion against your threshold for the action
]
],
[
'action' => 'signup',
'threshold' => 0.2,
'score_comparision' => true
],
]
```
Note: if you want to enable Score Comparision, you also need to enable is_score_enabled to be true.
``` php
'is_score_enabled' = true
'setting' = [
...
'is_score_enabled' = true
...
]
```

For score comparision, all actions should be registered in googlerecaptchav3 config file under 'setting' section.
Expand Down Expand Up @@ -216,66 +226,40 @@ If you manually assign a value to setScore($score), the code will fully skip you


## Blade Usage <a name="blade-basic-usage" />

### Display reCAPTCHA v3

#### Blade
Include div with an ID inside your form, e.g.
#### Blade for Background (optional)

``` html
<div id="contact_us_id"></div>
```
It's recommended to include reCAPTCHA v3 on every page which can help you get the most context about interactions for analytics.

Include Template script in your bottom/header of your page, params should follow 'ID'=>'Action', e.g.
In your main homepage or layout page, put the following script at the bottom of your page:

``` PHP
{!! GoogleReCaptchaV3::render(
[
'contact_us_id'=>'contact_us', // the div id=contact_us_id maps to action name contact_us
'signin_id'=>'registration', // the div id=signin_id maps to action name registration
'register_id'=>'registration' // the div id=register_id maps to action name registration
]) !!}
``` html
{!! GoogleReCaptchaV3::background() !!}
```

#### Example Usage

Register your action in config, also enable score and set up your own site key and secret key:
Note: the above script MUST be called after GoogleReCaptchaV3::render(), otherwise the google script might run multiple times.

You can also set the background reCAPTCHA as hidden or visible(bottomright):

``` php
'setting' => [
[
'action' => 'contact_us',
'threshold' => 2,
'score_comparision' => true
],
[
'action' => 'signup',
'threshold' => 0.2,
'score_comparision' => true
],
]
...
'background_badge_display' => true,
...
```

#### Blade for Form & Action

Register two routes in web.php
``` php
Route::get('/index', 'ReCaptchaController@index');
Route::post('/verify', 'ReCaptchaController@verify');
```
Include div with an ID inside your form, e.g.

Create two functions in controller:
``` php
public function verify(Request $request)
{
dd(GoogleReCaptchaV3::verifyResponse($request->input('g-recaptcha-response'))->getMessage());
}
public function index(Request $request)
{
return view('index');
}
``` html
<div id="contact_us_id"></div>
```

Create your form in index.blade.php:
``` html
Include GoogleReCaptchaV3::render() script after your form, params should follow 'ID'=>'Action', e.g.

``` html
{{--if laravel version <=5.6, please use {{ csrf_field() }}--}}

<form method="POST" action="/verify">
Expand All @@ -294,11 +278,8 @@ Create your form in index.blade.php:
{!! GoogleReCaptchaV3::render(['contact_us_id'=>'contact_us', 'signup_id'=>'signup']) !!}
```

The backend request will receive a value for 'g-recaptcha-response'.

Go to /index and click submit button on contact us form and you should see an error message that 'Score does not meet the treshhold' because the threshold >2. You can play around the controller to see all outcomes. Importantly, you need to wait the script to be loaded before clicking the submit button.

## Badge Display <a name="badge-display" />
### Badge Display for Form & Action

If your settings were not reflected, please run php artisan config:cache to clear cache.

Expand Down Expand Up @@ -338,7 +319,7 @@ Custom
2. Do Styling/CSS on its div element


## Vue Usage (Pacakge version >= 2.2.0) <a name="vue-usage" />
## Vue Usage (Package version >= 2.2.0) <a name="vue-usage" />

The package provides a lightweight vue component. You need to publish the vue component before playing around it.

Expand Down
12 changes: 12 additions & 0 deletions config/googlerecaptchav3.php
Expand Up @@ -66,6 +66,18 @@
*/
'inline' => false,

/*
|--------------------------------------------------------------------------
| Background Badge Style
|--------------------------------------------------------------------------
| Type: boolean
| Support:
| - true: the background badge will be displayed at the bottom right of page
| - false: the background badge will be invisible
|
*/
'background_badge_display' => true,

/*
|--------------------------------------------------------------------------
| Score Comparision
Expand Down
18 changes: 18 additions & 0 deletions resources/views/googlerecaptchav3/background.blade.php
@@ -0,0 +1,18 @@
@if(\TimeHunter\LaravelGoogleReCaptchaV3\GoogleReCaptchaV3::$hasAction === false)
@if($display === false)
<style>
.grecaptcha-badge {
display: none;
}
</style>
@endif
<script>
if (!document.getElementById('gReCaptchaScript')) {
let reCaptchaScript = document.createElement('script');
reCaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js?render={{$publicKey}}');
reCaptchaScript.async = true;
reCaptchaScript.defer = true;
document.head.appendChild(reCaptchaScript);
}
</script>
@endif
7 changes: 5 additions & 2 deletions resources/views/googlerecaptchav3/template.blade.php
@@ -1,12 +1,14 @@
{{\TimeHunter\LaravelGoogleReCaptchaV3\GoogleReCaptchaV3::setHasAction(true)}}
<script>
function onloadCallback() {
@foreach($mappers as $action=>$fields)
@foreach($fields as $field)
let client{{$field}} = grecaptcha.render('{{$field}}', {
'sitekey': '{{$publicKey}}',
@if($inline===true) 'badge': 'inline', @endif
'size': 'invisible',
'hl' : '{{$language}}'
'hl': '{{$language}}'
});
grecaptcha.ready(function () {
grecaptcha.execute(client{{$field}}, {
Expand All @@ -17,4 +19,5 @@ function onloadCallback() {
@endforeach
}
</script>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback" defer async></script>
<script id='gReCaptchaScript' src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback" defer
async></script>
8 changes: 8 additions & 0 deletions src/Configurations/ReCaptchaConfigV3.php
Expand Up @@ -101,4 +101,12 @@ public function getSkipIps()
{
return config('googlerecaptchav3.skip_ips');
}

/**
* @return \Illuminate\Config\Repository|mixed
*/
public function getBackgroundBadgeDisplay()
{
return config('googlerecaptchav3.background_badge_display');
}
}
1 change: 1 addition & 0 deletions src/Facades/GoogleReCaptchaV3.php
Expand Up @@ -10,6 +10,7 @@
* @method static \TimeHunter\LaravelGoogleReCaptchaV3\GoogleReCaptchaV3 setAction($value)
* @method static \TimeHunter\LaravelGoogleReCaptchaV3\GoogleReCaptchaV3 setScore($value)
* @method static render($mappers)
* @method static background()
* @see \TimeHunter\LaravelGoogleReCaptchaV3\GoogleReCaptchaV3
*/
class GoogleReCaptchaV3 extends Facade
Expand Down
56 changes: 52 additions & 4 deletions src/GoogleReCaptchaV3.php
Expand Up @@ -16,12 +16,25 @@ class GoogleReCaptchaV3
{
private $service;
private $defaultTemplate = 'GoogleReCaptchaV3::googlerecaptchav3.template';
private $defaultBackgroundTemplate = 'GoogleReCaptchaV3::googlerecaptchav3.background';

public static $hasAction = false;

public function __construct(GoogleReCaptchaV3Service $service)
{
$this->service = $service;
}

/**
* @param $value
* @return bool
*/
public static function setHasAction($value)
{
self::$hasAction = $value;
return self::$hasAction;
}

/**
* @param $mappers
* @return array
Expand All @@ -43,18 +56,53 @@ public function prepareViewData($mappers)
return $data;
}

/**
* @return array
*/
public function prepareBackgroundData()
{
return [
'publicKey' => $this->getConfig()->getSiteKey(),
'display' => $this->getConfig()->getBackgroundBadgeDisplay()
];
}

/**
* @return \Illuminate\Contracts\View\View|mixed
*/
public function background()
{
return app('view')
->make(
$this->getBackgroundView(),
$this->prepareBackgroundData()
);
}

/**
* @param $mappers
* @return \Illuminate\Contracts\View\View|null
*/
public function render($mappers)
public function render($mappers = [])
{
if (! $this->getConfig()->isServiceEnabled()) {
if (!$this->getConfig()->isServiceEnabled()) {
return;
}
$data = $this->prepareViewData($mappers);

return app('view')->make($this->getView(), $data);
return app('view')
->make(
$this->getView(),
$this->prepareViewData($mappers)
);
}


/**
* @return mixed|string
*/
protected function getBackgroundView()
{
return $this->defaultBackgroundTemplate;
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/Interfaces/ReCaptchaConfigV3Interface.php
Expand Up @@ -69,4 +69,9 @@ public function getLanguage();
* @return array
*/
public function getSkipIps();

/**
* @return bool
*/
public function getBackgroundBadgeDisplay();
}

0 comments on commit 9dce2d5

Please sign in to comment.