123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- <?php
- /**
- * @Name
- * @Description
- * @Author 刘学玺
- * @Date 2024/3/25 11:38
- */
- namespace App\Http\Services\Frontend\Client\Common;
- use App\Exceptions\ApiException;
- use App\Http\Services\Service;
- use App\Models\Member\User;
- class SmsService extends Service
- {
- /**
- * Notes :
- * Method : Interface send
- * @param $mobile
- * @param int $category 0-注册 1-登录 2-忽略类型
- * @throws ApiException
- */
- public function send($mobile, int $category = 0): void
- {
- $where = ['mobile' => $mobile];
- $exists = User::query()->where($where)->exists();
- $category === 1 && !$exists && self::error('用户不存在!',404);
- $category === 0 && $exists && self::error('用户已存在!', 409);
- // 检测短信发送间隔
- // 生成验证码
- $code = 123456;
- // 发送短信
- // 判断发送结果
- // 缓存验证码
- $this->save($mobile, $code);
- }
- /**
- * Notes :
- * Method : 验证手机验证码并清除缓存
- * @param $mobile
- * @param $code
- * @return bool
- */
- public function verifyCode($mobile, $code): bool
- {
- $correctCode = cache('mobile_verification_code_' . $mobile);
- $isValid = $correctCode === $code;
- $isValid && cache(['mobile_verification_code_' . $mobile => 0], 0);
- return $isValid;
- }
- /**
- * Notes :
- * Method : 使用缓存保存手机验证码
- * @param $mobile
- * @param $code
- */
- protected function save($mobile, $code): void
- {
- $sms_expires_time = env('SMS_EXPIRES_TIME', 10);
- $expiresAt = now()->addMinutes(floatval($sms_expires_time)); // 设置验证码有效期为10分钟
- cache(['mobile_verification_code_' . $mobile => $code], $expiresAt);
- }
- }
|