|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Speicher210\KontaktIO; |
|
6
|
|
|
|
|
7
|
|
|
use GuzzleHttp\Client as GuzzleHttpClient; |
|
8
|
|
|
use GuzzleHttp\Exception\ClientException; |
|
9
|
|
|
use Speicher210\KontaktIO\Exception\ApiKeyExtractionInvalidCredentialsException; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Helper functions around the API key. |
|
13
|
|
|
*/ |
|
14
|
|
|
class ApiKeyHelper |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Get the API key using a username and password combination. |
|
18
|
|
|
* |
|
19
|
|
|
* @param string $username The username. |
|
20
|
|
|
* @param string $password The password. |
|
21
|
|
|
* @return string |
|
22
|
|
|
* @throws \Speicher210\KontaktIO\Exception\ApiKeyExtractionInvalidCredentialsException |
|
23
|
|
|
*/ |
|
24
|
|
|
public function getApiKey($username, $password) |
|
25
|
|
|
{ |
|
26
|
|
|
$client = new GuzzleHttpClient(['cookies' => true, 'allow_redirects' => false]); |
|
27
|
|
|
$client->post( |
|
28
|
|
|
'https://panel.kontakt.io/signin', |
|
29
|
|
|
[ |
|
30
|
|
|
'form_params' => [ |
|
31
|
|
|
'username' => $username, |
|
32
|
|
|
'password' => $password |
|
33
|
|
|
] |
|
34
|
|
|
] |
|
35
|
|
|
); |
|
36
|
|
|
|
|
37
|
|
|
$response = $client->get('https://panel.kontakt.io/api-key'); |
|
38
|
|
|
|
|
39
|
|
|
if ($response->getStatusCode() !== 200) { |
|
40
|
|
|
throw new ApiKeyExtractionInvalidCredentialsException(); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$response = \json_decode($response->getBody()->getContents(), true); |
|
44
|
|
|
|
|
45
|
|
|
return $response['apiKey']; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Check if an API key is valid. |
|
50
|
|
|
* |
|
51
|
|
|
* @param string $apiKey The API key to check. |
|
52
|
|
|
* @return bool |
|
53
|
|
|
*/ |
|
54
|
|
|
public function apiKeyIsValid(string $apiKey): bool |
|
55
|
|
|
{ |
|
56
|
|
|
$client = new Client($apiKey); |
|
57
|
|
|
|
|
58
|
|
|
try { |
|
59
|
|
|
$client->get('/manager/me'); |
|
60
|
|
|
|
|
61
|
|
|
return true; |
|
62
|
|
|
} catch (ClientException $e) { |
|
63
|
|
|
if ($e->getResponse()->getStatusCode() === 401) { |
|
64
|
|
|
return false; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
throw $e; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|