


Use laravel sms to build the function of sending SMS verification code for verification
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
You can also add in the require field of composer.json:
"toplan/laravel-sms": "2.6" "toplan/laravel-sms": "2.6"
and then execute it in the project root directory:
composer update composer update
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,
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,
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"
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', ],
Set the scheme array and configure the balanced scheduling scheme.
'scheme' => [ 'YunPian', ], 'scheme' => [ 'YunPian', ],
Configure laravel-sms.php
Set built-in routing.
'route' => [ 'enable' => true, 'prefix' => 'laravel-sms', 'middleware' => ['api'], ], 'route' => [ 'enable' => true, 'prefix' => 'laravel-sms', 'middleware' => ['api'], ],
Set the request interval in seconds.
'interval' => 60, 'interval' => 60,
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', ], ], ],
Set verification code rules.
'code' => [ 'length' => 4, //验证码长度 'validMinutes' => 10, //验证码有效时间长度,单位为分钟 'repeatIfValid' => true, //验证码有效期内是否重复使用 'maxAttempts' => 0, //验证码最大尝试验证次数,0 或负数则不启用 ], 'code' => [ 'length' => 4, //验证码长度 'validMinutes' => 10, //验证码有效时间长度,单位为分钟 'repeatIfValid' => true, //验证码有效期内是否重复使用 'maxAttempts' => 0, //验证码最大尝试验证次数,0 或负数则不启用 ],
Set verification code content SMS.
'content' => function ($code, $minutes, $input) { return "您的验证码是:{$code} ({$minutes}分钟内有效,如非本人操作,请忽略)"; }, 'content' => function ($code, $minutes, $input) { return "您的验证码是:{$code} ({$minutes}分钟内有效,如非本人操作,请忽略)"; },
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',
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() :验证数据合法性
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']); } }
##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)); } }
Functional Test
Next configure the routing and controller, Test whether the function is normal. You can openhost-domain/laravel-sms/info at the same time to view the verification code SMS sending and verification status.
$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');
use App\Utils\SmsCodeUtil; class LoginController extends Controller { use SmsCodeUtil; ... } use App\Utils\SmsCodeUtil; class LoginController extends Controller { use SmsCodeUtil; ... }
Send verification code
POST 服务器地址/api/auth/send-sms-code { "phone_number": "手机号" } POST 服务器地址/api/auth/send-sms-code { "phone_number": "手机号" }
{ "message": "短信验证码发送成功,请注意查收", "status_code": 200 } { "message": "短信验证码发送成功,请注意查收", "status_code": 200 }
Verification verification code
POST 服务器地址/api/auth/validate-sms-code { "phone_number": "手机号", "sms_code": "验证码" } POST 服务器地址/api/auth/validate-sms-code { "phone_number": "手机号", "sms_code": "验证码" }
'locale' => 'zh_cn', 'locale' => 'zh_cn',
然后在 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' => '验证码', ], ];
重新 POST 相关地址,可以看到对应的提示信息语言已经本地化。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
Laravel5.2使用Captcha生成验证码实现登录的方法
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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.

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

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.

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.

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.

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.
