Browse Source

refactor(sixshop-aliyun-idcard): 重构代码并优化错误处理

- 为 Config 类添加属性注释,提高代码可读性
- 重命名 getAppCode 方法为 getExtensionID,增强方法命名的可读性和准确性- 在 Extension 类中定义 EXTENSION_ID 常量,统一扩展 ID 的定义和使用
-优化 IDCardClient 类中的错误处理逻辑,提高错误信息的准确性和友好性
- 使用 app_code配置项替代 getAppCode 方法,简化配置项的获取方式
runphp 6 months ago
parent
commit
6b9d341c6b
3 changed files with 18 additions and 4 deletions
  1. 7 2
      src/Config.php
  2. 2 0
      src/Extension.php
  3. 9 2
      src/IDCardClient.php

+ 7 - 2
src/Config.php

@@ -5,12 +5,17 @@ namespace SixShop\AliyunIDCard;
 
 use SixShop\System\Trait\ConfigTrait;
 
+/**
+ * @property string $app_key
+ * @property string $app_secret
+ * @property string $app_code
+ */
 class Config
 {
     use ConfigTrait;
 
-    public function getAppCode(): string
+    public function getExtensionID(): string
     {
-        return $this->getConfig('app_code');
+        return Extension::EXTENSION_ID;
     }
 }

+ 2 - 0
src/Extension.php

@@ -7,6 +7,8 @@ use SixShop\Core\ExtensionAbstract;
 
 class Extension extends ExtensionAbstract
 {
+    public const string EXTENSION_ID = 'aliyun_idcard';
+
     protected function getBaseDir(): string
     {
         return dirname(__DIR__);

+ 9 - 2
src/IDCardClient.php

@@ -4,6 +4,7 @@ namespace SixShop\AliyunIDCard;
 
 use Symfony\Component\HttpClient\HttpClient;
 use Symfony\Contracts\HttpClient\HttpClientInterface;
+use function SixShop\Core\throw_logic_exception;
 
 class IDCardClient
 {
@@ -12,12 +13,18 @@ class IDCardClient
 
     private HttpClientInterface $httpClient;
 
+    private array $errorMesageMap = [
+        '5' => '身份证和姓名不匹配',
+        '14' => '无此身份证号码',
+        '96' => '验证失败,请稍后重试',
+    ];
+
     public function __construct(private Config $config)
     {
         $this->httpClient = HttpClient::create([
             'base_uri' => self::GATEWAY,
             'headers' => [
-                'Authorization' => 'APPCODE ' . $this->config->getAppCode(),
+                'Authorization' => 'APPCODE ' . $this->config->app_code,
             ]
         ]);
     }
@@ -35,7 +42,7 @@ class IDCardClient
         if ($result['resp']['code'] == 0) {
             return $result['data'];
         } else {
-            throw_logic_exception($result['resp']['desc'], $result['resp']['code']);
+            throw new \RuntimeException($this->errorMesageMap[$result['resp']['code']] ?? $result['resp']['desc']);
         }
     }
 }