Table of Contents
Articles you may be interested in:
Home Backend Development PHP Tutorial Laravel integrates Geetest verification code method php example

Laravel integrates Geetest verification code method php example

Jun 23, 2018 pm 04:48 PM
laravel Verification code

This article mainly introduces the method of integrating Geetest verification code with Laravel. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Geetest integration process

  1. The general logic of realizing login

  2. Register a JiExperience account

  3. Register a behavioral verification in the background management of “JiExperience”

  4. Configure our controller and routing according to the official Demo

  5. Configure our login template according to the official Demo

  6. Test

Geetest integration detailed process

1. Implement the general logic of login

Create the controller php artisan make:controller GeetestController

Edit Controller/app/Http/Controllers/GeetestController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/**
* 这是一个集成 Geetest 验证码的 Demo 类
*/
class GeetestController extends Controller
{ 
 /**
 * 导入登录视图
 */
 public function login() {
  return view(&#39;Geetest/login&#39;);
 }
 **
 * 验证用户信息
 */
 public function check() {
  return &#39;用户已经在前端通过了验证码验证, 你可以在这里完善后续的逻辑&#39;;
 }
}
Copy after login

The view is a simple form, omitted .

2. Omit => "Register"

3. Omit => "Backend login" => "Behavior verification" => Apply for an id & key

4. Configure the controller and routing

First of all, the core class library provided by the Demo is a class file called class.geetestlib.php, and the class name is GeetestLib. We create a controller with the same class name to replace it php artisan make:controller GeetestLib

Don’t copy the class, just copy the content in the class

GeetestController control Device implementation logic

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\GeetestLib; // 我们创建然后拷贝得来的 GeetestLib 核心库

/**
* 这是一个集成 Geetest 验证码的 Demo 类
*/
class GeetestController extends Controller
{ 
 // 这里配置 id & key
 private $captchaId = "5d467a3cb22a9310837d51720c5251f0";
 private $privateKey = "40764e6b94344f780d4b6b07148c9495";

 /**
 * 导入登录视图
 */
 public function login() {
  return view(&#39;Geetest/login&#39;);
 }

 /**
 * 验证用户信息
 */
 public function check() {
  return &#39;用户已经在前端通过了验证码验证, 你可以在这里完善后续的逻辑&#39;;
 }

 /**
 * 实现验证功能: 直接复制官方demo提供得
 */
 public function startCaptchaServlet() {
  // 这里使用配置的 id & key
  $GtSdk = new GeetestLib($this->captchaId, $this->privateKey);
  session_start();
  
  $data = array(
   "user_id" => "test", # 网站用户id
   "client_type" => "web", #web:电脑上的浏览器;h5:手机上的浏览器,包括移动应用内完全内置的web_view;native:通过原生SDK植入APP应用的方式
   "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
  );
  
  $status = $GtSdk->pre_process($data, 1);
  $_SESSION[&#39;gtserver&#39;] = $status;
  $_SESSION[&#39;user_id&#39;] = $data[&#39;user_id&#39;];
  echo $GtSdk->get_response_str();
 }
}
Copy after login

Configuration routing/routes/web.php

// 集成 Geetest 验证码
Route::get(&#39;GeetestLogin&#39;, &#39;GeetestController@login&#39;); //登录页面
Route::get(&#39;GeetestCheck&#39;, &#39;GeetestController@check&#39;); //登录验证 (我们没写具体逻辑)
Route::get(&#39;GeetestStartCaptchaServlet&#39;, &#39;GeetestController@startCaptchaServlet&#39;); // 调用方法启用验证码
Copy after login

5. Improve the login template/resources/views/Geetest/login.blade.php

Need to import jquery (we use npm run dev compiled app.js to integrate jquery)

Need to import Demo to give gt.js, we put it under public/js<script src="/js/gt.js"></script>

In fact, in theory, it can also be placed under /resouces/assets/js/, and require in /resouces/assets/js/app.js to let it participate in being compiled, and package it directly in public/js The integration takes effect.

On the template, two style classes need to be defined.show & .hide => The styles used for gt.js control prompt information can also be written under /resouces/assets/sass/

Submit an id to the "Login" button in the form

Copy the front-end logic js provided in the Demo, pay attention to binding this button

Pay attention to the .ajax configuration The url must be the path we defined in web.php with 'GeetestStartCaptchaServlet'

Specific code

<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <!-- 这是我们用 npm run dev 编译后的 css / js -->
 <link rel="stylesheet" href="/css/app.css" rel="external nofollow" >
 <script src="/js/app.js"></script>

 <!-- 这里需要用到两个样式 -->
 <style>
  .show {
   display: block;
  }
  .hide {
   display: none;
  }
 </style>

 <title> Geetest 集成 Demo</title>
</head>
<body>
 <p class="container">
  <p class="row">
   <p class="col-lg-12">
    <h1 class="text-center">Geetest 集成 Demo
     <small>
      <a href="http://www.geetest.com/" rel="external nofollow" rel="external nofollow" > Geetest 官方网站 </a>
     </small> 
    </h1>
   </p>
   <p class="col-lg-12">
    <form method="GET" action="/GeetestCheck">
     <p class="form-group">
      <label for="exampleInputEmail1">模拟邮箱地址</label>
      <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="请输入邮箱...">
      <small id="emailHelp" class="form-text text-muted">我们不会公开您的邮箱</small>
     </p>
     <p class="form-group">
      <label for="exampleInputPassword1">模拟密码</label>
      <input type="password" class="form-control" id="exampleInputPassword1" placeholder="请输入密码...">
     </p>
     <p class="form-group">
      <p id="embed-captcha"></p>
      <p id="wait" class="show">正在加载验证码......</p>
      <p id="notice" class="hide">请先完成验证</p>
     </p>
     <!-- 这里需要绑定一个按钮 -->
     <button type="submit" class="btn btn-primary" id="embed-submit">登录</button>
    </form>
   </p>
  </p>
 </p>

 <!-- 引用 gt.js -->
 <script src="/js/gt.js"></script>
 <!-- 直接复制官方Demo里的js代码 -->
 <script>
  var handlerEmbed = function (captchaObj) {
   $("#embed-submit").click(function (e) {
    var validate = captchaObj.getValidate();
    if (!validate) {
     $("#notice")[0].className = "show";
     setTimeout(function () {
      $("#notice")[0].className = "hide";
     }, 2000);
     e.preventDefault();
    }
   });
   // 将验证码加到id为captcha的元素里,同时会有三个input的值:geetest_challenge, geetest_validate, geetest_seccode
   captchaObj.appendTo("#embed-captcha");
   captchaObj.onReady(function () {
    $("#wait")[0].className = "hide";
   });
   // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
  };
  $.ajax({
   // 获取id,challenge,success(是否启用failback)
   url: "/GeetestStartCaptchaServlet", // 加随机数防止缓存
   type: "get",
   dataType: "json",
   success: function (data) {
    console.log(data);
    // 使用initGeetest接口
    // 参数1:配置参数
    // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
    initGeetest({
     gt: data.gt,
     challenge: data.challenge,
     new_captcha: data.new_captcha,
     product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
     offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
     // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
    }, handlerEmbed);
   }
  });
 </script>
</body>
</html>
Copy after login

Test Success

Things that can be optimized

It is best not to use a "controller" as the core class library. GeetestLib should be integrated into another place

The js & css on the view template should be written in resources/assets to participate in the compilation of generating app.css & app.js

We have not written the specific login logic. You should also be able to confirm whether the Geetest verification is successful in the login verification check() method. You can refer to Demo

. The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will learn more. Support PHP Chinese website.

Articles you may be interested in:

Phpstorm Xdebug breakpoint debugging method for PHP php instance

php strftime function gets the date and time php basics

Sample code for PHP multi-dimensional array to specify multi-field sorting_php example

The above is the detailed content of Laravel integrates Geetest verification code method php example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

See all articles