Compare commits

..

No commits in common. "dev" and "v1.0" have entirely different histories.
dev ... v1.0

5 changed files with 128 additions and 250 deletions

View File

@ -1 +1 @@
{"version":1,"defects":{"Feature\\OrderTest::testGetWeatherWithGuzzleRuntimeException":5,"Feature\\OrderTest::testGetWeatherWithInvalidType":3,"Feature\\OrderTest::testGetWeatherWithInvalidFormat":3,"Feature\\OrderTest::testGenerateSignature":3,"Feature\\OrderTest::testGetProductOrder":5},"times":{"Feature\\OrderTest::testGetWeatherWithInvalidType":0.319,"Feature\\OrderTest::testGetWeatherWithInvalidFormat":0.128,"Feature\\OrderTest::testGetWeatherWithGuzzleRuntimeException":1.562,"Feature\\OrderTest::testGetHttpClient":0.001,"Feature\\OrderTest::testSetGuzzleOptions":0.003,"Feature\\OrderTest::testGetProductOrder":0.11,"Feature\\OrderTest::testCreateProductOrder":1.468,"Feature\\OrderTest::testGenerateSignature":0.211}}
{"version":1,"defects":{"Feature\\OrderTest::testGetProductOrder":5},"times":{"Unit\\OrderTest::testGetWeatherWithInvalidType":0.041,"Feature\\OrderTest::testGetWeatherWithInvalidType":0.026,"Unit\\OrderTest::testGetWeatherWithInvalidFormat":0,"Feature\\OrderTest::testGetWeatherWithInvalidFormat":0,"Feature\\OrderTest::testGetWeatherWithGuzzleRuntimeException":0.074,"Feature\\OrderTest::testGetHttpClient":0.015,"Feature\\OrderTest::testSetGuzzleOptions":0.002,"Unit\\OrderTest::testGetWeatherWithGuzzleRuntimeException":0.101,"Unit\\OrderTest::testGetHttpClient":0.02,"Unit\\OrderTest::testSetGuzzleOptions":0.004,"Feature\\OrderTest::testGetProductOrder":0.202}}

View File

@ -1,11 +1,9 @@
# 德木自动化项目开放接口SDK
# 介绍
用于德木自动化对外开放接口数据交互
# 要求
- php版本>=7.0
# 安装
@ -17,94 +15,11 @@ composer require ykxiao/dmmes
# 使用
```php
// secretKey 必填
// callback url 选填业务逻辑需要时填写详情查看SDK文档
// options 选填(日志选项,默认写入日志)
$secretKey = 'gFBfirGATxafTeq74RAngaL74Ksdxhuy';
$options = [
'logger' => true,
'logs_path' => storage_path('logs/mes-sdk'),
];
$w = new Order($secretKey, 'callback url', $options);
$w = new Order($secretKey);
// 获取工单数据
$response = $w->getProductOrder(1);
// 加工工单原木材种
$w->getWoodTypeOptions([
'company_id' => 1
]);
// 加工工单加工等级
$w->getProductionLevelOptions([
'company_id' => 1
]);
// 创建加工工单
$response = $w->createProductOrder([
'company_id' => 1,
'wood_type_id' => 1,
'wood_level_id' => 1,
'spec_thickness' => 12,
'spec_width' => 22,
'spec_length' => 38,
'number_width' => 12,
'number_height' => 22,
'number_pcs' => 10,
'owner' => 'ykxiao'
]);
// 更新加工工单
$response = $w->updateProductOrder([
'id' => 1,
'company_id' => 1,
]);
// 撤回加工工单
$response = $w->revokeProductOrder([
'id' => 1
]);
```
# 回调说明
- 配置回调后地址后应用服务器会以POST方式请求你的服务器地址以便你做进一步业务流程。
- 回调你服务器地址后,可获取参数"data"、"signature"进行验签,"response" 为服务器处理结果。
```php
// 回调参数调用方法
$w = new Order($secretKey, 'callback url');
// 获取数据
$request = require();
$params = json_decode($request->contents(), true);
// 回调验签
$receivedSignature = $request->headers('mes-open-signature');
$timestamp = $request->headers('mes-open-timestamp');
$data = json_encode($params['data']);
/**
* 生成HMAC签名
* @param $data
* @return string
*/
function generateHmacSignature($data): string
{
$secretKey = 'YOUR_SECRET_KEY'; // 应用服务器密钥
return hash_hmac('sha256', $data, $secretKey);
}
$calculatedSignature = $this->generateHmacSignature($timestamp . $data);
// 验证签名是否匹配 hash_equals($receivedSignature, $calculatedSignature)
if ($receivedSignature === $calculatedSignature) {
return json_encode($data);
} else {
throw new Exception('数据签名验证失败!');
}
$response = $w->getProductOrder('SN5436745676543');
```

View File

@ -13,7 +13,6 @@
}
],
"require": {
"php": "^7.3|^8.0",
"guzzlehttp/guzzle": "^7.8",
"ext-json": "*"
},

View File

@ -10,124 +10,88 @@ namespace Ykxiao\Dmmes\OrderActions;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Ykxiao\Dmmes\Exceptions\Exception;
use Ykxiao\Dmmes\Exceptions\HttpException;
use Ykxiao\Dmmes\Exceptions\InvalidArgumentException;
use function in_array;
use function strtolower;
class Order
{
protected const API_URL = 'https://api.dev.dwoodauto.com/api/v3/';
protected const DEFAULT_FORMAT = 'json';
protected const DEFAULT_TYPE = 'base';
protected $guzzleOptions = [];
protected $httpClient;
protected $apiUrl = 'https://api.dev.dwoodauto.com/api/v3/';
protected $data = [];
protected $secretKey;
protected $callback;
protected $options = [];
/**
* @var string
*/
private $secretKey;
/**
* @var mixed|string
*/
private $type;
/**
* @var mixed|string
*/
private $format;
public function __construct($secretKey, $callback = '', $options = [])
public function __construct($secretKey, $type = 'base', $format = 'json')
{
$this->secretKey = $secretKey;
$this->httpClient = new Client($this->guzzleOptions);
$this->callback = $callback;
$this->options = $options;
$this->type = $type;
$this->format = $format;
}
public function getHttpClient(): Client
public function getHttpClient()
{
return $this->httpClient;
return new Client($this->guzzleOptions);
}
public function setGuzzleOptions(array $options)
{
$this->guzzleOptions = $options;
}
/**
* 请求参数签名
* @param $params
* @return string
*/
private function generateSignature($params): string
{
return (new Sign())->generateHmacSignature($this->secretKey, $params);
}
/**
* 日志
* @param array $logs
* @return void
* @throws Exception
*/
private function logger(array $logs)
{
$logFolder = './storage/logs/mes-sdk'; // 默认日志文件夹路径
$logFile = $logFolder . '/logs.log'; // 默认日志文件路径
// 如果有自定义日志路径,则使用自定义路径
if (!empty($this->options['logger']) && !empty($this->options['logs_path'])) {
$logFolder = $this->options['logs_path'];
$logFile = $logFolder . '/logs.log';
}
// 判断文件夹是否存在,如果不存在则创建文件夹
if (!is_dir($logFolder)) {
if (!mkdir($logFolder, 0777, true)) {
throw new Exception("Failed to create log folder: $logFolder");
}
}
$timestamp = date('Y-m-d H:i:s');
$logContent = "[$timestamp] " . json_encode($logs, JSON_UNESCAPED_UNICODE) . PHP_EOL;
// 打开日志文件并追加内容
if (file_put_contents($logFile, $logContent, FILE_APPEND) === false) {
throw new Exception("Failed to write to log file: $logFile");
}
}
/**
* 接口请求
* @param $api
* @param $data
* @return mixed|string
* @throws \Exception|GuzzleException
* @throws GuzzleException
* @throws HttpException
* @throws InvalidArgumentException
*/
private function sendRequest($api, $data)
public function baseFun($params)
{
$url = self::API_URL . $api;
$url = $this->apiUrl . 'production.status';
// 附加参数
$params = array_merge([
'times' => time(),
'output' => self::DEFAULT_FORMAT,
'extensions' => self::DEFAULT_TYPE,
], $data);
$signature = $this->generateSignature($params);
// 请求参数
$body = [
'signature' => $signature,
'data' => $params
];
if ($this->callback != '') {
$body = array_merge(['callback' => $this->callback], $body);
if (!in_array(strtolower($this->format), ['xml', 'json'])) {
throw new InvalidArgumentException('Invalid response format: ' . $this->format);
}
if (!in_array(strtolower($this->type), ['base', 'all'])) {
throw new InvalidArgumentException('Invalid type value(base/all): ' . $this->type);
}
$params['output'] = $this->format;
$params['extensions'] = $this->type;
$signature = (new Sign())->generateHmacSignature($this->secretKey, $params);
$params = [
'headers' => ['content-type' => 'application/json', 'accept' => 'application/json', 'user-agent' => 'mes sdk'],
'body' => json_encode($body),
'headers' => ['content-type' => 'application/json', 'accept' => 'application/json'],
'body' => json_encode([
'signature' => $signature,
'data' => $params
]),
'http_errors' => false
];
try {
$response = $this->httpClient
$response = $this->getHttpClient()
->request('POST', $url, $params)
->getBody()
->getContents();
$result = 'json' === self::DEFAULT_FORMAT ? json_decode($response, true) : $response;
// 日志
$this->logger(['request' => $body, 'response' => $result]);
return $result;
return 'json' === $this->format ? json_decode($response, true) : $response;
} catch (\Exception $e) {
$this->logger(['request' => $body, 'response' => $e]);
throw new HttpException($e->getMessage(), $e->getCode(), $e);
}
}
@ -137,62 +101,14 @@ class Order
* @param $order_sn
* @return mixed|string
* @throws GuzzleException
* @throws HttpException
* @throws InvalidArgumentException
*/
public function getProductOrder($orderId)
public function getProductOrder($order_sn)
{
$data = [
'id' => $orderId
'order_sn' => $order_sn
];
return $this->sendRequest('production.info', $data);
}
/**
* 加工工单原木材种
* @return mixed|string
* @throws GuzzleException
*/
public function getWoodTypeOptions($data)
{
return $this->sendRequest('Wood.types', $data);
}
/**
* 加工等级
* @return mixed|string
* @throws GuzzleException
*/
public function getProductionLevelOptions($data)
{
return $this->sendRequest('production.levels', $data);
}
/**
* 加工工单创建
* @return mixed|string
* @throws GuzzleException
*/
public function createProductOrder($data)
{
return $this->sendRequest('production.create', $data);
}
/**
* 加工工单更新
* @return mixed|string
* @throws HttpException|GuzzleException
*/
public function updateProductOrder($data)
{
return $this->sendRequest('production.update', $data);
}
/**
* 加工工单撤回
* @return mixed|string
* @throws HttpException|GuzzleException
*/
public function revokeProductOrder($data)
{
return $this->sendRequest('production.revoke', $data);
return $this->baseFun($data);
}
}

View File

@ -9,34 +9,82 @@
namespace Feature;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use Mockery;
use GuzzleHttp\ClientInterface;
use Mockery\Matcher\AnyArgs;
use PHPUnit\Framework\TestCase;
use Ykxiao\Dmmes\Exceptions\HttpException;
use Ykxiao\Dmmes\Exceptions\InvalidArgumentException;
use Ykxiao\Dmmes\OrderActions\Order;
class OrderTest extends TestCase
{
/**
* @return void
* @throws GuzzleException
*/
public function testGetWeatherWithInvalidType()
{
$w = new Order('mock-key', 'foo');
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid type value(base/all): foo');
$w->getProductOrder('SN23454324565432');
$this->fail('Failed to assert getOrder throw exception with invalid argument.');
}
public function testGetWeatherWithInvalidFormat()
{
$w = new Order('mock-key', 'base', 'array');
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid response format: array');
$w->getProductOrder('SN23454324565432');
$this->fail('Failed to assert getOrder throw exception with invalid argument.');
}
public function testGetWeatherWithGuzzleRuntimeException()
{
$client = \Mockery::mock(Client::class);
$client->allows()
->get(new AnyArgs())
->andThrow(new \Exception('request timeout'));
$w = \Mockery::mock(Order::class, ['mock-key'])->makePartial();
$w->allows()->getHttpClient()->andReturn($client);
$this->expectException(HttpException::class);
//$this->expectExceptionMessage('request timeout');
$w->getProductOrder('SN23454324565432');
}
public function testGetHttpClient()
{
$w = new Order('mock-key');
// 断言返回结果为 GuzzleHttp\ClientInterface 实例
$this->assertInstanceOf(ClientInterface::class, $w->getHttpClient());
}
public function testSetGuzzleOptions()
{
$w = new Order('mock-key');
// 设置参数前timeout 为 null
$this->assertNull($w->getHttpClient()->getConfig('timeout'));
// 设置参数
$w->setGuzzleOptions(['timeout' => 5000]);
// 设置参数后timeout 为 5000
$this->assertSame(5000, $w->getHttpClient()->getConfig('timeout'));
}
public function testGetProductOrder()
{
$response = new Response(200, [], '{"success": true}');
$w = new Order('mock-key');
// 创建模拟 http client。
$client = Mockery::mock(Client::class);
$client->allows()->post('https://api.dev.dwoodauto.com/api/v3/production.status', [
'signature' => 'eretgfdsa34565432b453',
'data' => ['order_sn' => 'w45676543456']
])->andReturn($response);
$w = Mockery::mock(Order::class, ['mock-key'])->makePartial();
$w->allows()->getHttpClient()->andReturn($client); // $client 为上面创建的模拟实例。
$this->assertSame('', '');
$w->getProductOrder('SN23454324565432');
$this->assertInstanceOf(ClientInterface::class, $w->getHttpClient());
}
}