laravel spa单页面手机短信验证码实现

发布时间:2023-10-13 15:26:22 浏览次数:264

1.安装第三方插件

composer require "overtrue/easy-sms"

2.配置config文件->config/sms.php 这里使用的云片

<?php

return [
    // HTTP 请求的超时时间(秒)
    'timeout' => 5.0,
    
    // 默认发送配置
    'default' => [
        // 网关调用策略,默认:顺序调用
        'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
        
        // 默认可用的发送网关
        'gateways' => [
            'yunpian'
        ],
    ],
    // 可用的网关配置
    'gateways' => [
        'errorlog' => [
            'file' => '/tmp/easy-sms.log',
        ],
        'yunpian' => [
            'api_key' => 'xxxxxxxx',
            'signature' => '【】', // 内容中无签名时使用
        ],
    ],
];

3.获取验证码,返回缓存的短信验证码key

/**
 * 获取手机验证码
 *
 */
 
public function getSmsCode(Request $request)
{
    if ($phone = $request->phone) {
  
        try {
            $easySms = new EasySms(config('sms'));
            $code = mt_rand(0000, 9999);
                
            $smsContent = [
                'content'  => '您的验证码是'.$code,
            ];
            $result = $easySms->send($phone, $smsContent);

            $key = 'verificationCode_'.str_random(15);
            $expiredAt = now()->addMinutes(10);
            // 缓存验证码 10分钟过期。
            Cache::put($key, ['phone' => $phone, 'code' => $code], $expiredAt);

            $data = [
                'sms_key' => $key,
                'expired_at' => $expiredAt->toDateTimeString(),
            ];
            return response()->json(['code'=>0, 'data'=>$data, 'message'=>'短信验证码发送成功']);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getException('yunpian')->getMessage();
            return response()-json(['code'=>10001, 'message'=>$message ?: '短信发送异常']);
        }
    }
}

4.通过短信验证码key,获取验证码,进行比对

$cacheCode = Cache::get($request->smsKey);
if ($cacheCode) {
    if ($request->smsCode != $cacheCode['code']) {
        return $this->errorWithCode('短信验证码不正确',1,422);
    }
} else {
    return $this->errorWithCode('验证码已过期,请重新发送',1,422);
}


最新文章
备案号:赣ICP备2022011147号-1
备案号:赣ICP备2022011147号-2