1+ <?php
2+
3+ namespace VaasSdk \Authentication ;
4+
5+ use Amp \Http \Client \Form ;
6+ use Amp \Http \Client \HttpClient ;
7+ use Amp \Http \Client \HttpClientBuilder ;
8+ use Amp \Http \Client \Request ;
9+ use Amp \TimeoutCancellation ;
10+ use Exception ;
11+ use VaasSdk \Exceptions \VaasAuthenticationException ;
12+
13+ class OAuth2TokenReceiver {
14+ private string $ _tokenEndpoint ;
15+ private string $ _clientId ;
16+ private string $ _clientSecret ;
17+ private string $ _username ;
18+ private string $ _password ;
19+ private string $ _grantType ;
20+ private Form $ _formParams ;
21+ private HttpClient $ _browser ;
22+ private int $ _receiveTokenTimeout = 30 ;
23+
24+ public function __construct (
25+ string $ tokenEndpoint , string $ clientId , string $ clientSecret = "" ,
26+ string $ username = "" , string $ password = "" )
27+ {
28+ $ this ->_browser = HttpClientBuilder::buildDefault ();
29+ $ this ->_tokenEndpoint = $ tokenEndpoint ;
30+ $ this ->_clientId = $ clientId ;
31+ $ this ->_clientSecret = $ clientSecret ;
32+ $ this ->_username = $ username ;
33+ $ this ->_password = $ password ;
34+ $ this ->_grantType = $ this ->_clientSecret == "" ? "password " : "client_credentials " ;
35+
36+ $ this ->_formParams = new Form ();
37+ $ this ->_formParams ->addField ('client_id ' , $ this ->_clientId );
38+ $ this ->_formParams ->addField ('grant_type ' , $ this ->_grantType );
39+
40+ switch ($ this ->_grantType ) {
41+ case "password " :
42+ $ this ->_formParams ->addField ('username ' , $ this ->_username );
43+ $ this ->_formParams ->addField ('password ' , $ this ->_password );
44+ break ;
45+ case "client_credentials " :
46+ $ this ->_formParams ->addField ('client_secret ' , $ this ->_clientSecret );
47+ break ;
48+ default :
49+ throw new VaasAuthenticationException ("Invalid grant type " );
50+ }
51+ }
52+
53+ public function getToken () {
54+ try {
55+ $ request = new Request ($ this ->_tokenEndpoint , 'POST ' );
56+ $ request ->addHeader ('Content-Type ' , 'application/x-www-form-urlencoded ' );
57+ $ request ->setBody ($ this ->_formParams );
58+ $ response = $ this ->_browser ->request ($ request , new TimeoutCancellation ($ this ->_receiveTokenTimeout ));
59+ if ($ response ->getStatus () != 200 ) {
60+ throw new VaasAuthenticationException ($ response ->getReason (), $ response ->getStatus ());
61+ }
62+ } catch (Exception $ e ) {
63+ throw new VaasAuthenticationException ($ e ->getMessage (), $ e ->getCode ());
64+ }
65+ $ body = $ response ->getBody ()->buffer ();
66+ $ response_body = json_decode ($ body );
67+ return $ response_body ->access_token ;
68+ }
69+ }
0 commit comments