我們這邊先申請了一個短信模板以及簽名頭,過程省略。
短信的內(nèi)容是這樣的:
短信簽名內(nèi)容:“XX科技”
短信正文內(nèi)容:{1}為您的登錄驗證碼,請于{2}分鐘內(nèi)填寫
短信模板ID:138418
第一步:先集成騰訊云SDK
在項目根目錄的composer.json內(nèi)依賴qcloudsms
"require": {
"qcloudsms/qcloudsms_php": "0.1.*"
}
添加完成之后 composer update 安裝
第二步:添加配置信息
我們需要在.env文件中,將我們騰訊云的配置信息輸入進去,以便日后配置。
QCLOUD_SMS_APP_ID=0123456789//這里是假滴
QCLOUD_SMS_APP_KEY=3a54d5f0a127b85860baedasdhh8ok//這也是假滴
QCLOUD_SMS_SIGN=XX科技
接著在根目錄下的“config”文件夾中,新建一個sms.php的文件,用于取出這些配置項:
//sms.php
<?php
return [
'app_id' => env('QCLOUD_SMS_APP_ID',''),
'app_key' => env('QCLOUD_SMS_APP_KEY',''),
'smsSign' => env('QCLOUD_SMS_SIGN','')
];
第三步:構(gòu)建一個發(fā)送驗證碼的Service
這里新建一個CodeService.php,詳情如下
//CodeService.php
namespace App\Services;
use App\Models\Captcha;
use Qcloud\Sms\SmsSingleSender;
class CodeService
{
protected $smsServer;
protected $sms;
protected $templateId;
public function __construct(){
$this->sms = config('sms');
$this->smsServer = new SmsSingleSender($this->sms['app_id'],$this->sms['app_key']);
$this->templateId = '138418';
}
public function getCode($phone,$code)
{
$result = $this->smsServer->sendWithParam(
'86',
$phone,
$this->templateId,
[$code,30],
$this->sms['smsSign']
);
return json_decode($result, true);
}
}
第四步:寫個控制器,綁定路由測試
首先,為了方便/route/api.php里頭配置命名空間,我這邊把api.php的指向路徑改為Controller目錄下的Api內(nèi)。
在app/Providers/RouteServiceProvider內(nèi)修改,Laravel官方文檔內(nèi)有說。
//文件最下方,在namespace后拼接上\Api,記得轉(zhuǎn)義
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace.'\\Api')
->group(base_path('routes/api.php'));
}
創(chuàng)建一個控制器-CaptchasController,調(diào)用驗證碼服務(wù)
//CaptchasController.php
<?php
namespace App\Http\Controllers\Api\Other;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\ApiController;
use App\Http\Requests\CaptchaGetRequest;
use App\Services\CodeService;
class CaptchasController extends ApiController
{
public function getCode(CodeService $codeService,CaptchaGetRequest $request){
$code = mt_rand(0,9999);
$code = str_pad($code,4,0,STR_PAD_RIGHT);
$phone = $request->get('phone');
$result = $codeService->getCode($phone,$code);
if ($result['result'] == 0){
return $this->success(null);
}else{
return $this->failed($result['result']);
}
}
}
最后在api.php中,綁定這個路由即可
//api.php
Route::group(['namespace' => 'Other'], function() {
Route::post('/captchas', 'CaptchasController@getCode');
});
測試一哈:

image.png
短信收到,歐幾把k,接下來可以做驗證碼的驗證過程了。