This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,12 @@
<?php
namespace Stemcell\Customer\Helper\Deepblue;
interface Caller
{
function getAppKey():string;
function getAppSecret():string;
function getHost():string;
}
@@ -0,0 +1,293 @@
<?php
namespace Stemcell\Customer\Helper\Deepblue;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Exception\LocalizedException;
use Stemcell\Customer\Api\Data\AvatrInterface;
use Stemcell\Customer\Helper\CarSeriesClueInterface;
use phpseclib3\Crypt\RSA\PublicKey;
use phpseclib3\Crypt\PublicKeyLoader;
class CluePost extends \Magento\Framework\App\Helper\AbstractHelper implements Caller, CarSeriesClueInterface
{
/**
* config must contains follow data:app_key, app_secret, host:请求地址, pubKey:RSA public key
*
* @var array
*/
private array $config = [
'host' => 'https://clue.changan.com.cn:5786',
'app_key' => '2e0a1703b9784ca89e9368e21a119b4c',
'app_secret' => 'a6049e8b647ae0339111b39ffaf1cab0',
'pubKey' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArJiVab+4lEatCcpLQHef8+MyjcSKmOLqcGPb+ObtwvLxbyRQ/eM2AO3mDAPFZddYhl/hSeLBsWIt1vY4WKUtkmm5mRRLkFQuLj0FRhRKxHBstKNXd0MX+ekz4Jx2FaulleRfJ7PbGpCZJNDzMmZHuRng0g+1g2Avk1B5NQ9dSn3SzRbHXAiY8aCkyUs3i8Hb/nMq2ivj9AJjgsc3LcltKLG/Lnlvr2b17WLKNjPxdyj112+xR0CA99/hBZo2cxDfjUIhDjBo9pcCRzA3AnFOnRQ44fjjcDwwoMhvpgnbt7D+5ek4wDzgnL4hai3naCIfzlnYQSVlCII/NUURs9WjZwIDAQAB',
];
private Token $tokenHelper;
private array $requestData = [];
/**
* RSA public key
* @var string
*/
private string $pubKey = '';
private \Magento\Framework\HTTP\Client\Curl $curl;
private string $response;
private AvatrInterface $clue;
private Transformers $transformers;
private string $distributorCode;
private string $carSeries;
/**
* @var string
*/
private string $line;
public function __construct(
Context $context,
Token $tokenHelper,
\Magento\Framework\HTTP\Client\Curl $curl,
Transformers $transformers
) {
parent::__construct($context);
$this->tokenHelper = $tokenHelper;
$this->curl = $curl;
$this->transformers = $transformers;
$this->tokenHelper->setCaller($this);
}
/**
* @throws LocalizedException
*/
public function getHost(): string
{
return $this->_getData('host');
}
public function setConfig(array $config = []): static
{
$this->config = array_merge($this->config, $config);
return $this;
}
/**
* @throws LocalizedException
*/
function _getData(string $key): string
{
if (isset($this->config[$key]) && !empty($this->config[$key])) {
return $this->config[$key];
}
throw new LocalizedException(__($key.' is not set'));
}
/**
* @throws LocalizedException
*/
function getAppSecret(): string
{
return $this->_getData('app_secret');
}
/**
* @throws LocalizedException
*/
function getAppKey(): string
{
return $this->_getData('app_key');
}
/**
* get RSA public key
* @return string
* @throws LocalizedException
*/
protected function getPubKey(): string
{
return "-----BEGIN PUBLIC KEY-----\n" .
wordwrap(
$this->_getData('pubKey'),
64,
"\n",
true
) . "\n-----END PUBLIC KEY-----";
}
/**
* data must contains follow data:
* customerPhoneNo: 客户电话
* outwardOriginId: 线索生成系统的原始id
* city: 客户城市编码(国标) https://github.com/modood/Administrative-divisions-of-China/tree/master/dist
*
* @param array $data
* @return $this
*/
public function setRequestData(array $data): static
{
$info = [
'brand' => '80081004',
'leaveInfoTime' => date('Y-m-d H:i:s'),
'sourceCd' => '0201700260000'
];
if ($this->line=='启源') {
$info['brand'] = '80081005';
$info['sourceCd'] = '0200300140010';
}
$this->requestData = array_merge($info, $data);
return $this;
}
/**
* @return array
*/
public function getRequestData(): array
{
if (!empty($this->requestData)) {
return $this->requestData;
}
$leadsCreateTime = $this->clue->getCreatedAt();
if (!$leadsCreateTime) {
$leadsCreateTime = date('Y-m-d H:i:s');
}
$this->requestData = [
'brand' => '80081004',
'leaveInfoTime' => $leadsCreateTime,
'sourceCd' => '0201700260000',
'customerName' => $this->clue->getName(),
'customerPhoneNo' => $this->clue->getTelephone(),
'outwardOriginId' => 'bbycm-'.str_pad($this->clue->getId(), 12, '0', STR_PAD_LEFT),
'city' => $this->clue->getCityId(),
'province' => $this->clue->getProvinceId(),
'intentionCarSeries' => $this->carSeries,
];
if (is_numeric($this->distributorCode)) {
$this->requestData['distributorId'] = $this->distributorCode;
} else {
$this->requestData['distributorCode'] = $this->distributorCode;
}
if ($this->line=='启源') {
$this->requestData['brand'] = '80081005';
$this->requestData['sourceCd'] = '0200300140010';
$this->requestData['marketingActivityName'] = '重庆福戈文化传播有限公司';
$this->requestData['marketingActivityNo'] = '2024mtjjrcqfg';
}
return $this->requestData;
}
/**
* @throws LocalizedException
*/
protected function sign(): string
{
return base64_encode($this->publicEncrypt(json_encode($this->requestData)));
}
protected function publicEncrypt(string $data)
{
if (!is_string($data)) {
return null;
}
$dataLength = mb_strlen($data);
$offet = 0;
$length = 128;
$i = 0;
$string = '';
while ($dataLength - $offet > 0) {
if ($dataLength - $offet > $length) {
$str = mb_substr($data, $offet, $length);
} else {
$str = mb_substr($data, $offet, $dataLength - $offet);
}
$encrypted = '';
openssl_public_encrypt($str,$encrypted, $this->getPubKey());
$string .= $encrypted;
$i ++;
$offet = $i * $length;
}
return base64_encode($string);
}
/**
* @throws LocalizedException
*/
protected function getRequestUrl(): string
{
return rtrim($this->getHost(), "/") . '/api/interface/commonClue/createClue';
}
/**
* @return Token
*/
public function getTokenHelper(): Token
{
return $this->tokenHelper;
}
/**
* @throws LocalizedException
*/
public function post(): self
{
$body = json_encode([array_merge($this->getRequestData(), ['data'=>$this->sign()])]);
$token = $this->tokenHelper->getToken();
$this->curl->addHeader("Content-Type", "application/json");
$this->curl->addHeader('token', $token);
$this->curl->addHeader('isEncipher', false);
$this->curl->post( $this->getRequestUrl(), $body);
$this->response = $this->curl->getBody();
return $this;
}
/**
* @throws LocalizedException
*/
public function transform(array $from): array
{
$this->distributorCode = $from[5];
$this->line = $from[2];
if(!$carSeries = $this->transformers->getCarSeriesCode(trim($from[6]))){
$carSeries = $this->transformers->getCarSeriesCode(trim($from[2]).trim($from[6]));
if(!$carSeries) {
throw new \Exception('车系:'.$from[6].'不存在');
}
}
$this->carSeries = $carSeries;
return $this->transformers->transform($from);
}
public function setClue(AvatrInterface $clue): CarSeriesClueInterface
{
$this->clue = $clue;
return $this;
}
public function isSuccess(): bool
{
$response = $this->getResponse();
return isset($response['code']) && $response['code']==200 && $response['total'] > 0;
}
public function getResponse(): array
{
$response = json_decode($this->response, true);
return is_array($response)? $response:[];
}
public function reset(): CarSeriesClueInterface
{
$this->requestData = [];
return $this;
}
}
@@ -0,0 +1,115 @@
<?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'];
}
}
@@ -0,0 +1,128 @@
<?php
namespace Stemcell\Customer\Helper\Deepblue;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Module\Dir as ModuleDir;
use Stemcell\Customer\Helper\TransformersInterface;
/**
* transform original province and city name to Avatr require id
*/
class Transformers implements TransformersInterface
{
private ModuleDir $moduleDir;
protected array $data = [];
protected array $regions = [];
public function __construct(
ModuleDir $moduleDir
) {
$this->moduleDir = $moduleDir;
}
/**
* @param string $path a relative path to $module, must begin with /
* @param string $module
* @return array
* @throws LocalizedException
*/
protected function loadDataFromFile(string $path, string $module='Stemcell_Customer') : array
{
if (isset($this->data[$path]) && !empty($this->data[$path])) {
return $this->data[$path];
}
$file = $this->moduleDir->getDir($module).$path;
if (!file_exists($file)) {
throw new LocalizedException(__("$file not exist"));
}
$data = json_decode(file_get_contents($file), true);
if (!$data) {
throw new LocalizedException(__("$file content is not json"));
}
return $this->data[$path] = $data;
}
protected function chineseEncoding(string $str) : string
{
// return mb_convert_encoding($str, 'UTF-8', ['gb2312', 'gbk']);
return $str;
}
/**
* @param array $row original row data
* @return array data order by ['name', 'telephone', 'favorite_vehicle', 'province_id', 'city_id']
* @throws LocalizedException
*/
public function transform(array $row): array
{
$region = $this->getRegionId($row[3], $row[4]);
// $row[2] = $this->chineseEncoding($row[2]);
return [$row[0], $row[1], $this->getCarModelId($row[2]), $region[0], $region[1]];
}
/**
* @throws LocalizedException
*/
public function getRegionId(string $province, string $city)
{
$city = str_replace(' ', '', $city);
// $city = $this->chineseEncoding($city);
// $province = $this->chineseEncoding($province);
if (isset($this->regions[$city])) {
return $this->regions[$city];
}
if (mb_strlen($city) < 2) {
throw new LocalizedException(__("invalid city name: ".$city));
}
$regions = $this->loadDataFromFile('/data/pc-code.json');
foreach ($regions as $item) {
if (mb_strpos($item['name'], $province) === 0 ) {
foreach ($item['children'] as $child) {
if (mb_strpos($child['name'], $city) === 0 ) {
return $this->regions[$city] = [
str_pad($item['code'], 6, '0'),
str_pad($child['code'], 6, '0')
];
}
}
}
}
return [null, null];
}
/**
* @throws LocalizedException
*/
public function getCarModelId(string $carModel)
{
$carModel = str_replace(' ', '', $carModel);
// $carModel = $this->chineseEncoding($carModel);
$carModels = $this->loadDataFromFile('/data/car-models.json');
return $carModels[$carModel] ?? null;
}
/**
* @param string $series
* @return string | null
* @throws LocalizedException
*/
public function getCarSeriesCode(string $series): ?string
{
$series = str_replace(' ', '', $series);
// $series = $this->chineseEncoding($series);
// var_dump($series);
// echo '<br/><br/><br/>';
$data = $this->loadDataFromFile('/data/car-series.json');
// var_dump($data[$series]);
// echo '<br/><br/><br/>';
return $data[$series] ?? null;
}
}