laravel架構下php手機簡訊驗證碼實現流程

來源:互聯網
上載者:User
本篇文章給大家帶來的內容是關於 laravel架構下php手機簡訊驗證碼實現流程,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

具體簡訊服務供應商大家可以自由選擇。

1,實現流程

輸入手機號,點擊擷取驗證碼
提交正確的簡訊驗證碼後,註冊完成

2,實現思路圖

3,註冊 雲片,以及開發資訊認證,模板設定,這裡就不詳細展開了

4, 安裝 easy-sms,easy-sms 是安正超寫的一個簡訊發送組件,利用這個組件,我們可以快速的實現簡訊發送功能。

 composer require "overtrue/easy-sms"    //建立設定檔    touch config/easysms.php

然後在 easysms.php 檔案內 添加以下內容:

 <?php   return [       'timeout'=>5.0,       'default'=>[           // 網關調用策略,預設:順序調用           'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,           // 預設可用的發送網關           'gateways' => [               'yunpian',           ],       ],       // 可用的網關配置       'gateways' => [           'errorlog' => [               'file' => '/tmp/easy-sms.log',           ],           'yunpian' => [               'api_key' => env('YUNPIAN_API_KEY'),           ],       ],   ];

然後建立一個 ServiceProvider

  php artisan make:provider EasySmsServiceProvider

修改檔案

app/providers/EasySmsServiceProvider.php

<?phpnamespace App\Providers;use Illuminate\Support\ServiceProvider;use Overtrue\EasySms\EasySms;class EasySmsServiceProvider extends ServiceProvider{    /**     * Bootstrap services.     *     * @return void     */    public function boot()    {        //    }    /**     * Register services.     *     * @return void     */    public function register()    {        $this->app->singleton(EasySms::class,function ($app){            return new EasySms(config('easysms'));        });        $this->app->alias(EasySms::class,'easysms');    }}

最後 開啟config/app.php 在 providers 中增加

 App\Providers\EasySmsServiceProvider::class,

5,擷取雲片的API_KEY

在 .env中配置 YUNPIAN_API_KEY,注意下面需要替換為你自己的 key

6,控制器代碼 擷取驗證碼(將code 以及key存入緩衝)

public function getVerificationCode($request)    {        if(FALSE === $this->validateApiRequest($request->all(),                ['mobile' => 'required|regex:/^1[34578]\d{9}$/|unique:users'],[                    'mobile.required'=>'請輸入手機號',                    'mobile.regex'=>'手機號格式不正確',                    'mobile.unique'=>'手機號已存在'                ])){            return false;        }        $mobile = trim($request->get('mobile'));       $code = str_pad(random_int(1,9999),4,0,STR_PAD_LEFT);        try{             $easySms->send($mobile,                ['content'=>"【UKNOW】您的驗證碼是{$code}。如非本人操作,請忽略本簡訊"]             );        }catch(\GuzzleHttp\Exception\ClientException $exception){            $response = $exception->getResponse();            $result =json_decode($response->getBody()->getContents(),true);            $this->setMsg($result['msg']?? '簡訊發送異常');            return false;        }        $key = 'verificationCode'.str_random(15);        $expiredAt = now()->addMinutes(1);        Cache::put($key,['mobile'=>$mobile,'code'=>$code],$expiredAt);        return [            'verification_key'=>$key,            'expiredAt'=>$expiredAt->toDateTimeString(),            'verification_code'=>$code            ];    }

7,對比驗證碼

public function userStore($mobile, $verification_key,$code,$password,$password_confirmation)    {        $params = [            'mobile'=>$mobile,            'verification_key'=>$verification_key,            'code'=>$code,            'password'=>$password,            'password_confirmation'=>$password_confirmation        ];        //參數判斷        if (            FALSE === $this->validateApiRequest($params, [                'mobile'  => 'required|regex:/^1[34578]\d{9}$/|unique:users',                'code'    => 'required',                'verification_key'=>'required',                'password'     => 'required|min:6|confirmed',                'password_confirmation' => 'required',            ], [                'mobile.required' => '請輸入手機號',                'mobile.regex'    => '手機號格式不正確',                'mobile.unique'   => '手機號已存在',                'code.required'   => '請輸入簡訊驗證碼',                'password.required'    => '請輸入密碼',                'password.min'         => '密碼不得小於6位',                'password.confirmed'   => '密碼前後不一致',                'password_confirmation.required'=>'請再次輸入密碼',                'verification_key.required'=>'請輸入簡訊驗證碼'            ])        ) {            return false;        }        $verifyData = Cache::get($verification_key);        if( !$verifyData){            $this->setMsg('驗證碼已失效');            return false;        }        if(!hash_equals($code,(string)$verifyData['code'])){            $this->setMsg('驗證碼錯誤');            return false;        }        Cache::forget($verification_key);        $user = User::create([            'mobile'=>$mobile,            'password'=>bcrypt($password)        ]);        if(!$user){            $this->setMsg('註冊失敗');            return false;        }        return true;    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.