123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- <?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;
- }
- }
- }
|