Skip to content

Commit a62459f

Browse files
committed
Authentication fix
1 parent 1f18f33 commit a62459f

2 files changed

Lines changed: 58 additions & 136 deletions

File tree

src/Client.php

Lines changed: 58 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@
3131

3232
class Client {
3333

34-
const API_BASE_URI_PRODUCTION = 'https://topups.reloadly.com';
34+
const API_BASE_URI_PRODUCTION = 'https://topups.reloadly.com';
35+
const API_BASE_URI_SANDBOX = 'https://topups-sandbox.reloadly.com';
3536
const API_ENDPOINT_AUTHENTICATE = 'https://auth.reloadly.com/oauth/token';
3637

3738
const API_ENDPOINT_TOPUP = '/topups';
@@ -40,6 +41,7 @@ class Client {
4041
const ENV_CLIENT_SECRET = 'RELOADLY_CLIENT_SECRET';
4142
const ENV_AUDIENCE = 'RELOADLY_AUDIENCE';
4243
const ENV_GRANT_TYPE = 'RELOADLY_GRANT_TYPE';
44+
const ENV_MODE = 'APP_ENV';
4345

4446
protected $clientId;
4547
protected $clientSecret;
@@ -49,7 +51,7 @@ class Client {
4951
protected $httpClient;
5052
protected $environment;
5153

52-
protected $session;
54+
protected $accessToken;
5355

5456
/**
5557
* Initializes the Reloadly Client
@@ -77,15 +79,14 @@ public function __construct(
7779
$this->grantType = $this->getArg($grantType, self::ENV_GRANT_TYPE);
7880
$this->audience = $this->getArg($audience, self::ENV_AUDIENCE);
7981

80-
$this->session = new Session();
81-
8282
if (!$this->clientId || !$this->clientSecret) {
8383
throw new Exception('Credentials are required to create a client.');
8484
}
8585

86-
$this->httpClient = ($httpClient) ? $httpClient : new HttpClient(['base_uri' => Client::API_BASE_URI_PRODUCTION]);
86+
//$this->httpClient = ($httpClient) ? $httpClient : new HttpClient(['base_uri' => Client::API_BASE_URI_PRODUCTION]);
87+
$this->httpClient = ($httpClient) ? $httpClient : new HttpClient(['base_uri' => $this->getBaseUri()]);
8788

88-
if (!$this->session->exists()) {
89+
if (!$this->accessToken) {
8990
$this->authenticate($clientId, $clientSecret);
9091
}
9192

@@ -123,26 +124,29 @@ private function authenticate(string $clientId = null, string $clientSecret = nu
123124
"audience" => $this->audience
124125
];
125126

126-
$response = $this->request("post", Client::API_ENDPOINT_AUTHENTICATE, $params, [], [], null, null, 2.0, true);
127+
$headers['Content-Type'] = 'application/json';
128+
129+
130+
$res = $this->httpClient->request('POST', Client::API_ENDPOINT_AUTHENTICATE, $params);
127131

128-
if ($response == null || $response->getContent()->access_token == null) return;
132+
$response = new Response($res->getStatusCode(), $res->getBody()->getContents(), $res->getHeaders());
129133

130-
$this->session->set($response->getContent()->access_token);
134+
if ($response != null && $response->getContent()->access_token != null)
135+
$this->accessToken = $response->getContent()->access_token;
131136
}
132137

133138
/**
134139
* Makes a request to the Reloadly API using the configured http client
135140
* Authentication information is automatically added if none is provided
136141
*
137-
* @param string $method HTTP Method
138-
* @param string $uri Fully qualified url
139-
* @param string[] $params Query string parameters
140-
* @param string[] $data POST body data
141-
* @param string[] $headers HTTP Headers
142-
* @param string|null $clientId
143-
* @param string|null $clientSecret
144-
* @param int $timeout Timeout in seconds
145-
* @param bool $authenticate should attempt authentication after 401
142+
* @param string $method HTTP Method
143+
* @param string $uri Fully qualified url
144+
* @param string[] $params Query string parameters
145+
* @param string[] $data POST body data
146+
* @param string[] $headers HTTP Headers
147+
* @param string|null $clientId
148+
* @param string|null $clientSecret
149+
* @param int $timeout Timeout in seconds
146150
* @return Response|null
147151
*/
148152
public function request(
@@ -153,8 +157,7 @@ public function request(
153157
array $headers = [],
154158
string $clientId = null,
155159
string $clientSecret = null,
156-
int $timeout = null,
157-
bool $authenticate = true
160+
int $timeout = null
158161
) : ?Response
159162
{
160163
$options = [];
@@ -171,25 +174,17 @@ public function request(
171174

172175
$headers['Accept'] = 'application/com.reloadly.topups-v1+json';
173176

174-
175177
if (!empty($params)) {
176-
if ($authenticate) {
177-
$options['query'] = array_merge_recursive($options, $params);
178-
}
179-
else {
180-
$options['query'] = $params;
181-
}
178+
$options['query'] = $params;
182179
}
183180

184181
try {
185182

186-
if ($this->session->exists()) {
187-
$headers['Authorization'] = 'Bearer '.$this->session->get();
183+
if ($this->accessToken) {
184+
$headers['Authorization'] = 'Bearer '.$this->accessToken;
188185
}
189186
else {
190-
if (!$authenticate) {
191-
$this->authenticate($clientId, $clientSecret);
192-
}
187+
$this->authenticate($clientId, $clientSecret);
193188
}
194189

195190
$options['headers'] = $headers;
@@ -202,7 +197,7 @@ public function request(
202197
} catch (ClientException | RequestException | GuzzleExceptionA $e) {
203198
if ($e->hasResponse()) {
204199

205-
if ($e->getResponse()->getStatusCode() == 401 && !$authenticate) {
200+
if ($e->getResponse()->getStatusCode() == 401) {
206201
$this->authenticate($clientId, $clientSecret);
207202
}
208203
}
@@ -247,12 +242,19 @@ public function setHttpClient(HttpClient $httpClient): void {
247242
$this->httpClient = $httpClient;
248243
}
249244

245+
public function getBaseUri()
246+
{
247+
return ($this->getArg(null, self::ENV_MODE) == "prod")
248+
? Client::API_BASE_URI_PRODUCTION
249+
: Client::API_BASE_URI_SANDBOX;
250+
}
251+
250252
/**
251-
* @return Balance|null
253+
* Returns account available balance
252254
*/
253-
public function getBalance() : ?Balance {
255+
public function getBalance() {
254256

255-
$response = $this->request("GET", "https://topups.reloadly.com/accounts/balance");
257+
$response = $this->request("GET", "/accounts/balance");
256258

257259
return Balance::fromResponse($response);
258260
}
@@ -270,7 +272,7 @@ public function getForeignExchangeRates(int $operator_id, int $amount): ?FxRate
270272
"amount" => $amount
271273
];
272274

273-
$response = $this->request("POST", "https://topups.reloadly.com/operators/fx-rate", [], $data);
275+
$response = $this->request("POST", "/operators/fx-rate", [], $data);
274276

275277
return FxRate::fromResponse($response);
276278
}
@@ -281,7 +283,7 @@ public function getForeignExchangeRates(int $operator_id, int $amount): ?FxRate
281283
*/
282284
public function getCountries() : array {
283285

284-
$response = $this->request("GET", "https://topups.reloadly.com/countries");
286+
$response = $this->request("GET", "/countries");
285287

286288
$countries = [];
287289

@@ -298,12 +300,17 @@ public function getCountries() : array {
298300

299301

300302
/**
301-
* @param string $isoName
302-
* @return Country
303+
* Retrieves country details by querying Reloadly using the country's ISO 3166-1 code.
304+
*
305+
* e.g: getCountryByIso("CD");
306+
* Where `CD` is the ISO 3166-1 code for the Democratic Republic of Congo.
307+
*
308+
* @param string $isoName
309+
* @return Country
303310
*/
304311
public function getCountryByIso(string $isoName) : ?Country {
305312

306-
$response = $this->request("GET", "https://topups.reloadly.com/countries/".strtoupper($isoName));
313+
$response = $this->request("GET", "/countries/".strtoupper($isoName));
307314

308315
return Country::fromResponse($response);
309316
}
@@ -327,7 +334,7 @@ public function getOperators(int $page = 1, int $size = 50, bool $suggestedAmoun
327334
"includeBundles" => $includeBundles
328335
];
329336

330-
$response = $this->request("GET", "https://topups.reloadly.com/operators", $params);
337+
$response = $this->request("GET", "/operators", $params);
331338

332339
$operators = [];
333340

@@ -366,7 +373,7 @@ public function getOperatorById(int $operator_id, bool $suggestedAmounts = true,
366373
"includeBundles" => $includeBundles
367374
];
368375

369-
$response = $this->request("GET", "https://topups.reloadly.com/operators/".$operator_id, $params);
376+
$response = $this->request("GET", "/operators/".$operator_id, $params);
370377

371378
return Operator::fromResponse($response);
372379
}
@@ -382,15 +389,13 @@ public function getOperatorById(int $operator_id, bool $suggestedAmounts = true,
382389
*/
383390
public function getOperatorByPhoneNumber(string $phoneNumber, string $countryIso, bool $suggestedAmounts = true, bool $suggestedAmountsMap = true, bool $includeBundles = true) : ?Operator {
384391

385-
// https://topups.reloadly.com/operators/auto-detect/phone/+50936377111/countries/HT?&includeBundles=true
386-
387392
$params = [
388393
"suggestedAmounts" => $suggestedAmounts,
389394
"suggestedAmountsMap" => $suggestedAmountsMap,
390395
"includeBundles" => $includeBundles
391396
];
392397

393-
$response = $this->request("GET", "https://topups.reloadly.com/operators/auto-detect/phone/{$phoneNumber}/countries/".strtoupper($countryIso), $params);
398+
$response = $this->request("GET", "/operators/auto-detect/phone/{$phoneNumber}/countries/".strtoupper($countryIso), $params);
394399

395400
var_dump($response);
396401

@@ -408,15 +413,13 @@ public function getOperatorByPhoneNumber(string $phoneNumber, string $countryIso
408413
*/
409414
public function getOperatorsByCountryIso(string $countryIso, bool $suggestedAmounts = true, bool $suggestedAmountsMap = true, bool $includeBundles = true) : ?array {
410415

411-
// https://topups.reloadly.com/operators/countries/HT
412-
413416
$params = [
414417
"suggestedAmounts" => $suggestedAmounts,
415418
"suggestedAmountsMap" => $suggestedAmountsMap,
416419
"includeBundles" => $includeBundles
417420
];
418421

419-
$response = $this->request("GET", "https://topups.reloadly.com/operators/countries/".strtoupper($countryIso), $params);
422+
$response = $this->request("GET", "/operators/countries/".strtoupper($countryIso), $params);
420423

421424
$operators = [];
422425

@@ -447,14 +450,12 @@ public function getOperatorsByCountryIso(string $countryIso, bool $suggestedAmou
447450
*/
448451
public function getPromotions(int $page = 1, int $size = 50) : ?array {
449452

450-
// https://topups.reloadly.com/promotions?page=1&size=3
451-
452453
$params = [
453454
"page" => $page,
454455
"size" => $size
455456
];
456457

457-
$response = $this->request("GET", "https://topups.reloadly.com/promotions", $params);
458+
$response = $this->request("GET", "/promotions", $params);
458459

459460
$promotions = [];
460461

@@ -484,9 +485,7 @@ public function getPromotions(int $page = 1, int $size = 50) : ?array {
484485
*/
485486
public function getPromotionsByCountryIso(string $country_iso) : ?array {
486487

487-
// https://topups.reloadly.com/promotions/country-codes/{countryCode}
488-
489-
$response = $this->request("GET", "https://topups.reloadly.com/promotions/country-codes/".$country_iso);
488+
$response = $this->request("GET", "/promotions/country-codes/".$country_iso);
490489

491490
$promotions = [];
492491

@@ -516,9 +515,7 @@ public function getPromotionsByCountryIso(string $country_iso) : ?array {
516515
*/
517516
public function getPromotionsByOperator(int $operator_id) : ?array {
518517

519-
// https://topups.reloadly.com/promotions/operators/129
520-
521-
$response = $this->request("GET", "https://topups.reloadly.com/promotions/operators/".$operator_id);
518+
$response = $this->request("GET", "/promotions/operators/".$operator_id);
522519

523520
$promotions = [];
524521

@@ -548,9 +545,7 @@ public function getPromotionsByOperator(int $operator_id) : ?array {
548545
*/
549546
public function getPromotionById(int $promotion_id) : ?Promotion {
550547

551-
// https://topups.reloadly.com/promotions/5
552-
553-
$response = $this->request("GET", "https://topups.reloadly.com/promotions/".$promotion_id);
548+
$response = $this->request("GET", "/promotions/".$promotion_id);
554549

555550
return Promotion::fromResponse($response);
556551
}
@@ -565,16 +560,14 @@ public function getPromotionById(int $promotion_id) : ?Promotion {
565560
*/
566561
public function getTransactions(DateTimeInterface $start_date_time, DateTimeInterface $end_date_time, int $page = 1, int $size = 50) : ?array {
567562

568-
// https://topups.reloadly.com/topups/reports/transactions?page=1&size=1&startTime=2018-06-01 00:00:00&endTime=2018-06-26 23:59:59
569-
570563
$params = [
571564
"page" => $page,
572565
"size" => $size,
573566
"startTime" => $start_date_time->format("Y-m-d H:i:s"),
574567
"endTime" => $end_date_time->format("Y-m-d H:i:s"),
575568
];
576569

577-
$response = $this->request("GET", "https://topups.reloadly.com/topups/reports/transactions", $params);
570+
$response = $this->request("GET", "/topups/reports/transactions", $params);
578571

579572
$transactions = [];
580573

@@ -604,14 +597,11 @@ public function getTransactions(DateTimeInterface $start_date_time, DateTimeInte
604597
*/
605598
public function getTransactionById(int $transaction_id) : ?Transaction {
606599

607-
// https://topups.reloadly.com/topups/reports/transactions/{transactionId}
608-
609-
$response = $this->request("GET", "https://topups.reloadly.com/topups/reports/transactions/".$transaction_id);
600+
$response = $this->request("GET", "/topups/reports/transactions/".$transaction_id);
610601

611602
return Transaction::fromResponse($response);
612603
}
613604

614-
615605
/**
616606
* @param int $operator_id
617607
* @param int $amount
@@ -644,14 +634,6 @@ public function topup(
644634
return TopUpResponse::fromResponse($response);
645635
}
646636

647-
/*
648-
649-
protected function getDiscounts(int $page = 1, int $size = 10, int $operator_id = null): \Twilio\Rest\Api\V2010\Account\CallList {
650-
return $this->api->v2010->account->calls;
651-
}
652-
653-
*/
654-
655637
/**
656638
* Provide a friendly representation
657639
*
@@ -660,10 +642,4 @@ protected function getDiscounts(int $page = 1, int $size = 10, int $operator_id
660642
public function __toString(): string {
661643
return '[Client ' . $this->getClientId() . ']';
662644
}
663-
664645
}
665-
666-
667-
668-
669-

0 commit comments

Comments
 (0)