|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PaymentGateway\PayPalSdk; |
|
4
|
|
|
|
|
5
|
|
|
use EasyHttp\GuzzleLayer\GuzzleClient; |
|
6
|
|
|
use EasyHttp\LayerContracts\Contracts\EasyClientContract; |
|
7
|
|
|
use EasyHttp\LayerContracts\Contracts\HttpClientRequest; |
|
8
|
|
|
|
|
9
|
|
|
abstract class PayPalApi |
|
10
|
|
|
{ |
|
11
|
|
|
protected EasyClientContract $client; |
|
12
|
|
|
protected string $baseUri; |
|
13
|
|
|
protected string $username; |
|
14
|
|
|
protected string $password; |
|
15
|
|
|
protected array $token; |
|
16
|
|
|
|
|
17
|
15 |
|
public function __construct(string $baseUri) |
|
18
|
|
|
{ |
|
19
|
15 |
|
$this->baseUri = $baseUri; |
|
20
|
15 |
|
$this->client = new GuzzleClient(); |
|
21
|
15 |
|
} |
|
22
|
|
|
|
|
23
|
15 |
|
public function setCredentials(string $username, string $password) |
|
24
|
|
|
{ |
|
25
|
15 |
|
$this->username = $username; |
|
26
|
15 |
|
$this->password = $password; |
|
27
|
15 |
|
} |
|
28
|
|
|
|
|
29
|
15 |
|
public function withHandler(callable $handler) |
|
30
|
|
|
{ |
|
31
|
15 |
|
$this->client->withHandler($handler); |
|
32
|
15 |
|
} |
|
33
|
|
|
|
|
34
|
15 |
|
protected function getToken(): array |
|
35
|
|
|
{ |
|
36
|
15 |
|
if ($this->token ?? null) { |
|
37
|
|
|
return $this->token; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
15 |
|
$client = clone $this->client; |
|
41
|
|
|
|
|
42
|
15 |
|
$client->prepareRequest('POST', $this->baseUri . '/v1/oauth2/token'); |
|
43
|
15 |
|
$client->getRequest()->setBasicAuth($this->username, $this->password); |
|
|
|
|
|
|
44
|
15 |
|
$client->getRequest()->setQuery(['grant_type' => 'client_credentials']); |
|
45
|
|
|
|
|
46
|
15 |
|
$this->token = $client->execute()->parseJson(); |
|
47
|
|
|
|
|
48
|
15 |
|
return $this->token; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
15 |
|
protected function setAuthentication(): HttpClientRequest |
|
52
|
|
|
{ |
|
53
|
15 |
|
return $this->client->getRequest() |
|
54
|
15 |
|
->setHeader('Authorization', 'Bearer ' . $this->getToken()['access_token']); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|