This article mainly introduces the Laravel implementation of SMS Registration example code, the use of cloud-based SMS platform, the content is very good, and now share to everyone, but also for everyone to do a reference.
Is the company to do a mall project, because there is only one backstage, so registration with SMS registration is my turn to do. Just beginning, my heart is still a bit empty, fortunately there is a Laravel-china
community of the summer
great God, wrote the book. In the inside reference to its writing and ideas, and use the easy-sms
package, this only used half the afternoon time, smooth to make, the evening hurriedly and everyone to share a wave.
1. Identify SMS Operators
I see the big guys are using the cloud film, I also do not hesitate to recommend the company with this message platform, but other can also be slightly.
First register an account, and then find this
Click Start Access to complete the novice boot process.
The second part of the signature and template must be filled, similar to what I have written below
It is worth noting that this template must be with you at the time of the easy-sms
package, set the text message must be the same as this, or it will be an error.
Still have to remember must get apikey. At the time, configure it in Env.
# Cloud Slice yunpian_api_key=9c60bdd**********
2. Installation easy-sms
Package
Using this package, you can quickly implement the text messaging function.
Composer require "Overtrue/easy-sms"
Since the component is not Laravel ServiceProvider
, we can encapsulate it ourselves for ease of use.
First add the file in the Config directory easysms.php
Fill in the config/easysms.php below.
<?phpreturn [////HTTP Request timeout (seconds) ' Timeout ' = 5.0,//default send configuration ' default ' = [ //Gateway invoke policy, default: Sequential call ' strategy ' = = \overtrue\easysms\strategies\orderstrategy::class, //default available send Gateway ' gateways ' = [ ' Yunpian ', ],],///Available gateway configuration ' gateways ' = [' errorlog ' = ' = ' file ' = '/tmp/easy-sms.log ', ], ' Yunpian ' = ' + [ ' api_key ' = env (' Yunpian_api_key '),],] ;
Then create a serviceprovider
PHP Artisan Make:provider Easysmsserviceprovider
Modify File app/providers/easysmsserviceprovider.php
<?phpnamespace App\providers;use Overtrue\easysms\easysms;use Illuminate\support\serviceprovider;class Easysmsserviceprovider extends serviceprovider{/** * Bootstrap the application services. * * @return void * /Public Function boot () { //}/** * Register the application services. * * @return void */public function Register () { $this->app->singleton (Easysms::class, function ($ APP) { return new easysms (config (' easysms ')); }); $this->app->alias (easysms::class, ' easysms '); }}
Finally config/app.php
add the providers
service that you just created in the to write it in,App\Providers\EasySmsServiceProvider::class,
app\providers\appserviceprovider::class,app\providers\authserviceprovider::class,//App\Providers\ Broadcastserviceprovider::class,app\providers\eventserviceprovider::class,app\providers\routeserviceprovider:: Class,app\providers\easysmsserviceprovider::class,//easy-sms
3. Create routes and corresponding controllers
To create the route first, we need a method for the AJAX request SMS verification code, and a logical method for confirming the registration, as follows:
Route::group ([' prefix ' = ' verificationcodes ', ' as ' = ' verificationcodes. '], function () { Route::p Ost (' Register ', ' Verificationcodescontroller@register ')->name (' register '); Route::get (' Ajaxregister ', ' Verificationcodescontroller@ajaxregister ')->name (' Ajaxregister '); });
The route is created, and we generate the controller with the command.
PHP Artisan Make:controller Home\verificationcodescontroller
And then just write it in there register
and ajaxregister
the method.
Code logic
Modify a file
app/home/verificationcodescontroller.php
<?php...use overtrue\easysms\easysms;use App\models\system\user;class Verificationcodescontroller extends controller{//The verification will not be written here. Public Function Ajaxregister (verificationcoderequest $request, easysms $easySms) {//Get front end AJAX-transmitted phone number $phone = $request-& Gt;phone; Generate 4-bit random number, left 0 $code = Str_pad (Random_int (1, 9999), 4, 0, str_pad_left); try {$result = $easySms->send ($mobile, [' content ' = ' "'" ' "" "The Mall" Your verification code is {$code}. If I do not operate, please ignore this text message "]); } catch (Overtrue\easysms\exceptions\nogatewayavailableexception $exception) {$response = $exception Getexceptions (); return response ()->json ($response); }//Generate a non-repeating key to match the cache to determine whether it expires $key = ' Verificationcode_ '. Str_random (15); $expiredAt = Now ()->addminutes (10); The cache verification code expires 10 minutes. \cache::p ut ($key, [' Mobile ' + $mobile, ' code ' = $code], $expiredAt); return response ()->json ([' key ' = $key, ' expired_at ' and ' = ' $expiredAt->todatetimestring (),], 201); }
In this way, the user will be able to receive text messages, and the front-end should save this key
, submit a registration form when passed to the background, to determine whether it has expired. Here is the decision whether to expire, the verification code is wrong.
Public Function Register (verificationcoderequest $request) {//Get the verification code and key $verifyData Just cached = \cache::get ($request, Verification_key); If the data does not exist, the verification code is invalid. if (! $verifyData) { return response ()->json ([' Status ' =>0, ' message ' = ' SMS Verification Code expired '], 422);} Verify that the verification code passed by the front end is consistent with the IF in the cache (!hash_equals ($verifyData [' Code '], $request->verification_code) { return redirect ( )->back ()->with (' Warning ', ' SMS Verification Code error '); } $user = User::create ([ ' mobile ' + $verifyData [' mobile '], ' password ' = bcrypt ($request password),]); Clear Authenticode Cache \cache::forget ($request->verification_key); Return Redirect ()->route (' login ')->with (' Success ', ' Registration successful! '); }
Above hash_equals
is a string comparison that prevents sequence attacks ~
This is my whole process.
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!