增加回调逻辑,PHP版本,其他优化

This commit is contained in:
ykxiao 2023-09-08 10:42:34 +08:00
parent c760f26478
commit 540a9d0a58
5 changed files with 102 additions and 140 deletions

View File

@ -1 +1 @@
{"version":1,"defects":{"Feature\\OrderTest::testGetProductOrder":5},"times":{"Unit\\OrderTest::testGetWeatherWithInvalidType":0.041,"Feature\\OrderTest::testGetWeatherWithInvalidType":0.107,"Unit\\OrderTest::testGetWeatherWithInvalidFormat":0,"Feature\\OrderTest::testGetWeatherWithInvalidFormat":0,"Feature\\OrderTest::testGetWeatherWithGuzzleRuntimeException":0.217,"Feature\\OrderTest::testGetHttpClient":0.043,"Feature\\OrderTest::testSetGuzzleOptions":0.01,"Unit\\OrderTest::testGetWeatherWithGuzzleRuntimeException":0.101,"Unit\\OrderTest::testGetHttpClient":0.02,"Unit\\OrderTest::testSetGuzzleOptions":0.004,"Feature\\OrderTest::testGetProductOrder":0.491,"Feature\\OrderTest::testCreateProductOrder":0.146}} {"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}}

View File

@ -28,3 +28,35 @@ $response = $w->createProductOrder([
'owner' => 'ykxiao' 'owner' => 'ykxiao'
]); ]);
``` ```
# 回调说明
- 配置回调后地址后应用服务器会以POST方式请求你的服务器地址以便你做进一步业务流程
- 回调你服务器地址后,可获取参数"data"、"signature"进行验签,"response" 为服务器处理结果数据
```php
// 回调参数调用方法
$w = new Order($secretKey, 'callback url');
// 回调验签
$receivedSignature = $params['signature'];
$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(json_encode($data));
// 验证签名是否匹配 hash_equals($receivedSignature, $calculatedSignature)
if ($receivedSignature === $calculatedSignature) {
return json_encode($data);
} else {
throw new Exception('数据签名验证失败!');
}
```

View File

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

View File

@ -11,89 +11,82 @@ namespace Ykxiao\Dmmes\OrderActions;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Ykxiao\Dmmes\Exceptions\HttpException; use Ykxiao\Dmmes\Exceptions\HttpException;
use Ykxiao\Dmmes\Exceptions\InvalidArgumentException;
use function in_array;
use function strtolower;
class Order 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 $guzzleOptions = [];
protected $apiUrl = 'https://api.dev.dwoodauto.com/api/v3/'; protected $httpClient;
protected $data = [];
/** protected $secretKey;
* @var string protected $callback;
*/
private $secretKey;
/**
* @var mixed|string
*/
private $type;
/**
* @var mixed|string
*/
private $format;
public function __construct($secretKey, $type = 'base', $format = 'json') public function __construct($secretKey, $callback = '')
{ {
$this->secretKey = $secretKey; $this->secretKey = $secretKey;
$this->type = $type; $this->httpClient = new Client($this->guzzleOptions);
$this->format = $format; $this->callback = $callback;
} }
public function getHttpClient() public function getHttpClient(): Client
{ {
return new Client($this->guzzleOptions); return $this->httpClient;
}
public function setGuzzleOptions(array $options)
{
$this->guzzleOptions = $options;
} }
/** /**
* 请求参数签名
* @param $params * @param $params
* @param $api * @return string
* @return mixed|string
* @throws GuzzleException
* @throws HttpException
* @throws InvalidArgumentException
*/ */
public function baseFun($params, $api) private function generateSignature($params): string
{ {
$url = $this->apiUrl . $api; return (new Sign())->generateHmacSignature($this->secretKey, $params);
}
if (!in_array(strtolower($this->format), ['xml', 'json'])) { /**
throw new InvalidArgumentException('Invalid response format: ' . $this->format); * 接口请求
} * @param $api
* @param $data
if (!in_array(strtolower($this->type), ['base', 'all'])) { * @return mixed|string
throw new InvalidArgumentException('Invalid type value(base/all): ' . $this->type); * @throws HttpException|GuzzleException
} */
private function sendRequest($api, $data)
{
$url = self::API_URL . $api;
// 附加参数 // 附加参数
$params['times'] = time(); $params = array_merge([
$params['output'] = $this->format; 'times' => time(),
$params['extensions'] = $this->type; 'output' => self::DEFAULT_FORMAT,
'extensions' => self::DEFAULT_TYPE,
], $data);
$signature = (new Sign())->generateHmacSignature($this->secretKey, $params); $signature = $this->generateSignature($params);
// 请求参数
$body = [
'signature' => $signature,
'data' => $params
];
if ($this->callback != '') {
$body = array_merge(['callback' => $this->callback], $body);
}
$params = [ $params = [
'headers' => ['content-type' => 'application/json', 'accept' => 'application/json'], 'headers' => ['content-type' => 'application/json', 'accept' => 'application/json', 'user-agent' => 'mes sdk'],
'body' => json_encode([ 'body' => json_encode($body),
'signature' => $signature,
'data' => $params
]),
'http_errors' => false 'http_errors' => false
]; ];
try { try {
$response = $this->getHttpClient() $response = $this->httpClient
->request('POST', $url, $params) ->request('POST', $url, $params)
->getBody() ->getBody()
->getContents(); ->getContents();
return 'json' === $this->format ? json_decode($response, true) : $response; return 'json' === self::DEFAULT_FORMAT ? json_decode($response, true) : $response;
} catch (\Exception $e) { } catch (\Exception $e) {
throw new HttpException($e->getMessage(), $e->getCode(), $e); throw new HttpException($e->getMessage(), $e->getCode(), $e);
} }
@ -103,27 +96,23 @@ class Order
* 获取工单信息 * 获取工单信息
* @param $order_sn * @param $order_sn
* @return mixed|string * @return mixed|string
* @throws GuzzleException * @throws HttpException|GuzzleException
* @throws HttpException
* @throws InvalidArgumentException
*/ */
public function getProductOrder($order_sn) public function getProductOrder($order_sn)
{ {
$data = [ $data = [
'order_sn' => $order_sn 'order_sn' => $order_sn
]; ];
return $this->baseFun($data, 'production.status'); return $this->sendRequest('production.status', $data);
} }
/** /**
* 加工工单创建 * 加工工单创建
* @return mixed|string * @return mixed|string
* @throws GuzzleException * @throws HttpException|GuzzleException
* @throws HttpException
* @throws InvalidArgumentException
*/ */
public function createProductOrder($data) public function createProductOrder($data)
{ {
return $this->baseFun($data, 'production.create'); return $this->sendRequest('production.create', $data);
} }
} }

View File

@ -9,94 +9,34 @@
namespace Feature; namespace Feature;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException;
use Mockery\Matcher\AnyArgs; use GuzzleHttp\Psr7\Response;
use Mockery;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Ykxiao\Dmmes\Exceptions\HttpException;
use Ykxiao\Dmmes\Exceptions\InvalidArgumentException;
use Ykxiao\Dmmes\OrderActions\Order; use Ykxiao\Dmmes\OrderActions\Order;
class OrderTest extends TestCase class OrderTest extends TestCase
{ {
public function testGetWeatherWithInvalidType() /**
{ * @return void
$w = new Order('mock-key', 'foo'); * @throws GuzzleException
*/
$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() public function testGetProductOrder()
{ {
$w = new Order('mock-key'); $response = new Response(200, [], '{"success": true}');
$w->getProductOrder('SN23454324565432'); // 创建模拟 http client。
$this->assertInstanceOf(ClientInterface::class, $w->getHttpClient()); $client = Mockery::mock(Client::class);
}
public function testCreateProductOrder() $client->allows()->post('https://api.dev.dwoodauto.com/api/v3/production.status', [
{ 'signature' => 'eretgfdsa34565432b453',
$w = new Order('mock-key'); 'data' => ['order_sn' => 'w45676543456']
])->andReturn($response);
$data = [ $w = Mockery::mock(Order::class, ['mock-key'])->makePartial();
'cube_plan' => 32.12,
'owner' => 'ykxiao' $w->allows()->getHttpClient()->andReturn($client); // $client 为上面创建的模拟实例。
];
$w->createProductOrder($data); $this->assertSame('', '');
$this->assertInstanceOf(ClientInterface::class, $w->getHttpClient());
} }
} }