· 6 years ago · Mar 23, 2020, 08:34 AM
1<?php declare(strict_types=1);
2
3namespace KingApp\ApaczkaBundle\Service;
4
5use Doctrine\ORM\EntityManagerInterface;
6use KingApp\CommonBundle\Service\Site;
7use KingApp\ConsignmentBundle\Entity\Provider;
8use GuzzleHttp\Client;
9
10final class Api
11{
12 private const EXPIRES = '+30min';
13
14 private $site;
15 private $client;
16 private $entityManager;
17
18 public function __construct(Site $site, Client $client, EntityManagerInterface $entityManager)
19 {
20 $this->site = $site;
21 $this->client = $client;
22 $this->entityManager = $entityManager;
23 }
24
25 public function request(string $route, $data = null)
26 {
27 $ch = curl_init($this->getApiUri() . $route);
28 curl_setopt($ch, CURLOPT_POST, true);
29 curl_setopt($ch, CURLOPT_VERBOSE, true);
30 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
31 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
32 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
33
34 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($this->buildRequest($route, $data)));
35
36 $result = curl_exec($ch);
37
38 if ($result === false) {
39 curl_close($ch);
40
41 return false;
42 }
43 curl_close($ch);
44
45 return json_decode($result);
46 }
47
48// public function request2(string $route, ?array $data = null)
49// {
50// $options = [
51//// 'headers' => [
52//// 'Content-Type' => 'application/json',
53//// ],
54// ];
55// $options['form_params'] = $this->buildRequest($route, $data);
56// /** @var \GuzzleHttp\Psr7\Response $request */
57// $request = $this->client->post($this->getApiUri() . $route, $options);
58// return json_decode($request->getBody()->getContents());
59// }
60
61 private function buildRequest(string $route, ?array $data = [])
62 {
63 $data = json_encode($data);
64 $expires = strtotime(self::EXPIRES);
65 return [
66 'app_id' => $this->getAppId(),
67 'request' => $data,
68 'expires' => $expires,
69 'signature' => $this->getSignature($this->stringToSign($this->getAppId(), $route, $data, $expires), $this->getAppSecret()),
70 ];
71 }
72
73 private function getApiUri(): string
74 {
75 return 'https://www.apaczka.pl/api/v2/';
76 }
77
78 private function getAppId(): string
79 {
80 return $this->getConfig()->getLogin();
81 }
82
83 private function getAppSecret(): string
84 {
85 return $this->getConfig()->getPassword();
86 }
87
88 private function getSignature(string $string, string $key): string
89 {
90 return hash_hmac('sha256', $string, $key);
91 }
92
93 private function stringToSign(string $appId, string $route, string $data, int $expires): string
94 {
95 return sprintf("%s:%s:%s:%s", $appId, $route, $data, $expires);
96 }
97
98 private function getConfig(): Provider
99 {
100 $provider = $this->entityManager->getRepository(Provider::class)->findOneBy([
101 'config' => $this->site->getConsignment(),
102 'type' => Provider::TYPE_APACZKA,
103 ]);
104 if (!$provider) throw new \Exception('Nie zintegrowano Apaczka');
105 return $provider;
106 }
107}