Commit b3f9579a by 王召彬

腾讯短信发送验证码

parent 369fa719
......@@ -9,7 +9,8 @@
],
"require": {
"qcloud/cos-sdk-v5": "^2.0",
"catfan/medoo": "^1.6"
"catfan/medoo": "^1.6",
"qcloudsms/qcloudsms_php": "0.1.*"
},
"autoload": {
"psr-4": {
......
......@@ -5,7 +5,7 @@ use Swoft\App;
use Hdll\Services\Common\Entity\User;
/**
* 手机验证码 工具类
* (阿里短信)手机验证码 工具类
* 发送验证码:
* $err = (new Smscode)->send($mobile); // $mobile 接收验证码的手机号
* if($err) {
......
<?php
namespace Hdll\Services\Common\Lib;
use Swoft\App;
use Hdll\Services\Common\Entity\User;
/**
* (腾讯短信)手机验证码 工具类
* 发送验证码:
* $err = (new Smscode)->send($mobile); // $mobile 接收验证码的手机号
* if($err) {
* throw .... // 错误处理
* }
* 校验验证码:
* $check = (new Smscode)->check($mobile,$smscode); // 前台传入的手机号和验证码
* if(!$check) {
* throw .... // 错误处理
* }
*
*/
class TencSmscode
{
protected $uid;
public function __construct($uid = null)
{
if($uid !== null) {
$this->uid = $uid;
} else {
$this->uid = App::getBean(User::class)->getId();
}
}
/**
* 发送验证码,可指定短信签名和使用哪个短信模块
*
* @param integer $mobile
* @param [type] $signName
* @param [type] $templateCode
* @return null|string 返回错误信息,正确时返回null
*/
public function send(int $mobile, $signName = null, $templateCode = null)
{
$key = $this->getKey($mobile);
$val = cache()->get($key);
if ($val) {
list(, $time, $count) = explode(',', $val);
if ($count >= 3) {
return '验证码发送次数超限,请稍后再试';
}
if (time() - $time < 60) {
return '发送验证码请求过于频繁';
}
$count += 1;
} else {
$count = 1;
}
$vcode = mt_rand(1000, 9999);
}
/**
* 校验验证码
*
* @param integer $mobile
* @param integer $smscode
* @return bool 验证码正确时返回true
*/
public function check(int $mobile, int $smscode)
{
$key = $this->getKey($mobile);
$val = cache()->get($key);
if ($val) {
list($vcode,, ) = explode(',', $val);
if ($vcode == $smscode) {
return true;
}
}
return false;
}
private function getKey($mobile)
{
return 'smscode:' . md5($this->uid . '|' . $mobile);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment