Compare commits
17 Commits
Author | SHA1 | Date |
---|---|---|
|
5541bd41b6 | |
|
44fc0defb5 | |
|
e20f6b950e | |
|
8e972bb2dd | |
|
13a3da9b4e | |
![]() |
06a645973e | |
![]() |
9b3913ed60 | |
![]() |
bea811606c | |
|
4829305a44 | |
|
c9484deaec | |
![]() |
8c9680d364 | |
![]() |
2f30a6cf6f | |
![]() |
2e9999c877 | |
![]() |
540a9d0a58 | |
![]() |
c760f26478 | |
![]() |
27bafb5d6d | |
![]() |
21e28aee92 |
|
@ -1 +1 @@
|
|||
{"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}}
|
||||
{"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}}
|
89
README.md
89
README.md
|
@ -1,9 +1,11 @@
|
|||
# 德木自动化项目开放接口SDK
|
||||
|
||||
# 介绍
|
||||
|
||||
用于德木自动化对外开放接口数据交互
|
||||
|
||||
# 要求
|
||||
|
||||
- php版本:>=7.0
|
||||
|
||||
# 安装
|
||||
|
@ -15,11 +17,94 @@ composer require ykxiao/dmmes
|
|||
# 使用
|
||||
|
||||
```php
|
||||
|
||||
// secretKey 必填
|
||||
// callback url 选填(业务逻辑需要时填写,详情查看SDK文档)
|
||||
// options 选填(日志选项,默认写入日志)
|
||||
|
||||
$secretKey = 'gFBfirGATxafTeq74RAngaL74Ksdxhuy';
|
||||
|
||||
$w = new Order($secretKey);
|
||||
$options = [
|
||||
'logger' => true,
|
||||
'logs_path' => storage_path('logs/mes-sdk'),
|
||||
];
|
||||
|
||||
$w = new Order($secretKey, 'callback url', $options);
|
||||
|
||||
// 获取工单数据
|
||||
$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');
|
||||
```
|
||||
|
|
|
@ -13,6 +13,7 @@
|
|||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.3|^8.0",
|
||||
"guzzlehttp/guzzle": "^7.8",
|
||||
"ext-json": "*"
|
||||
},
|
||||
|
|
|
@ -10,88 +10,124 @@ 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 $apiUrl = 'https://api.dev.dwoodauto.com/api/v3/';
|
||||
protected $data = [];
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $secretKey;
|
||||
/**
|
||||
* @var mixed|string
|
||||
*/
|
||||
private $type;
|
||||
/**
|
||||
* @var mixed|string
|
||||
*/
|
||||
private $format;
|
||||
protected $secretKey;
|
||||
protected $callback;
|
||||
protected $options = [];
|
||||
|
||||
public function __construct($secretKey, $type = 'base', $format = 'json')
|
||||
public function __construct($secretKey, $callback = '', $options = [])
|
||||
{
|
||||
$this->secretKey = $secretKey;
|
||||
$this->type = $type;
|
||||
$this->format = $format;
|
||||
$this->httpClient = new Client($this->guzzleOptions);
|
||||
$this->callback = $callback;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
public function getHttpClient()
|
||||
public function getHttpClient(): Client
|
||||
{
|
||||
return new Client($this->guzzleOptions);
|
||||
}
|
||||
|
||||
public function setGuzzleOptions(array $options)
|
||||
{
|
||||
$this->guzzleOptions = $options;
|
||||
return $this->httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数签名
|
||||
* @param $params
|
||||
* @return mixed|string
|
||||
* @throws GuzzleException
|
||||
* @throws HttpException
|
||||
* @throws InvalidArgumentException
|
||||
* @return string
|
||||
*/
|
||||
public function baseFun($params)
|
||||
private function generateSignature($params): string
|
||||
{
|
||||
$url = $this->apiUrl . 'production.status';
|
||||
return (new Sign())->generateHmacSignature($this->secretKey, $params);
|
||||
}
|
||||
|
||||
if (!in_array(strtolower($this->format), ['xml', 'json'])) {
|
||||
throw new InvalidArgumentException('Invalid response format: ' . $this->format);
|
||||
/**
|
||||
* 日志
|
||||
* @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 (!in_array(strtolower($this->type), ['base', 'all'])) {
|
||||
throw new InvalidArgumentException('Invalid type value(base/all): ' . $this->type);
|
||||
// 判断文件夹是否存在,如果不存在则创建文件夹
|
||||
if (!is_dir($logFolder)) {
|
||||
if (!mkdir($logFolder, 0777, true)) {
|
||||
throw new Exception("Failed to create log folder: $logFolder");
|
||||
}
|
||||
}
|
||||
|
||||
$params['output'] = $this->format;
|
||||
$params['extensions'] = $this->type;
|
||||
$timestamp = date('Y-m-d H:i:s');
|
||||
$logContent = "[$timestamp] " . json_encode($logs, JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
|
||||
$signature = (new Sign())->generateHmacSignature($this->secretKey, $params);
|
||||
// 打开日志文件并追加内容
|
||||
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
|
||||
*/
|
||||
private function sendRequest($api, $data)
|
||||
{
|
||||
$url = self::API_URL . $api;
|
||||
|
||||
// 附加参数
|
||||
$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);
|
||||
}
|
||||
$params = [
|
||||
'headers' => ['content-type' => 'application/json', 'accept' => 'application/json'],
|
||||
'body' => json_encode([
|
||||
'signature' => $signature,
|
||||
'data' => $params
|
||||
]),
|
||||
'headers' => ['content-type' => 'application/json', 'accept' => 'application/json', 'user-agent' => 'mes sdk'],
|
||||
'body' => json_encode($body),
|
||||
'http_errors' => false
|
||||
];
|
||||
|
||||
try {
|
||||
$response = $this->getHttpClient()
|
||||
$response = $this->httpClient
|
||||
->request('POST', $url, $params)
|
||||
->getBody()
|
||||
->getContents();
|
||||
|
||||
return 'json' === $this->format ? json_decode($response, true) : $response;
|
||||
$result = 'json' === self::DEFAULT_FORMAT ? json_decode($response, true) : $response;
|
||||
// 日志
|
||||
$this->logger(['request' => $body, 'response' => $result]);
|
||||
return $result;
|
||||
} catch (\Exception $e) {
|
||||
$this->logger(['request' => $body, 'response' => $e]);
|
||||
throw new HttpException($e->getMessage(), $e->getCode(), $e);
|
||||
}
|
||||
}
|
||||
|
@ -101,14 +137,62 @@ class Order
|
|||
* @param $order_sn
|
||||
* @return mixed|string
|
||||
* @throws GuzzleException
|
||||
* @throws HttpException
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public function getProductOrder($order_sn)
|
||||
public function getProductOrder($orderId)
|
||||
{
|
||||
$data = [
|
||||
'order_sn' => $order_sn
|
||||
'id' => $orderId
|
||||
];
|
||||
return $this->baseFun($data);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,82 +9,34 @@
|
|||
namespace Feature;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use Mockery\Matcher\AnyArgs;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Mockery;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Ykxiao\Dmmes\Exceptions\HttpException;
|
||||
use Ykxiao\Dmmes\Exceptions\InvalidArgumentException;
|
||||
use Ykxiao\Dmmes\OrderActions\Order;
|
||||
|
||||
class OrderTest extends TestCase
|
||||
{
|
||||
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'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function testGetProductOrder()
|
||||
{
|
||||
$w = new Order('mock-key');
|
||||
$response = new Response(200, [], '{"success": true}');
|
||||
|
||||
$w->getProductOrder('SN23454324565432');
|
||||
$this->assertInstanceOf(ClientInterface::class, $w->getHttpClient());
|
||||
// 创建模拟 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('', '');
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue