Commit 28669e4a by 王召彬

手机验证码 工具类

parent b8d02185
<?php <?php
namespace Hdll\Services\Common\Lib; namespace Hdll\Services\Common\Lib;
use Flc\Dysms\Client; use Swoft\App;
use Flc\Dysms\Request\SendSms; 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 Smscode class Smscode
{ {
protected $storeId; protected $sellerId;
public function __construct()
{
$this->sellerId = 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(10000, 99999);
$alisms = new Alisms(
$signName ?? Alisms::SN_01,
$templateCode ?? Alisms::TPL_01,
['code' => $vcode]
);
$response = $alisms->send($mobile);
if ($response->Code == 'OK') {
$vdata = sprintf("%d,%d,%d", $vcode, time(), $count);
$result = cache()->set($key, $vdata, 300); // 验证码有效期5分钟
if (!$result) {
return '验证码存储失败';
}
} else {
return '验证码发送失败:' . $response->Message;
}
}
/**
* 校验验证码
*
* @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->sellerId . '|' . $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