You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.5 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Constants\v3\ErrorCode;
  4. use App\Constants\v3\SsdbKeys;
  5. use App\Exception\BusinessException;
  6. use App\Exception\ErrorCodeException;
  7. use App\Service\v3\Interfaces\HelperServiceInterface;
  8. use App\Service\v3\Interfaces\SmsSendServiceInterface;
  9. use App\Service\v3\Interfaces\VerifyCodeServiceInterface;
  10. use App\TaskWorker\SSDBTask;
  11. use Hyperf\Utils\ApplicationContext;
  12. use Hyperf\Di\Annotation\Inject;
  13. class VerifyCodeService implements VerifyCodeServiceInterface
  14. {
  15. /**
  16. * @Inject
  17. * @var SmsSendServiceInterface
  18. */
  19. protected $smsService;
  20. /**
  21. * @Inject
  22. * @var HelperServiceInterface
  23. */
  24. protected $helperService;
  25. public function do($userId, $tel)
  26. {
  27. // 获取验证码
  28. $verifyCode = $this->helperService->makeNumCode(6);
  29. // 存到SSDB
  30. $ssdbClient = ApplicationContext::getContainer()->get(SSDBTask::class);
  31. $setRes = $ssdbClient->exec(
  32. "setnx",
  33. SsdbKeys::VERIFY_CODE.$userId.'_'.$tel,
  34. $verifyCode
  35. );
  36. // if (!$setRes) {
  37. // throw new ErrorCodeException(ErrorCode::VERIFY_CODE_SENDED);
  38. // }
  39. $expireRes = $ssdbClient->exec(
  40. 'expire',
  41. SsdbKeys::VERIFY_CODE.$userId.'_'.$tel,
  42. 600
  43. );
  44. if (!$expireRes) {
  45. throw new ErrorCodeException(ErrorCode::VERIFY_CODE_ERROR, '', ['message' => '验证码有效期设置失败', 'data' => ['ssdbkey' => SsdbKeys::VERIFY_CODE.$userId.'_'.$tel]]);
  46. }
  47. // 发送短信
  48. $smsRes = $this->smsService->doVerifyCode($tel, $verifyCode);
  49. if (!$smsRes) {
  50. throw new ErrorCodeException(ErrorCode::VERIFY_CODE_ERROR);
  51. }
  52. return true;
  53. }
  54. public function check($userId, $tel, $verifyCode)
  55. {
  56. // 获取验证码并验证
  57. $ssdbClient = ApplicationContext::getContainer()->get(SSDBTask::class);
  58. $code = $ssdbClient->exec(
  59. "get",
  60. SsdbKeys::VERIFY_CODE.$userId.'_'.$tel
  61. );
  62. if (empty($code) || $verifyCode!=$code) {
  63. throw new ErrorCodeException(ErrorCode::INVALID_VERIFY_CODE);
  64. }
  65. $this->undo($userId, $tel);
  66. return true;
  67. }
  68. public function undo($userId, $tel)
  69. {
  70. $ssdbClient = ApplicationContext::getContainer()->get(SSDBTask::class);
  71. return $ssdbClient->exec(
  72. 'del',
  73. SsdbKeys::VERIFY_CODE.$userId.'_'.$tel
  74. );
  75. }
  76. }