Laravel 使用阿里云的短信验证码

2 篇文章 0 订阅
阿里大鱼
[需求暂时只需要发送验证码所以使用的是阿里短信 对短信和流量有更多操作的可以使用阿里大鱼]
composer require flc/dysms                //安装
 
 
<?php   namespace App\Service;

define("UID_MOBILE_CODE_CACHE_KEY", "uid_mobile_code_cache_");
define("UID_MOBILE_CODE_CACHE_TIME", 300 );

use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use Illuminate\Support\Facades\Redis;
use Log;

class  aliyunSendSms
{
        
    public function sendSms($mobile){
        $config = [
            'accessKeyId'    => '*******',
            'accessKeySecret' => '*******',
        ];
        $code = $this->getPhoneCode();
        $client  = new Client($config);
        $sendSms = new SendSms;
        $sendSms->setPhoneNumbers($mobile);
        $sendSms->setSignName('短信签名');
        $sendSms->setTemplateCode('短信模板');
        $sendSms->setTemplateParam(['code' => $code]);
        $sendSms->setOutId('5286');
        $cliReturn = $client->execute($sendSms);
        if($cliReturn->Code=="OK"){    
                 $cacheKey = UID_MOBILE_CODE_CACHE_KEY.$mobile;
                 Redis::setex($cacheKey,UID_MOBILE_CODE_CACHE_TIME,$code); 
                 Log::info("生成短信缓存:".$code);
                return true;
         }else{ 
                return false; 
        } 
       }    
        
//验证短信验证码是否正确 
public function isCheckPhoneCode($mobile, $phoneCode){ 
        $cacheKey = UID_MOBILE_CODE_CACHE_KEY.$mobile; 
        $redisCode = Redis::get($cacheKey); 
        if(!empty($redisCode) && $redisCode == $phoneCode) 
        { 
        Log::info("短信验证码正确!");
         return true;
         } 
        Log::info("短信证验码错误:{$mobile}|imgcode{$phoneCode}|redisCode:".json_encode($redisCode)); 
        return false;
         } 
  
 // 验证码生成方式       
 public function getPhoneCode() { 
                $max = 9; 
                $y1 = rand(0, $max); 
                $y2 = rand(0, $max); 
                $y3 = rand(0, $max); 
                $y4 = rand(0, $max); 
                return $y4.$y3.$y2.$y1; 
}       
         //验证手机号是否正确
 public function isMobile($string){ 
        return !!preg_match('/^1[3|4|5|7|8]\d{9}$/', $string);
 }
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值