Laravel对接ApiMedic的TokenGenerator集成实现问询
实现ApiMedic动态Token生成与集成方案
1. 创建TokenGenerator类
在app/Services/ApiMedic目录下创建TokenGenerator.php(目录不存在则自行创建),实现Token的获取与缓存逻辑:
<?php namespace App\Services\ApiMedic; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Config; class TokenGenerator { protected $apiUrl; protected $userId; protected $apiKey; public function __construct() { $this->apiUrl = Config::get('services.apimedic.token_url', 'https://sandbox-healthservice.priaid.ch/login'); $this->userId = Config::get('services.apimedic.user_id'); $this->apiKey = Config::get('services.apimedic.api_key'); } public function getValidToken() { // 检查缓存是否存在有效Token $cachedToken = Cache::get('apimedic_token'); $validThrough = Cache::get('apimedic_token_valid_through'); if ($cachedToken && $validThrough && now()->timestamp < $validThrough) { return $cachedToken; } // 请求新Token $response = Http::asForm()->post($this->apiUrl, [ 'userId' => $this->userId, 'apiKey' => $this->apiKey, ]); if (!$response->successful()) { throw new \Exception('获取ApiMedic Token失败: ' . $response->body()); } $tokenData = $response->json(); $token = $tokenData['Token']; $validThrough = strtotime($tokenData['ValidThrough']); // 缓存Token,提前1分钟过期避免请求时Token失效 $cacheDuration = $validThrough - now()->timestamp - 60; Cache::put('apimedic_token', $token, $cacheDuration); Cache::put('apimedic_token_valid_through', $validThrough, $cacheDuration); return $token; } }
2. 配置.env与服务参数
确保.env中已配置密钥:
APIMEDIC_USER_ID=你的用户ID APIMEDIC_API_KEY=你的API密钥 APIMEDIC_BASE_URL=https://sandbox-healthservice.priaid.ch/
在config/services.php中添加统一配置项:
'apimedic' => [ 'user_id' => env('APIMEDIC_USER_ID'), 'api_key' => env('APIMEDIC_API_KEY'), 'base_url' => env('APIMEDIC_BASE_URL', 'https://sandbox-healthservice.priaid.ch/'), 'token_url' => env('APIMEDIC_TOKEN_URL', 'https://sandbox-healthservice.priaid.ch/login'), ],
3. 集成到DiagnosisClient
修改现有DiagnosisClient,注入TokenGenerator并自动携带有效Token:
<?php namespace App\Services\ApiMedic; use Illuminate\Support\Facades\Http; class DiagnosisClient { protected $baseUrl; protected $tokenGenerator; public function __construct(TokenGenerator $tokenGenerator) { $this->baseUrl = config('services.apimedic.base_url'); $this->tokenGenerator = $tokenGenerator; } public function getDiagnosis(array $params) { $token = $this->tokenGenerator->getValidToken(); return Http::withHeaders([ 'Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json', ])->get($this->baseUrl . 'diagnosis', $params); } // 其他接口方法(如症状查询)按相同逻辑添加Token请求头 }
4. 在ApiMedicService中使用
保持原有ApiMedicService的依赖注入逻辑,Laravel容器会自动解析TokenGenerator:
<?php namespace App\Services; use App\Services\ApiMedic\DiagnosisClient; class ApiMedicService { protected $diagnosisClient; public function __construct(DiagnosisClient $diagnosisClient) { $this->diagnosisClient = $diagnosisClient; } public function getPatientDiagnosis($symptoms, $gender, $yearOfBirth) { $response = $this->diagnosisClient->getDiagnosis([ 'symptoms' => json_encode($symptoms), 'gender' => $gender, 'yearOfBirth' => $yearOfBirth, 'language' => 'en-gb', // 根据需求调整语言 ]); if (!$response->successful()) { throw new \Exception('诊断请求失败: ' . $response->body()); } return $response->json(); } }
关键说明
- 缓存策略:提前1分钟让Token过期,避免请求过程中Token刚好失效
- 异常处理:添加基础异常抛出,可根据项目需求自定义异常类或错误处理逻辑
- 依赖注入:利用Laravel容器自动解析依赖,无需手动实例化类
内容的提问来源于stack exchange,提问作者tukitooo1998
相关产品推荐
相关产品推荐

