Home Backend Development PHP Tutorial Use laravel sms to build the function of sending SMS verification code for verification

Use laravel sms to build the function of sending SMS verification code for verification

Jun 13, 2018 pm 02:22 PM
laravel sms

This article introduces to you the use of laravel-sms to build an SMS verification code sending verification module through sample code. It is very good and has reference value. Friends in need can refer to

laravel to implement the SMS verification code function. , Searching for information, I found two popular packages:

One is laravel sms address https://github.com/toplan/laravel-sms

One is The address of easy sms is https://github.com/overtrue/easy-sms. The

project needs to implement a function of sending and verifying SMS verification codes. The previous method was a bit cumbersome. After advice from experts, I found that the laravel-sms package can be used instead. It is easy to configure and use. Hence this example.

This example uses Laravel 5.5, Api Starter Kit and Laravel Sms 2.6.

The SMS service provider used in this example is Yunpian.

Installation

Execute in the project root directory (recommended):

composer require toplan/laravel-sms:~2.6
composer require toplan/laravel-sms:~2.6
Copy after login

You can also add in the require field of composer.json:

"toplan/laravel-sms": "2.6"
"toplan/laravel-sms": "2.6"
Copy after login

and then execute it in the project root directory:

composer update
composer update
Copy after login

Add in the providers array of config/app.php:

Toplan\PhpSms\PhpSmsServiceProvider::class,
Toplan\Sms\SmsManagerServiceProvider::class,
Toplan\PhpSms\PhpSmsServiceProvider::class,
Toplan\Sms\SmsManagerServiceProvider::class,
Copy after login

and add in the aliases array:

'PhpSms' => Toplan\PhpSms\Facades\Sms::class,
'SmsManager' => Toplan\Sms\Facades\SmsManager::class,
'PhpSms' => Toplan\PhpSms\Facades\Sms::class,
'SmsManager' => Toplan\Sms\Facades\SmsManager::class,
Copy after login

Execute in the project root directory:

php artisan vendor:publish --provider="Toplan\PhpSms\PhpSmsServiceProvider"
php artisan vendor:publish --provider="Toplan\Sms\SmsManagerServiceProvider"
php artisan vendor:publish --provider="Toplan\PhpSms\PhpSmsServiceProvider"
php artisan vendor:publish --provider="Toplan\Sms\SmsManagerServiceProvider"
Copy after login

will be in the config folder Two configuration files are generated: phpsms.php and laravel-sms.php.

You can configure proxy information and balanced scheduling plan in phpsms.php.

The verification code sending and verification scheme can be configured in laravel-sms.php.

At the same time, the 2015_12_21_111514_create_sms_table.php file will be copied to database\migrations. Used to generate laravel_sms table.

Configuration

Here we only take cloud slices as an example.

Configure phpsms.php

Set the proxy information of the cloud slice in the agnets array in phpsms.php.

'YunPian' => [
 //用户唯一标识,必须
 'apikey' => '在这里填写你的 APIKEY',
],
'YunPian' => [
 //用户唯一标识,必须
 'apikey' => '在这里填写你的 APIKEY',
],
Copy after login

Set the scheme array and configure the balanced scheduling scheme.

'scheme' => [
 'YunPian',
],
'scheme' => [
 'YunPian',
],
Copy after login

Configure laravel-sms.php

Set built-in routing.

'route' => [
 'enable'  => true,
 'prefix'  => 'laravel-sms', 
 'middleware' => ['api'],
],
'route' => [
 'enable'  => true,
 'prefix'  => 'laravel-sms', 
 'middleware' => ['api'],
],
Copy after login

Set the request interval in seconds.

'interval' => 60,
'interval' => 60,
Copy after login

Set number verification rules.

'validation' => [
 'phone_number' => [ //需验证的字段
 'isMobile' => true, //本字段是否为手机号
 'enable'  => true, //是否需要验证
 'default'  => 'mobile_required', //默认的静态规则
 'staticRules' => [ //全部静态规则
  'mobile_required'  => 'required|zh_mobile',
 ],
 ],
],
'validation' => [
 'phone_number' => [ //需验证的字段
 'isMobile' => true, //本字段是否为手机号
 'enable'  => true, //是否需要验证
 'default'  => 'mobile_required', //默认的静态规则
 'staticRules' => [ //全部静态规则
  'mobile_required'  => 'required|zh_mobile',
 ],
 ],
],
Copy after login

Set verification code rules.

'code' => [
 'length'  => 4, //验证码长度
 'validMinutes' => 10, //验证码有效时间长度,单位为分钟
 'repeatIfValid' => true, //验证码有效期内是否重复使用
 'maxAttempts' => 0, //验证码最大尝试验证次数,0 或负数则不启用
],
'code' => [
 'length'  => 4, //验证码长度
 'validMinutes' => 10, //验证码有效时间长度,单位为分钟
 'repeatIfValid' => true, //验证码有效期内是否重复使用
 'maxAttempts' => 0, //验证码最大尝试验证次数,0 或负数则不启用
],
Copy after login

Set verification code content SMS.

'content' => function ($code, $minutes, $input) {
 return "您的验证码是:{$code} ({$minutes}分钟内有效,如非本人操作,请忽略)";
},
'content' => function ($code, $minutes, $input) {
 return "您的验证码是:{$code} ({$minutes}分钟内有效,如非本人操作,请忽略)";
},
Copy after login

If necessary, you can enable database logging. You need to run php artisan migrate in advance to generate the laravel_sms table.

'dbLogs' => 'ture',
'dbLogs' => 'ture',
Copy after login

API implementation

Create a new SmsCodeUtil.php under app/Utils, and Implement the verification code sending and verification functions inside. In this way, other classes can be called at any time, improving code reusability.

Sending module

The mobile phone number needs to be verified before sending, including:

validateSendable() :验证是否满足发送间隔 
validateFields() :验证数据合法性
Copy after login

After passing the verification, use requestVerifySms() to send the verification code.

The specific code is as follows:

use SmsManager;
trait SmsCodeUtil {
 public function sendSmsCode()
 {
 $result = SmsManager::validateSendable();
 if(!$result['success']) {
  return respondUnprocessable($result['message']);
 }
 $result = SmsManager::validateFields();
 if(!$result['success']) {
  return respondUnprocessable($result['message']);
 }
 $result = SmsManager::requestVerifySms();
 if(!$result['success']) {
  return respondUnprocessable($result['message']);
 }
 return respondSuccess($result['message']);
 }
}

use SmsManager;
trait SmsCodeUtil {
 public function sendSmsCode()
 {
 $result = SmsManager::validateSendable();
 if(!$result['success']) {
  return respondUnprocessable($result['message']);
 }
 $result = SmsManager::validateFields();
 if(!$result['success']) {
  return respondUnprocessable($result['message']);
 }
 $result = SmsManager::requestVerifySms();
 if(!$result['success']) {
  return respondUnprocessable($result['message']);
 }
 return respondSuccess($result['message']);
 }
}
Copy after login

##Verification module

When logging in, you may need to verify your mobile phone number and verification code. Therefore, the verification code verification function needs to be added to SmsCodeUtil.php. The code has been given on the official Github here and can be modified slightly.


public function validateSmsCode()
{
 //验证数据
 $validator = Validator::make(inputAll(), [
 'phone_number' => 'required|confirm_mobile_not_change|confirm_rule:mobile_required',
 'sms_code'  => 'required|verify_code',
 ]);

 if ($validator->fails()) {
 //验证失败后建议清空存储的发送状态,防止用户重复试错
 SmsManager::forgetState();
 respondUnprocessable(formatValidationErrors($validator));
 }
}
public function validateSmsCode()
{
 //验证数据
 $validator = Validator::make(inputAll(), [
 'phone_number' => 'required|confirm_mobile_not_change|confirm_rule:mobile_required',
 'sms_code'  => 'required|verify_code',
 ]);
 if ($validator->fails()) {
 //验证失败后建议清空存储的发送状态,防止用户重复试错
 SmsManager::forgetState();
 respondUnprocessable(formatValidationErrors($validator));
 }
}
Copy after login

Functional Test

Next configure the routing and controller, Test whether the function is normal.

You can open

host-domain/laravel-sms/info at the same time to view the verification code SMS sending and verification status.

If the database log is enabled, you can view the detailed information of the SMS sending results in the laravel_sms table.

First add in api.php:

$api->post('/auth/send-sms-code', 'Auth\LoginController@sendSmsCode');
$api->post('/auth/validate-sms-code', 'Auth\LoginController@validateSmsCode');
$api->post('/auth/send-sms-code', 'Auth\LoginController@sendSmsCode');
$api->post('/auth/validate-sms-code', 'Auth\LoginController@validateSmsCode');
Copy after login

Then add in LoginController.php:


use App\Utils\SmsCodeUtil;
class LoginController extends Controller {
 use SmsCodeUtil;
 ...
}
use App\Utils\SmsCodeUtil;
class LoginController extends Controller {
 use SmsCodeUtil;
 
 ...
}
Copy after login

Then use Postman or other similar tools to test the Api functionality.

Send verification code

POST 服务器地址/api/auth/send-sms-code
{
  "phone_number": "手机号"
}
POST 服务器地址/api/auth/send-sms-code
{
  "phone_number": "手机号"
}
Copy after login

If the verification code is passed and sent successfully, It will return:


{
  "message": "短信验证码发送成功,请注意查收",
  "status_code": 200
}
{
  "message": "短信验证码发送成功,请注意查收",
  "status_code": 200
}
Copy after login

The phone number filled in at the same time will receive the verification code.

If the verification fails or the sending fails, the corresponding error message will be returned.

Verification verification code

POST 服务器地址/api/auth/validate-sms-code
{
  "phone_number": "手机号",
  "sms_code": "验证码"
}

POST 服务器地址/api/auth/validate-sms-code
{
  "phone_number": "手机号",
  "sms_code": "验证码"
}
Copy after login

If the verification is passed, then there is no return.

If the verification fails, the corresponding error message will be returned.

Localized prompt information language

provides customization of some prompt information in laravel-sms.php. If you want to convert the remaining prompt information into the local language, you need to handle it separately.

First make sure the language setting in config/app.php is correct. This is set to zh_cn.

'locale' => 'zh_cn',
'locale' => 'zh_cn',
Copy after login

然后在 resources\lang\zh_cn 文件夹下新建 validation.php,并填入本地化信息:

return [
 'required' => '缺少:attribute参数',
 'zh_mobile'         => '非标准的中国大陆手机号',
 'confirm_mobile_not_change' => '提交的手机号已变更',
 'verify_code'        => '验证码不合法或无效',
 'attributes' => [
  'phone_number' => '手机号',
  'sms_code'  => '验证码',
 ],
];
return [
 'required' => '缺少:attribute参数',
 'zh_mobile'         => '非标准的中国大陆手机号',
 'confirm_mobile_not_change' => '提交的手机号已变更',
 'verify_code'        => '验证码不合法或无效',
 'attributes' => [
  'phone_number' => '手机号',
  'sms_code'  => '验证码',
 ],
];
Copy after login

重新 POST 相关地址,可以看到对应的提示信息语言已经本地化。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Laravel中重写资源路由自定义URL的实现方法

Laravel5.2使用Captcha生成验证码实现登录的方法

通过 Laravel “规范” 的开发短信验证码发送功能

The above is the detailed content of Use laravel sms to build the function of sending SMS verification code for verification. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1269
29
C# Tutorial
1249
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.

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 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.

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.

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.

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