135 lines
3.4 KiB
PHP
135 lines
3.4 KiB
PHP
<?php
|
|
namespace app\common\service;
|
|
|
|
use think\Cache;
|
|
use think\Exception;
|
|
use app\common\traits\ServiceTrait;
|
|
|
|
class SmsService
|
|
{
|
|
use ServiceTrait;
|
|
|
|
/**
|
|
* 验证码有效期(秒)
|
|
*/
|
|
const CODE_EXPIRE = 300;
|
|
|
|
/**
|
|
* 发送间隔时间(秒)
|
|
*/
|
|
const SEND_INTERVAL = 60;
|
|
|
|
/**
|
|
* 生成验证码
|
|
* @return string
|
|
*/
|
|
protected function generateCode(): string
|
|
{
|
|
return sprintf("%06d", random_int(0, 999999));
|
|
}
|
|
|
|
/**
|
|
* 获取缓存key
|
|
* @param string $mobile
|
|
* @param string $type
|
|
* @return string
|
|
*/
|
|
protected function getCacheKey(string $mobile, string $type = 'code'): string
|
|
{
|
|
return "sms_{$type}_{$mobile}";
|
|
}
|
|
|
|
/**
|
|
* 发送验证码
|
|
* @param string $mobile 手机号
|
|
* @return array
|
|
* @throws Exception
|
|
*/
|
|
public function send($mobile, $code = null, $event = 'default'): array
|
|
{
|
|
// 检查发送间隔
|
|
$intervalKey = $this->getCacheKey($mobile, 'interval');
|
|
if (Cache::get($intervalKey)) {
|
|
throw new Exception('发送太频繁,请稍后再试');
|
|
}
|
|
try {
|
|
// 这里调用具体的短信发送接口
|
|
$result = $this->sendSms($mobile, $code);
|
|
|
|
if (!$result) {
|
|
throw new Exception('短信发送失败');
|
|
}
|
|
|
|
// 缓存验证码
|
|
$codeKey = $this->getCacheKey($mobile);
|
|
Cache::set($codeKey, $code, self::CODE_EXPIRE);
|
|
|
|
// 设置发送间隔
|
|
Cache::set($intervalKey, 1, self::SEND_INTERVAL);
|
|
|
|
return [
|
|
'mobile' => $mobile,
|
|
'expire' => self::CODE_EXPIRE
|
|
];
|
|
} catch (\Exception $e) {
|
|
throw new Exception('短信发送失败:' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 验证码验证
|
|
* @param string $mobile
|
|
* @param string $code
|
|
* @return bool
|
|
* @throws Exception
|
|
*/
|
|
public function check(string $mobile, string $code): bool
|
|
{
|
|
if (empty($mobile) || empty($code)) {
|
|
throw new Exception('手机号和验证码不能为空');
|
|
}
|
|
|
|
$codeKey = $this->getCacheKey($mobile);
|
|
$cacheCode = Cache::get($codeKey);
|
|
|
|
if (!$cacheCode) {
|
|
throw new Exception('验证码已过期');
|
|
}
|
|
|
|
if ($cacheCode !== $code) {
|
|
throw new Exception('验证码错误');
|
|
}
|
|
|
|
// 验证成功后删除缓存
|
|
Cache::rm($codeKey);
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 发送短信
|
|
* @param string $mobile
|
|
* @param string $code
|
|
* @return bool
|
|
*/
|
|
protected function sendSms(string $mobile, string $code): bool
|
|
{
|
|
// 这里实现具体的短信发送逻辑
|
|
// 可以对接阿里云、腾讯云等短信服务
|
|
// 示例使用阿里云短信服务
|
|
try {
|
|
$config = [
|
|
'access_key_id' => config('site.sms.access_key_id'),
|
|
'access_key_secret' => config('site.sms.access_key_secret'),
|
|
'sign_name' => config('site.sms.sign_name'),
|
|
'template_code' => config('site.sms.template_code')
|
|
];
|
|
|
|
// 测试环境直接返回true
|
|
return true;
|
|
} catch (\Exception $e) {
|
|
// 记录日志
|
|
\think\Log::error('短信发送失败:' . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
}
|