search
HomeBackend DevelopmentPHP TutorialLaravel integrates Geetest verification code method php example

Laravel integrates Geetest verification code method php example

Jun 23, 2018 pm 04:48 PM
laravelVerification 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;;
 }
}

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();
 }
}

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;); // 调用方法启用验证码

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>

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
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function