Use laravel sms to build the sms Verification Code sending verification function, laravelsms

Source: Internet
Author: User

Use laravel sms to build the sms Verification Code sending verification function, laravelsms

Laravel implements the text message verification code function. Two popular packages are found in the search:

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

One is the easy sms address https://github.com/overtrue/easy-sms,

The project needs to implement the function of sending and verifying the SMS verification code. The previous method is a little complicated. We found that laravel-sms can be used instead. It is easy to configure and use. Therefore, this example is provided.

In this example, Laravel 5.5, Api Starter Kit, and Laravel Sms 2.6 are used.

In this example, the text message service provider is cloud.

Install

Run the following command in the project root directory (recommended ):

composer require toplan/laravel-sms:~2.6composer require toplan/laravel-sms:~2.6 

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

"toplan/laravel-sms": "2.6""toplan/laravel-sms": "2.6" 

Run the following command in the project root directory:

composer updatecomposer update

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

Toplan\PhpSms\PhpSmsServiceProvider::class,Toplan\Sms\SmsManagerServiceProvider::class,Toplan\PhpSms\PhpSmsServiceProvider::class,Toplan\Sms\SmsManagerServiceProvider::class, 

Add the following 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,

Run the following command 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" 

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

In phpsms. php, you can configure proxy information and a balanced scheduling scheme.

You can configure the send and verify scheme of the verification code in the laravel-sms.php.

Copy the 2015_12_21_111514_create_sms_table.php file to database \ migrations. Generate the laravel_sms table.

Configuration

Here, we only use cloud films as an example.

Configure phpsms. php

Set the agent information of cloud slices in the agnets array in phpsms. php.

''Piany'' => [// Unique User ID, which must be 'apikey' => 'enter your apikey' here,], ''piany'' => [// Unique User ID, which must be 'apikey' => 'enter your apikey' here,],

Set the scheme array and configure the balanced scheduling scheme.

'scheme' => [ 'YunPian',],'scheme' => [ 'YunPian',], 

Configure laravel-sms.php

Set the built-in route.

'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' => [// The Field 'ismobile' to be verified => true, // whether this field is the mobile phone number 'enable' => true, // whether to verify 'default' => 'mobile _ required ', // default static rule 'staticrules' => [// All static rules 'mobile _ required' => 'required | zh_mobile ',], 'validation '=> ['phone _ number' => [// The Field 'ismobile' to be verified => true, // whether this field is the mobile phone number 'enable' => true, // whether to verify 'default' => 'mobile _ required ', // default static rule 'staticrules' => [// All static rules 'mobile _ required' => 'required | zh_mobile ',],

Set Verification Code rules.

'Code' => ['length' => 4, // verification code length 'validminutes '=> 10, // Verification code validity period, the Unit is minute 'repeatifvalid' => true, // whether the 'maxattempts' => 0 is repeatedly used in the verification code validity period, // The maximum number of times the verification code is verified, 0 or negative, do not enable], 'code' => ['length' => 4, // verification code length 'validminutes '=> 10, // Verification code validity period, the Unit is minute 'repeatifvalid' => true, // whether the 'maxattempts' => 0 is repeatedly used in the verification code validity period, // The maximum number of times the verification code is verified, 0 or negative, but not enabled],

Set the verification code content text message.

'Content' => function ($ code, $ minutes, $ input) {return "your verification code is valid within {$ code} ({$ minutes} minutes, if you do not perform this operation, ignore it) ";}, 'content' => function ($ code, $ minutes, $ input) {return" your verification code is: {$ code} (valid within {$ minutes} minutes, if not operated by myself, please ignore )";},

If necessary, you can enable database logs. Run php artisan migrate in advance to generate the laravel_sms table.

'dbLogs' => 'ture','dbLogs' => 'ture',

API implementation

Create SmsCodeUtil. php under app/Utils and implement the verification code sending and verification functions. In this way, other classes can be called at any time to improve code reusability.

Sending Module

Verify the mobile phone number before sending, including:

ValidateSendable (): verify whether the sending interval is met validateFields (): Verify Data Validity

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

The 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

During login, you may need to verify the mobile phone number and verification code. Therefore, you need to add the verification code verification function in SmsCodeUtil. php. The Code has been provided on the official Github. Just make a slight modification.

Public function validateSmsCode () {// verify data $ validator = Validator: make (inputAll (), ['phone _ number' => 'required | confirm_mobile_not_change | confirm_rule: mobile_required ', 'sms _ Code' => 'required | verify_code ',]); if ($ validator-> fails () {// It is recommended to clear the sending status of the storage after the verification fails, prevent users from retrying SmsManager: forgetState (); respondUnprocessable (formatValidationErrors ($ validator);} public function validateSmsCode () {// verify data $ validator = Validator :: make (inputAll (), ['phone _ number' => 'required | confirm_mobile_not_change | confirm_rule: mobile_required ', 'sms _ Code' => 'required | verify_code',]); if ($ validator-> fails () {// after the verification fails, we recommend that you clear the sending status of the storage to prevent the user from re-trying the error SmsManager: forgetState (); respondUnprocessable (formatValidationErrors ($ validator ));}}

Function Testing

Next, configure the route and controller, and test whether the function is normal.

Can be opened at the same timehost-domain/laravel-sms/info View the SMS sending and verification status of the verification code.

If database logs are enabled, you can view the details of the text message sending result in the laravel_sms table.

Add the following 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');

Add the following in LoginController. php:

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

Use Postman or other similar tools to test Api functions.

Send verification code 

POST Server address/api/auth/send-sms-code {"phone_number": "mobile phone number"} POST server address/api/auth/send-sms-code {"phone_number ": "Mobile Phone Number "}

If the verification is passed and the message is sent successfully, the following message is returned:

{"Message": "The SMS verification code has been sent successfully. Check the message", "status_code": 200 }{ "message": "The SMS verification code has been sent successfully. Check the message ", "status_code": 200}

At the same time, the entered mobile phone number receives the verification code.

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

Verification Code

POST Server address/api/auth/validate-sms-code {"phone_number": "mobile phone number", "sms_code ": "Verification code"} POST server address/api/auth/validate-sms-code {"phone_number": "mobile phone number", "sms_code": "Verification code "}

If verification is passed, no response is returned.

If the verification fails, the corresponding error message is returned.

Localized prompt information language

Custom partial prompt information is provided in the laravel-sms.php. To convert the remaining part of the prompt information to a local language, you need to handle it separately.

First, make sure that the language settings in config/app. php are correct. Set zh_cn here.

'locale' => 'zh_cn','locale' => 'zh_cn', 

Then, create validation. php In the resources \ lang \ zh_cn folder and enter the localization information:

Return ['requestred' => 'missing: attribute parameter ', 'zh _ mobile' => 'non-standard Chinese Mainland mobile phone no ', 'Confirm _ mobile_not_change '=> 'the submitted mobile phone number has changed', 'verify _ Code' => 'verification code is invalid or invalid ', 'tes buckets' => ['phone _ number' => 'mobile phone number', 'sms _ Code' => 'verification code ',],]; return ['requestred' => 'missing: attribute parameter ', 'zh _ mobile' => 'non-standard Chinese Mainland mobile phone no ', 'Confirm _ mobile_not_change '=> 'the submitted mobile phone number has changed', 'verify _ Code' => 'verification code is invalid or invalid ', 'tes buckets' => ['phone _ number' => 'mobile phone number', 'sms _ Code' => 'verification code ',],];

Repost the related address to see that the corresponding prompt information language has been localized.

Summary

The above section describes how to use laravel-sms to build an sms Verification Code sending verification module. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.