Files
2026-09-15 10:26:34 +08:00

116 lines
3.0 KiB
PHP

<?php
namespace Stemcell\Customer\Helper\Deepblue;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Exception\LocalizedException;
class Token extends \Magento\Framework\App\Helper\AbstractHelper
{
const DEEPBLUE_TOKEN_IDENTIFIER = 'DEEPBLUE-TOKEN-IDENTIFIER-';
protected \Magento\Framework\HTTP\Client\Curl $curl;
protected Caller $caller;
private int $timestamp = 0;
private \Magento\Framework\App\CacheInterface $cache;
public function __construct(
Context $context,
\Magento\Framework\HTTP\Client\Curl $curl,
\Magento\Framework\App\CacheInterface $cache
) {
parent::__construct($context);
$this->curl = $curl;
$this->cache = $cache;
}
public function setCaller(Caller $caller): static
{
$this->caller = $caller;
return $this;
}
protected function getTimestamp(): int
{
if (!$this->timestamp) {
return $this->timestamp = round(microtime(true) * 1000);
}
return $this->timestamp;
}
protected function sign(): string
{
return md5(
$this->caller->getAppKey() . $this->getTimestamp() . $this->caller->getAppSecret()
);
}
protected function getRequestData(): array
{
return [
'sign' => $this->sign(),
'appKey' => $this->caller->getAppKey(),
'timestamp' => $this->getTimestamp(),
];
}
protected function getRequestUrl(): string
{
return rtrim($this->caller->getHost(), "/") . '/api/auth/thirdPartyToken';
}
protected function post(): array
{
$body = json_encode($this->getRequestData());
$this->curl->addHeader("Content-Type", "application/json");
$this->curl->post( $this->getRequestUrl(), $body);
$body = json_decode($this->curl->getBody(), true);
return $body;
}
/**
* @return string
* @throws LocalizedException
*/
protected function tokenCache(): string
{
$lifeTime = 24*3600-60;
$token = $this->post();
if (isset($token['code']) && $token['code'] == 200) {
$cacheData = json_encode([
'token' => $token['data'],
'created_at' => time()
]);
$this->cache->save($cacheData, self::DEEPBLUE_TOKEN_IDENTIFIER, [], $lifeTime);
return $token['data'];
}
throw new LocalizedException(__('从/api/auth/thirdPartyToken获取token失败,原因:'.$token['msg'].', code:'.$token['code']));
}
/**
* @return string
* @throws LocalizedException
*/
public function getToken(): string
{
$token = $this->cache->load(self::DEEPBLUE_TOKEN_IDENTIFIER);
if (!$token) {
return $this->tokenCache();
}
$cacheData = json_decode($token, true);
if ((time() - $cacheData['created_at']) > 60) {
return $this->tokenCache();
}
return $cacheData['token'];
}
}