Home > Article > Backend Development > 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');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; ... }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": "手机号" }If the verification code is passed and sent successfully, It will return:
{ "message": "短信验证码发送成功,请注意查收", "status_code": 200 } { "message": "短信验证码发送成功,请注意查收", "status_code": 200 }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": "验证码" }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',
然后在 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!