|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace App\Helper\OmiPay;
|
|
|
|
|
|
|
|
use App\Helper\Log;
|
|
|
|
use App\Helper\OmiPay\Request\AbstractRequest;
|
|
|
|
use App\Helper\StringHelper;
|
|
|
|
use App\Helper\TimeHelper;
|
|
|
|
use Exception;
|
|
|
|
use GuzzleHttp\Client;
|
|
|
|
use Hyperf\Guzzle\CoroutineHandler;
|
|
|
|
use GuzzleHttp\HandlerStack;
|
|
|
|
|
|
|
|
abstract class AbstractApi
|
|
|
|
{
|
|
|
|
protected static $client;
|
|
|
|
|
|
|
|
protected static function getCommonParams() {
|
|
|
|
$params = [
|
|
|
|
'm_number' => Config::get('app_id'),
|
|
|
|
'timestamp' => TimeHelper::getMillisecond(),
|
|
|
|
'nonce_str' => StringHelper::getRandomString(32),
|
|
|
|
];
|
|
|
|
$params['sign'] = Signer::sign($params);
|
|
|
|
return $params;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function request(AbstractRequest $request) {
|
|
|
|
$params = self::getCommonParams();
|
|
|
|
$params = array_merge($params, $request->getParams());
|
|
|
|
try {
|
|
|
|
Log::info('url:' . $request->getUrl(), [], 'omipay');
|
|
|
|
$response = self::getClient()->post($request->getUrl(), [
|
|
|
|
'query' => $params
|
|
|
|
]);
|
|
|
|
Log::info('request:', $params, 'omipay');
|
|
|
|
$body = (string)$response->getBody();
|
|
|
|
Log::info('response:' . $body, [], 'omipay');
|
|
|
|
$result = json_decode($body, true);
|
|
|
|
if (empty($result)) {
|
|
|
|
$result = [
|
|
|
|
'return_code' => 'FAIL',
|
|
|
|
'error_code' => 'RESPONSE_ERROR',
|
|
|
|
'error_msg' => '返回数据异常',
|
|
|
|
];
|
|
|
|
}
|
|
|
|
return new Result($result);
|
|
|
|
} catch (Exception $e) {
|
|
|
|
Log::error('error:' . $e->getMessage(), [], 'omipay');
|
|
|
|
return new Result([
|
|
|
|
'return_code' => 'FAIL',
|
|
|
|
'error_code' => 'NETWORK_ERROR',
|
|
|
|
'error_msg' => '网络错误',
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
protected static function getClient(): Client {
|
|
|
|
if (!self::$client) {
|
|
|
|
self::$client = new Client([
|
|
|
|
'base_uri' => Config::get('base_url'),
|
|
|
|
'handler' => HandlerStack::create(new CoroutineHandler()),
|
|
|
|
'headers' => [
|
|
|
|
'Content-Type' => 'application/json',
|
|
|
|
],
|
|
|
|
'timeout' => 5,
|
|
|
|
'swoole' => [
|
|
|
|
'timeout' => 10,
|
|
|
|
'socket_buffer_size' => 1024 * 1024 * 2,
|
|
|
|
],
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
return self::$client;
|
|
|
|
}
|
|
|
|
}
|