Home Backend Development PHP Tutorial How to implement SMS registration in Larav

How to implement SMS registration in Larav

Jun 13, 2018 pm 04:31 PM
laravel

This article mainly introduces the sample code for SMS registration using Laravel, using the Yunpian SMS platform. The content is quite good. I will share it with you now and give it as a reference.

I am working on a mall project in my company. Since there is only one backend, it is my turn to register via SMS. At the beginning, I was still a little weak in my heart. Fortunately, there is a book written by the summer master of the Laravel-china community. I referred to its writing method and ideas in it, and used the easy-sms package. It only took half an afternoon to make it successfully. I will share it with everyone in the evening.

1. Determine the SMS operator

#I saw that the big guys all used Yunpian, so I did not hesitate to use it. It is recommended that companies use this text messaging platform, but others are also available.

First register an account yourself, and then find this

Click to start accessing and complete the novice guidance process.

The second signature and template must be filled in, similar to what I filled in below

It is worth noting that this template must be exactly the same as the text message content you set when using the easy-sms package, otherwise an error will be reported.

Also remember to get APIKEY. At that time, configure it in env.

# 云片
YUNPIAN_API_KEY=9c60bdd**********
Copy after login

2. Installation easy-sms package

Use this package to quickly implement the SMS sending function.

composer require "overtrue/easy-sms"
Copy after login

Since this component does not yet have Laravel's ServiceProvider, for the convenience of use, we can encapsulate it ourselves.

First add the easysms.php file in the config directory

Fill in the following content in config/easysms.php.

<?php
return [
 // HTTP 请求的超时时间(秒)
 &#39;timeout&#39; => 5.0,

 // 默认发送配置
 &#39;default&#39; => [
  // 网关调用策略,默认:顺序调用
  &#39;strategy&#39; => \Overtrue\EasySms\Strategies\OrderStrategy::class,

  // 默认可用的发送网关
  &#39;gateways&#39; => [
   &#39;yunpian&#39;,
  ],
 ],
 // 可用的网关配置
 &#39;gateways&#39; => [
  &#39;errorlog&#39; => [
   &#39;file&#39; => &#39;/tmp/easy-sms.log&#39;,
  ],
  &#39;yunpian&#39; => [
   &#39;api_key&#39; => env(&#39;YUNPIAN_API_KEY&#39;),
  ],
 ],
];
Copy after login

Then create a ServiceProvider

php artisan make:provider EasySmsServiceProvider
Copy after login

Modify the fileapp/providers/EasySmsServiceProvider.php

<?php

namespace App\Providers;

use Overtrue\EasySms\EasySms;
use Illuminate\Support\ServiceProvider;

class EasySmsServiceProvider extends ServiceProvider
{
 /**
  * Bootstrap the application services.
  *
  * @return void
  */
 public function boot()
 {
  //
 }

 /**
  * Register the application services.
  *
  * @return void
  */
 public function register()
 {
  $this->app->singleton(EasySms::class, function ($app) {
   return new EasySms(config(&#39;easysms&#39;));
  });

  $this->app->alias(EasySms::class, &#39;easysms&#39;);
 }
}
Copy after login

Finally in config/app.php Add the service you just created in providers, App\Providers\EasySmsServiceProvider::class,

App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,

App\Providers\EasySmsServiceProvider::class, //easy-sms
Copy after login

3, Create a route and corresponding controller

First create the route, we need an ajax method to request the SMS verification code, and a logical method to confirm the registration, as follows:

Route::group([&#39;prefix&#39; => &#39;verificationCodes&#39;, &#39;as&#39; => &#39;verificationCodes.&#39;], function() {
  Route::post(&#39;register&#39;, &#39;VerificationCodesController@register&#39;)->name(&#39;register&#39;);
  Route::get(&#39;ajaxregister&#39;, &#39;VerificationCodesController@ajaxregister&#39;)->name(&#39;ajaxregister&#39;);
 });
Copy after login

After the route is created, we use the command to generate the controller

php artisan make:controller Home\VerificationCodesController
Copy after login

and then directly write the register and ajaxregister methods in it

Code logic

Modify the file

app/Home/VerificationCodesController.php

<?php
.
.
.
use Overtrue\EasySms\EasySms;
use App\Models\System\User;
class VerificationCodesController extends Controller
{
 // 这里验证就不写了。
 public function ajaxregister(VerificationCodeRequest $request, EasySms $easySms)
 {
  //获取前端ajax传过来的手机号
  $phone = $request->phone;
  
  // 生成4位随机数,左侧补0
  $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
  
  try {
   $result = $easySms->send($mobile, [
    &#39;content&#39; => "【安拾商城】您的验证码是{$code}。如非本人操作,请忽略本短信"
   ]);
  } catch (Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
   $response = $exception->getExceptions();
   return response()->json($response);
  }
  
  //生成一个不重复的key 用来搭配缓存cache判断是否过期
  $key = &#39;verificationCode_&#39; . str_random(15);
  $expiredAt = now()->addMinutes(10);
  
  // 缓存验证码 10 分钟过期。
  \Cache::put($key, [&#39;mobile&#39; => $mobile, &#39;code&#39;=> $code], $expiredAt);
  
  return response()->json([
   &#39;key&#39; => $key,
   &#39;expired_at&#39; => $expiredAt->toDateTimeString(),
  ], 201);
 }
Copy after login

In this way, the user can receive the text message, and The front end should save this key and pass it to the backend when submitting the registration form to determine whether it has expired. The following is to determine whether it has expired and whether the verification code is wrong.

public function register(VerificationCodeRequest $request)
{
 //获取刚刚缓存的验证码和key
 $verifyData = \Cache::get($request->verification_key);
 
 //如果数据不存在,说明验证码已经失效。
 if(!$verifyData) {
  return response()->json([&#39;status&#39; =>0, &#39;message&#39;=> &#39;短信验证码已失效&#39;], 422);
 }
 
 // 检验前端传过来的验证码是否和缓存中的一致
 if (!hash_equals($verifyData[&#39;code&#39;], $request->verification_code) {
  return redirect()->back()->with(&#39;warning&#39;, &#39;短信验证码错误&#39;);
 }
 
 $user = User::create([
  &#39;mobile&#39; => $verifyData[&#39;mobile&#39;],
  &#39;password&#39; => bcrypt($request->password),
 ]);

 // 清除验证码缓存
 \Cache::forget($request->verification_key);

 return redirect()->route(&#39;login&#39;)->with(&#39;success&#39;, &#39;注册成功!&#39;);
 
}
Copy after login

The above hash_equals is a string comparison that can prevent timing attacks~

The above is my entire process.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use Laravel to generate Gravatar avatar address

How to create a custom artisan make command through laravel Create a new class file

The above is the detailed content of How to implement SMS registration in Larav. 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
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.

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

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

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.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles