This article through the sample code to introduce the use of laravel-sms to build SMS verification code to send the calibration module, very good, with reference value, the need for friends can refer to the next
Laravel implementation of SMS Verification code function, search data found more popular has two packages:
One is laravel SMS address https://github.com/toplan/laravel-sms
One is easy SMS address https://github.com/overtrue/easy-sms,
The project needs to implement a function of sending and verifying the SMS Verification code. The previous approach was slightly cumbersome. By expert guidance, found that can be replaced with laravel-sms this package. And the configuration and use of simple and easy to learn. Therefore, this example is available.
This example uses Laravel 5.5, Api Starter Kit, and Laravel Sms 2.6.
This example uses the SMS service provider as a cloud slice.
Installation
Execute under Project root (recommended):
Composer require toplan/laravel-sms:~2.6composer require toplan/laravel-sms:~2.6
You can also add it in the Require field of Composer.json:
"Toplan/laravel-sms": "2.6" "toplan/laravel-sms": "2.6"
Then execute it under the project root directory:
Composer Updatecomposer Update
In the providers array of config/app.php, add:
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 under 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.
The agent information and the Equalization scheduling scheme can be configured in phpsms.php.
In the laravel-sms.php, you can configure the authentication code to send and verify the scheme.
The 2015_12_21_111514_create_sms_table.php file is also copied to the Database\migrations. Used to generate the Laravel_sms table.
Configuration
Here are just a few examples of cloud slices.
Configure phpsms.php
Sets the agent information for the cloud slice in the agnets array in phpsms.php.
' Yunpian ' + [//user Unique identification, must ' apikey ' = ' = ' here to fill in your Apikey ',], ' Yunpian ' + [//user Unique identifier, must ' apikey ' = ' + ' here to fill your Apik EY ',],
Set the scheme array and configure the Equalization scheduling scheme.
' Scheme ' = [' Yunpian ',], ' scheme ' = [' Yunpian ',],
Configure laravel-sms.php
Set up a built-in route.
' route ' + = [' enable ' = ' = ', ' prefix ' = ' laravel-sms ', ' middleware ' + [' API '],], ' route ' = > [' Enable ' = True, ' prefix ' = ' laravel-sms ', ' middleware ' = [' API '],],
Sets the request interval in seconds.
' Interval ', ' interval ' = 60,
Set up number validation rules.
' Validation ' = [' phone_number ' = ' = ' =//field to be verified ' ismobile ' + true,//whether this field is a mobile number ' enable ' and true,//whether validation is required ' Default ' = ' mobile_required ',//defaults to the static rule ' staticrules ' = [//All static rules ' mobile_required ' = ' Required|zh_mobile ',],],], ' validation ' = = [' phone_number ' = =//field to be verified ' ismobile ' = true,//whether this field is a mobile number ' enabl E ' = = true,//need to verify ' default ' = ' mobile_required ',//default static rule ' staticrules ' = [//All static rules ' mobile _required ' = ' required|zh_mobile ',],],
Set up CAPTCHA rules.
' Code ' = [' length ' = + 4,//Captcha length ' validminutes ' = + 10,//verification code valid time length, in minutes ' repeatifvalid ' + true,//verification code has Whether the ' maxattempts ' + 0 is reused during the validity period, the maximum number of verification codes attempted, 0 or negative is not enabled], ' Code ' = [' length ' = 4,//Captcha length ' validminutes ' => ; 10,//Verification code effective time, in minutes ' repeatifvalid ' + true,//verification code is valid for re-use of ' maxattempts ' + 0,//Verification code maximum attempted verification, 0 or negative number is not enabled],
Set the CAPTCHA content SMS.
' Content ' = function ($code, $minutes, $input) {return ' Your verification code is: {$code} (valid for {$minutes} minutes, if not in person, please ignore) ";}, ' content ' =& Gt function ($code, $minutes, $input) {return "Your verification code is: {$code} (valid for {$minutes} minutes, please ignore it if you do not)";},
If necessary, you can turn on the database log. You need to run PHP artisan migrate to generate the Laravel_sms table ahead of time.
' Dblogs ' = ' ture ', ' dblogs ' = ' ture ',
API implementation
Create a new smscodeutil.php under App/utils, and implement the verification code sending and verifying function inside. Such other classes can be called at any time to improve the reusability of the code.
Send Module
The phone number needs to be verified before sending, including:
Validatesendable (): Verify that the Send interval is met Validatefields (): Verify data legitimacy
After 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 (! $resul t[' 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 ') ]); }}
Calibration module
When you log in, you may need to verify your phone number and verification code. Therefore, you need to add verification code check function in smscodeutil.php. Here, the official Github has already given the code, slightly modified.
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 ()) {//validation fails, it is recommended to empty the sending State of the store, preventing the user from repeating the trial and error 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 ()) {//validation fails, it is recommended to empty the sending State of the store, preventing the user from repeating the trial and error smsmanager::forgetstate (); Respondunprocessable ( Formatvalidationerrors ($validator)); }}
Functional Testing
Next configure the Routing and Controller, the test function is normal.
You can also open host-domain/laravel-sms/info The View verification code SMS send and check status.
If the database log is enabled, you can view the details of the text message 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 ');
Then add it in the 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 server address/api/auth/send-sms-code{ "Phone_number": "Phone Number"}post server address/api/auth/send-sms-code{ "Phone_number ":" Phone Number "}
If it is verified and sent successfully, it will return:
{ "message": "SMS Verification code sent successfully, please pay attention to check", "Status_code": 200}{ "message": "SMS Verification code sent successfully, please pay attention to check", "Status_code": 200}
The phone number that is filled in at the same time accepts the verification code.
If the validation fails or the send fails, the corresponding error message is returned.
Verification Code
POST server address/api/auth/validate-sms-code{ "Phone_number": "Phone number", "Sms_code": "Captcha"}post server address/api/auth/ validate-sms-code{ "Phone_number": "Phone number", "Sms_code": "Verification Code"}
If verified, no return is obtained.
If the validation fails, the corresponding error message is returned.
Localization Hint Information language
The customization of some of the information is provided in laravel-sms.php. To convert the rest of the information to the local language, you need to deal with it separately.
First make sure that the language in config/app.php is set correctly. This is set to ZH_CN.
' Locale ' = ' zh_cn ', ' locale ' = ' zh_cn ',
Then create a new validation.php under the Resources\lang\zh_cn folder and fill in the localization information:
return [' Required ' = ' Missing: attribute parameter ', ' zh_mobile ' = ' non-standard China Mobile phone number ', ' confirm_mobile_not_change ' = ' The submitted mobile number has been changed ', ' verify_code ' = ' + ' verification code is not valid or invalid ', ' attributes ' = ' + ' [' phone_number ' = ' + ' phone number ', ' Sms_code ' = ' Captcha ',],];return [' Required ' = ' Missing: attribute parameter ', ' zh_mobile ' = ' non-standard China Mobile phone number ', ' Confirm_mobile_ Not_change ' + ' submitted mobile number has been changed ', ' Verify_code ' and ' = ' Verification code is not valid or invalid ', ' attributes ' and ' = ' phone_number ' = ' " mobile number ' , ' sms_code ' = ' verification Code ',],;
Re-POST the relevant address, you can see the corresponding message language has been localized.
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!