首頁  >  文章  >  後端開發  >  php手機驗證碼怎麼實現

php手機驗證碼怎麼實現

藏色散人
藏色散人原創
2021-03-08 11:20:414344瀏覽

php手機驗證碼的實作方法:先註冊雲端片以及開發資訊認證,並進行範本設定;然後在「easysms.php」檔案內加入「'default'=>[]」等內容;接著取得雲片的API_KEY;最後透過控制器程式碼取得驗證碼即可。

php手機驗證碼怎麼實現

本文操作環境:Windows7系統、PHP7.1、Dell G3電腦。

PHP手機簡訊驗證碼實現流程詳解

本人在自己部落格(Laravel)的註冊部分 使用手機號碼註冊,需要發送簡訊驗證碼。

使用雲端片的簡訊服務供應商,當然具體簡訊服務供應商大家可以自由選擇。

1、實作流程

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

#2、實作想法圖

3、註冊雲片,以及開發資訊認證,範本設定,這裡就不詳細展開了【推薦:《PHP影片教學》】

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

composer require "overtrue/easy-sms"
//新建配置文件
touch config/easysms.php

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

 <?php

  return [

    &#39;timeout&#39;=>5.0,
    &#39;default&#39;=>[
      // 网关调用策略,默认:顺序调用
      &#39;strategy&#39; => \Overtrue\EasySms\Strategies\OrderStrategy::class,

      // 默认可用的发送网关
      &#39;gateways&#39; => [
        &#39;yunpian&#39;,
      ],
    ],
    // 可用的网关配置
    &#39;gateways&#39; => [
      &#39;errorlog&#39; => [
        &#39;file&#39; => &#39;/tmp/easy-sms.log&#39;,
      ],
      &#39;yunpian&#39; => [
        &#39;api_key&#39; => env(&#39;YUNPIAN_API_KEY&#39;),
      ],
    ],

];

然後建立一個ServiceProvider

php artisan make:provider EasySmsServiceProvider

修改檔案

app/providers/EasySmsServiceProvider. php

<?php

namespace 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(&#39;easysms&#39;));

    });

    $this->app->alias(EasySms::class,&#39;easysms&#39;);
  }
}

最後開啟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(),
        [&#39;mobile&#39; => &#39;required|regex:/^1[34578]\d{9}$/|unique:users&#39;],[
          &#39;mobile.required&#39;=>&#39;请输入手机号&#39;,
          &#39;mobile.regex&#39;=>&#39;手机号格式不正确&#39;,
          &#39;mobile.unique&#39;=>&#39;手机号已存在&#39;
        ])){
      return false;
    }

    $mobile = trim($request->get(&#39;mobile&#39;));
    $code = str_pad(random_int(1,9999),4,0,STR_PAD_LEFT);


    try{
       $easySms->send($mobile,
        [&#39;content&#39;=>"【UKNOW】您的验证码是{$code}。如非本人操作,请忽略本短信"]       );

    }catch(\GuzzleHttp\Exception\ClientException $exception){

      $response = $exception->getResponse();
      $result =json_decode($response->getBody()->getContents(),true);
      $this->setMsg($result[&#39;msg&#39;]?? &#39;短信发送异常&#39;);
      return false;
    }

    $key = &#39;verificationCode&#39;.str_random(15);
    $expiredAt = now()->addMinutes(1);
    Cache::put($key,[&#39;mobile&#39;=>$mobile,&#39;code&#39;=>$code],$expiredAt);

    return [
      &#39;verification_key&#39;=>$key,
      &#39;expiredAt&#39;=>$expiredAt->toDateTimeString(),
      &#39;verification_code&#39;=>$code
      ];
}

7、比較驗證碼

public function userStore($mobile, $verification_key,$code,$password,$password_confirmation)
 {

  $params = [
   &#39;mobile&#39;=>$mobile,
   &#39;verification_key&#39;=>$verification_key,
   &#39;code&#39;=>$code,
   &#39;password&#39;=>$password,
   &#39;password_confirmation&#39;=>$password_confirmation
  ];
  //参数判断
  if (
   FALSE === $this->validateApiRequest($params, [
    &#39;mobile&#39; => &#39;required|regex:/^1[34578]\d{9}$/|unique:users&#39;,
    &#39;code&#39; => &#39;required&#39;,
    &#39;verification_key&#39;=>&#39;required&#39;,
    &#39;password&#39;  => &#39;required|min:6|confirmed&#39;,
    &#39;password_confirmation&#39; => &#39;required&#39;,
   ], [
    &#39;mobile.required&#39; => &#39;请输入手机号&#39;,
    &#39;mobile.regex&#39; => &#39;手机号格式不正确&#39;,
    &#39;mobile.unique&#39; => &#39;手机号已存在&#39;,
    &#39;code.required&#39; => &#39;请输入短信验证码&#39;,
    &#39;password.required&#39; => &#39;请输入密码&#39;,
    &#39;password.min&#39;   => &#39;密码不得小于6位&#39;,
    &#39;password.confirmed&#39; => &#39;密码前后不一致&#39;,
    &#39;password_confirmation.required&#39;=>&#39;请再次输入密码&#39;,
    &#39;verification_key.required&#39;=>&#39;请输入短信验证码&#39;
   ])
  ) {
   return false;
  }

  $verifyData = Cache::get($verification_key);
  if( !$verifyData){
   $this->setMsg(&#39;验证码已失效&#39;);
   return false;
  }
  if(!hash_equals($code,(string)$verifyData[&#39;code&#39;])){
   $this->setMsg(&#39;验证码错误&#39;);
   return false;
  }

  Cache::forget($verification_key);
  $user = User::create([
   &#39;mobile&#39;=>$mobile,
   &#39;password&#39;=>bcrypt($password)
  ]);
  if(!$user){
   $this->setMsg(&#39;注册失败&#39;);
   return false;
  }
  return true;
}

以上流程就是手機驗證碼基本步驟。

以上是php手機驗證碼怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn