Completed
Push — master ( 396800...21044c )
by Kirill
03:50
created

Client::getSerialNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

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 6
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Personnage\Tinkoff\SDK\E2Card;
4
5
use Closure;
6
use GuzzleHttp\Psr7\Request;
7
use Personnage\Tinkoff\SDK\Exception\HttpException;
8
use Personnage\Tinkoff\SDK\Exception\ResponseException;
9
use Personnage\Tinkoff\SDK\HasSender;
10
use Personnage\Tinkoff\SDK\Response\Init;
11
use Personnage\Tinkoff\SDK\Response\Payment;
12
use Personnage\Tinkoff\SDK\Response\State;
13
use Personnage\Tinkoff\SDK\Sender;
14
use Psr\Http\Message\RequestInterface;
15
16
final class Client
17
{
18
    use HasSignature, HasSender;
19
20
    private $baseUri;
21
    private $terminalKey;
22
    private $certNumber;
23
    private $signer;
24
25
    /**
26
     * @var array
27
     */
28
    private static $requestHeaders = [
29
        'Accept' => 'application/json',
30
        'Content-Type' => 'application/x-www-form-urlencoded',
31
    ];
32
33
    /**
34
     * Init a new instance.
35
     *
36
     * @param string  $uri
37
     * @param string  $terminalKey
38
     * @param string  $certNumber
39
     * @param Closure $signer
40
     * @param Sender  $sender
41
     */
42
    public function __construct(string $uri, string $terminalKey, string $certNumber, Closure $signer, Sender $sender)
43
    {
44
        $this->baseUri = rtrim($uri, '/');
45
        $this->terminalKey = $terminalKey;
46
        $this->certNumber = $certNumber;
47
        $this->signer = $signer;
48
        $this->setSender($sender);
49
    }
50
51
    /**
52
     * Create a new instance.
53
     *
54
     * @param string   $uri
55
     * @param string   $terminalKey
56
     * @param string   $pemFile
57
     * @param Sender   $sender
58
     * @return self
59
     */
60
    public static function make(string $uri, string $terminalKey, string $pemFile, Sender $sender): self
61
    {
62
        $signer = function ($message) use ($pemFile): string {
63
            return self::sign($message, realpath($pemFile));
64
        };
65
66
        return new self($uri, $terminalKey, self::getSerialNumber($pemFile), $signer, $sender);
67
    }
68
69
    /**
70
     * Get serial number of X509.
71
     *
72
     * @param  string  $pemFile
73
     * @return string
74
     */
75
    private static function getSerialNumber(string $pemFile): string
76
    {
77
        $text = openssl_x509_parse('file://'.$pemFile, true);
78
79
        return $text['serialNumber'];
80
    }
81
82
    /**
83
     * Init a new payment session.
84
     *
85
     * @param string $orderId Номер заказа в системе Продавца.
86
     * @param string $cardId  Идентификатор карты пополнения.
87
     * @param int    $amount  Сумма в копейках.
88
     * @param array  $extra   Массив дополнительных полей, которые могут быть переданы в этом запросе.
89
     *
90
     * @return Init
91
     * @throws HttpException
92
     */
93 View Code Duplication
    public function init(string $orderId, string $cardId, int $amount, array $extra = []): Init
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...
94
    {
95
        $extra['Amount'] = $amount;
96
        $extra['CardId'] = $cardId;
97
        $extra['OrderId'] = $orderId;
98
99
        return new Init($this->send($this->makeRequest('Init', $extra)));
100
    }
101
102
    /**
103
     * Make payout to card.
104
     *
105
     * @param mixed $paymentId
106
     *
107
     * @return Payment
108
     * @throws HttpException
109
     */
110
    public function payment($paymentId): Payment
111
    {
112
        return new Payment($this->send($this->makeRequest('Payment', ['PaymentId' => $paymentId])));
113
    }
114
115
    /**
116
     * Get op state.
117
     *
118
     * @param mixed $paymentId
119
     *
120
     * @return State
121
     * @throws HttpException
122
     */
123
    public function getState($paymentId): State
124
    {
125
        return new State($this->send($this->makeRequest('GetState', ['PaymentId' => $paymentId])));
126
    }
127
128
    /**
129
     * Init a new payment session and make payout to card.
130
     *
131
     * @param string $orderId Номер заказа в системе Продавца.
132
     * @param string $cardId  Идентификатор карты пополнения.
133
     * @param int    $amount  Сумма в копейках.
134
     * @param array  $extra   Массив дополнительных полей, которые могут быть переданы в этом запросе.
135
     *
136
     * @return Payment
137
     * @throws HttpException
138
     * @throws ResponseException
139
     */
140
    public function payout(string $orderId, string $cardId, int $amount, array $extra = []): Payment
141
    {
142
        $response = $this->init($orderId, $cardId, $amount, $extra);
143
        if ($response->hasError() || 'CHECKED' !== $response->getStatus()) {
144
            throw new ResponseException($response);
145
        }
146
147
        $response = $this->payment($response->getPaymentId());
148
        if ($response->hasError() || 'COMPLETED' !== $response->getStatus()) {
149
            throw new ResponseException($response);
150
        }
151
152
        return $response;
153
    }
154
155
    /**
156
     * Make a new http request.
157
     *
158
     * @param string $uri
159
     * @param array  $body
160
     *
161
     * @return RequestInterface
162
     */
163
    private function makeRequest(string $uri, array $body = []): RequestInterface
164
    {
165
        $body['TerminalKey'] = $this->terminalKey;
166
        $body['DigestValue'] = base64_encode(self::digest($body));
167
        $body['SignatureValue'] = base64_encode(\call_user_func($this->signer, $body));
168
        $body['X509SerialNumber'] = $this->certNumber;
169
170
        return new Request('post', "$this->baseUri/$uri", self::$requestHeaders, http_build_query($body, '', '&'));
171
    }
172
}
173