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

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles