1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PeterColes\Betfair\Api; |
4
|
|
|
|
5
|
|
|
use PeterColes\Betfair\Http\Client as HttpClient; |
6
|
|
|
|
7
|
|
|
class Auth |
8
|
|
|
{ |
9
|
|
|
const ENDPOINT = 'https://identitysso.betfair.com/api/'; |
10
|
|
|
|
11
|
|
|
const SESSION_LENGTH = 4 * 60 * 60; // 4 hours |
12
|
|
|
|
13
|
|
|
protected $httpClient; |
14
|
|
|
|
15
|
|
|
public static $appKey = null; |
16
|
|
|
|
17
|
|
|
public static $sessionToken = null; |
18
|
|
|
|
19
|
|
|
public static $lastLogin = null; |
20
|
|
|
|
21
|
|
|
public function __construct(HttpClient $httpClient = null) |
22
|
|
|
{ |
23
|
|
|
$this->httpClient = $httpClient ?: new HttpClient; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function init($appKey, $username, $password) |
27
|
|
|
{ |
28
|
|
|
if ($appKey == self::$appKey && $this->sessionRemaining() > 5) { |
29
|
|
|
$this->keepAlive(); |
30
|
|
|
} else { |
31
|
|
|
self::$appKey = $appKey; |
32
|
|
|
self::$sessionToken = $this->login($appKey, $username, $password); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function login($appKey, $username, $password) |
37
|
|
|
{ |
38
|
|
|
$result = $this->httpClient |
39
|
|
|
->setMethod('post') |
40
|
|
|
->setEndPoint(self::ENDPOINT.'login/') |
41
|
|
|
->authHeaders([ 'X-Application' => $appKey ]) |
42
|
|
|
->setFormData([ 'username' => $username, 'password' => $password ]) |
43
|
|
|
->send(); |
44
|
|
|
|
45
|
|
|
self::$lastLogin = time(); |
46
|
|
|
|
47
|
|
|
return $result->token; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function keepAlive() |
51
|
|
|
{ |
52
|
|
|
$this->httpClient |
53
|
|
|
->setEndPoint(self::ENDPOINT.'keepAlive/') |
54
|
|
|
->authHeaders() |
55
|
|
|
->send(); |
56
|
|
|
|
57
|
|
|
self::$lastLogin = time(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function logout() |
61
|
|
|
{ |
62
|
|
|
$this->httpClient |
63
|
|
|
->setEndPoint(self::ENDPOINT.'logout/') |
64
|
|
|
->authHeaders() |
65
|
|
|
->send(); |
66
|
|
|
|
67
|
|
|
self::$appKey = null; |
68
|
|
|
self::$sessionToken = null; |
69
|
|
|
self::$lastLogin = null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function sessionRemaining() |
73
|
|
|
{ |
74
|
|
|
return self::$lastLogin + self::SESSION_LENGTH - time(); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|