Sfoglia il codice sorgente

7-7验证码生成提取到类库中

Home 5 anni fa
parent
commit
9ed8fa3e15
3 ha cambiato i file con 41 aggiunte e 4 eliminazioni
  1. 1 1
      app/api/controller/Sms.php
  2. 4 3
      app/common/business/Sms.php
  3. 36 0
      app/common/lib/Num.php

+ 1 - 1
app/api/controller/Sms.php

@@ -31,7 +31,7 @@ class Sms extends BaseController
         }
 
         // 调用business层
-        if (SmsBus::sendCode($phoneNumber)) {
+        if (SmsBus::sendCode($phoneNumber, 6)) {
             return show(config('status.success'), '发送验证码成功');
         }
         return show(config('status.success'), '发送验证码失败');

+ 4 - 3
app/common/business/Sms.php

@@ -11,20 +11,21 @@ namespace app\common\business;
 
 
 use AlibabaCloud\Client\Exception\ClientException;
+use app\common\lib\Num;
 use app\common\lib\sms\AliSms;
 
 class Sms
 {
-    public static function sendCode(string $phoneNumber): bool
+    public static function sendCode(string $phoneNumber, int $len): bool
     {
         // 生成短信验证码
-        $code = random_int(100000, 999999);
+        $code = Num::getCode($len);
         $sms = AliSms::sendCode($phoneNumber, $code);
         if ($sms) {
             // 将验证码记录到redis,并设置失效时间
             // 检查php环境是否有redis拓展
             // redis服务
-            cache(config('redis.code_pre').$phoneNumber,$code,config('redis.expire'));
+            cache(config('redis.code_pre') . $phoneNumber, $code, config('redis.expire'));
         }
         return true;
     }

+ 36 - 0
app/common/lib/Num.php

@@ -0,0 +1,36 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/1/14 0:08
+ */
+
+declare(strict_types=1);
+
+namespace app\common\lib;
+
+/**
+ * 记录和数字相关的类库中的方法
+ * Class Num
+ * @package app\common\lib
+ */
+class Num
+{
+    /**
+     * 生成随机验证码
+     * @param int $len 4位或者6位
+     * @return int
+     * @throws \Exception
+     */
+    public static function getCode(int $len = 4): int
+    {
+        $code = random_int(1000, 9999);
+        if ($len === 6) {
+            $code = random_int(100000, 999999);
+        }
+
+        return $code;
+    }
+}