diff --git a/config/sms.php b/config/sms.php index d0608ee..a16b4f2 100644 --- a/config/sms.php +++ b/config/sms.php @@ -176,4 +176,8 @@ 'app_id' => env('SMS_YUNZHIXUN_APP_ID'), ], ], + 'verification' => [ + 'prefix' => 'sms_code_', + 'length' => 5, + ], ]; diff --git a/src/VerificationCodeManager.php b/src/VerificationCodeManager.php new file mode 100644 index 0000000..2e03307 --- /dev/null +++ b/src/VerificationCodeManager.php @@ -0,0 +1,41 @@ +cacheManager = $cacheManager; + } + + protected function getPrefixedKey($number) + { + return config('sms.verification.prefix') . $number; + } + + public function verify($number, $code) + { + return $code === $this->cacheManager->get($this->getPrefixedKey($number)); + } + + public function issue($number) + { + $length = config('sms.verification.length'); + $code = random_int(10 ** ($length - 1), (10 ** $length) - 1); + $this->cacheManager->set($this->getPrefixedKey($number), $code, 600); + + return $code; + } +} diff --git a/tests/VerificationCodeManagerTest.php b/tests/VerificationCodeManagerTest.php new file mode 100644 index 0000000..4941a86 --- /dev/null +++ b/tests/VerificationCodeManagerTest.php @@ -0,0 +1,36 @@ +manager = app(VerificationCodeManager::class); + } + + public function testIssue(): void + { + $code = $this->manager->issue('18888888888'); + self::assertSame(config('sms.verification.length'), strlen((string) $code)); + } + + public function testVerify(): void + { + $code = $this->manager->issue(new SmsNumber('18888888888')); + self::assertTrue($this->manager->verify(new SmsNumber('18888888888'), $code)); + } +}