BaseClient::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Kaylyu\Alipay\F2fpay\Kernel;
4
5
use GuzzleHttp\MessageFormatter;
6
use GuzzleHttp\Middleware;
7
use Kaylyu\Alipay\F2fpay\Base\Model\Result\AlipayF2FPayResult;
8
use Kaylyu\Alipay\Kernel\Exceptions\Exception;
9
use Kaylyu\Alipay\Kernel\ServiceContainer;
10
use Kaylyu\Alipay\Kernel\Support\Collection;
11
use Kaylyu\Alipay\Kernel\Traits\HasHttpRequests;
12
use Psr\Http\Message\ResponseInterface;
13
14
/**
15
 * Class BaseClient.
16
 */
17
class BaseClient
18
{
19
    use HasHttpRequests {
20
        request as performRequest;
21
    }
22
23
    /**
24
     * @var \Kaylyu\Alipay\Kernel\ServiceContainer
25
     */
26
    protected $app;
27
28
    /**
29
     * @var
30
     */
31
    protected $baseUri;
32
33
    /**
34
     * BaseClient constructor.
35
     *
36
     * @param \Kaylyu\Alipay\Kernel\ServiceContainer $app
37
     */
38
    public function __construct(ServiceContainer $app)
39
    {
40
        $this->app = $app;
41
    }
42
43
    /**
44
     * @param $request
45
     * @param null $appAuthToken
46
     * @author kaylv <[email protected]>
47
     * @return array|Collection|string
48
     */
49
    public function httpPost($request, $appAuthToken = null)
50
    {
51
        return $this->request($request, 'POST', $appAuthToken);
52
    }
53
54
    /**
55
     * @param $request
56
     * @param string $method
57
     * @param null $appAuthToken
58
     * @author kaylv <[email protected]>
59
     * @return array|bool|Collection|mixed|object|ResponseInterface|\SimpleXMLElement|string
60
     * @throws Exception
61
     */
62
    public function request($request, string $method = 'GET', $appAuthToken = null)
63
    {
64
        if (empty($this->middlewares)) {
65
            $this->registerHttpMiddlewares();
66
        }
67
68
        //初始化AopClient
69
        $aop = $this->newAopClient();
70
71
        //准备请求参数
72
        list($requestUrl, $apiParams) = $aop->requestPrepare($request, null, $appAuthToken);
73
74
        //发起HTTP请求
75
        $key = 'query';
76
        if ($method == 'POST') {
77
            $key = 'form_params';
78
        }
79
        $response = $this->performRequest($requestUrl, $method, [$key => $apiParams]);
80
81
        //读取内容
82
        $response = $response->getBody()->getContents();
83
84
        //解析
85
        $rs = json_decode($response);
86
87
        //校验
88
        if(isset($rs->null_response)){
89
            throw new Exception('系统繁忙!!!', $rs->null_response->code);
90
        }
91
92
        //验签解密
93
        $response = $aop->responseHandle($request, $response);
94
95
        return $response;
96
    }
97
98
    /**
99
     * Register Guzzle middlewares.
100
     */
101
    protected function registerHttpMiddlewares()
102
    {
103
        // log
104
        $this->pushMiddleware($this->logMiddleware(), 'log');
105
    }
106
107
    /**
108
     * Log the request.
109
     *
110
     * @return \Closure
111
     */
112
    protected function logMiddleware()
113
    {
114
        $formatter = new MessageFormatter($this->app['config']['http.log_template'] ?? MessageFormatter::DEBUG);
115
116
        return Middleware::log($this->app['logger'], $formatter);
117
    }
118
119
    /**
120
     * 初始化AopClient
121
     * @author kaylv <[email protected]>
122
     * @throws Exception
123
     */
124 View Code Duplication
    private function newAopClient()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
125
    {
126
        //获取当面付配置
127
        $f2fpay = $this->app->getF2fpay();
128
129
        //获取配置参数
130
        $gatewayUrl = $f2fpay['gateway_url'];
131
        $appId = $f2fpay['app_id'];
132
        $signType = $f2fpay['sign_type'];
133
        $rsaPrivateKey = $f2fpay['merchant_private_key'];
134
        $alipayPublicKey = $f2fpay['alipay_public_key'];
135
        $charset = $f2fpay['charset'];
136
        $notifyUrl = $f2fpay['notify_url'];
137
138
        if (empty($appId) || trim($appId) == "") {
139
            throw new Exception("appid should not be NULL!");
140
        }
141
        if (empty($rsaPrivateKey) || trim($rsaPrivateKey) == "") {
142
            throw new Exception("merchant_private_key should not be NULL!");
143
        }
144
        if (empty($alipayPublicKey) || trim($alipayPublicKey) == "") {
145
            throw new Exception("alipay_public_key should not be NULL!");
146
        }
147
        if (empty($charset) || trim($charset) == "") {
148
            throw new Exception("charset should not be NULL!");
149
        }
150
        if (empty($notifyUrl) || trim($notifyUrl) == "") {
151
            throw new Exception("sign_type should not be NULL");
152
        }
153
        if (empty($gatewayUrl) || trim($gatewayUrl) == "") {
154
            throw new Exception("gateway_url should not be NULL");
155
        }
156
        if (empty($signType) || trim($signType) == "") {
157
            throw new Exception("sign_type should not be NULL");
158
        }
159
160
        //组装请求数据
161
        $aop = new AopClient();
162
        $aop->gatewayUrl = $gatewayUrl;
163
        $aop->appId =$appId;
164
        $aop->signType = $signType;
165
        $aop->rsaPrivateKey = $rsaPrivateKey;
166
        $aop->alipayrsaPublicKey = $alipayPublicKey;
167
        $aop->apiVersion = "1.0";
168
        $aop->charset = $charset;
0 ignored issues
show
Bug introduced by
The property charset does not seem to exist. Did you mean postCharset?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
169
        $aop->format = 'json';
170
171
        return $aop;
172
    }
173
174
    /**
175
     * 格式化返回数据
176
     * @param $response
177
     * @author kaylv <[email protected]>
178
     * @return array|Collection|string
179
     */
180
    protected function formatResponseToType($response)
181
    {
182
        //获取数据
183
        $data = is_object($response) ? (array)$response : $response;
184
        //返回数据类型
185
        $type = $this->app->config->get('response_type');
186
187
        switch ($type ?? 'array') {
188
            default:
189
            case 'collection':
190
                return new Collection($data);
191
            case 'array':
192
                return $data;
193
            case 'object':
194
                return $response;
195
            case 'json':
196
                return json_encode($data, JSON_UNESCAPED_UNICODE);
197
        }
198
    }
199
}
200