Skip to content

Commit

Permalink
Merge pull request #13 from DrH97/dev-dr
Browse files Browse the repository at this point in the history
Dev dr
  • Loading branch information
DrH97 authored Jan 10, 2022
2 parents aa3b7da + 8217e43 commit 3429e21
Show file tree
Hide file tree
Showing 13 changed files with 243 additions and 180 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function (Blueprint $table) {
$table->string('request_id')->unique();
$table->string('status');
$table->string('message');
// $table->string('receipt_number')->nullable();
$table->string('receipt_number')->nullable();
$table->string('command_id');
$table->string('provider');
$table->string('destination');
Expand Down
61 changes: 61 additions & 0 deletions src/Console/RequestStatusCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace DrH\Tanda\Console;

use DrH\Tanda\Repositories\Tanda;
use Illuminate\Console\Command;

class RequestStatusCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'tanda:query_status';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Check the status of all missing transactions.';

/**
* Create a new command instance.
*
*/
public function __construct(private Tanda $tanda)
{
parent::__construct();
}

/**
* Execute the console command.
*
*/
public function handle()
{
$results = $this->tanda->queryRequestStatus();

if (count($results['successful'])) {
$this->info("Successful queries: ");

foreach ($results['successful'] as $reference => $message) {
$this->comment(" * $reference ---> $message");
}
}

if (count($results['errors'])) {
$this->info("Failed queries: ");

foreach ($results['errors'] as $reference => $message) {
$this->comment(" * $reference ---> $message");
}
}

if (empty($results['successful']) && empty($results['errors'])) {
$this->comment("Nothing to query... all transactions seem to be ok.");
}
}
}
63 changes: 0 additions & 63 deletions src/Console/TransactionStatusCommand.php

This file was deleted.

1 change: 1 addition & 0 deletions src/Facades/Utility.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
/**
* @method static TR airtimePurchase(int $phone, int $amount, int $relationId = null)
* @method static array requestStatus(string $reference)
* @method static TR billPayment(int $accountNo, int $amount, string $provider, int $relationId = null)
*
* @see \DrH\Tanda\Library\Utility
*/
Expand Down
15 changes: 5 additions & 10 deletions src/Library/Authenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,17 @@

class Authenticator
{
protected string $endpoint;

protected BaseClient $client;

protected static Authenticator $instance;
private string $endpoint;

private ?string $credentials = null;

/**
* Authenticator constructor.
*
* @param BaseClient $baseClient
* @param BaseClient $client
*/
public function __construct(BaseClient $baseClient)
public function __construct(private BaseClient $client)
{
$this->client = $baseClient;
$this->endpoint = Endpoints::build(Endpoints::AUTH);
self::$instance = $this;
}


Expand Down Expand Up @@ -89,6 +82,8 @@ private function makeRequest(): ResponseInterface
$clientId = config('tanda.client_id', false);
$clientSecret = config('tanda.client_secret', false);

$this->endpoint = Endpoints::build(Endpoints::AUTH);

return $this->client->clientInterface->request(
'POST',
$this->endpoint,
Expand Down
32 changes: 10 additions & 22 deletions src/Library/Core.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function sendRequest(string $method, string $url, array $body): ResponseI

public function getBody(array $body): array
{
// Added these to reduce redundancy in child classes
// Added these to reduce redundancy in child classes
$body += [
'referenceParameters' => $this->getReferenceParameters()
];
Expand All @@ -82,29 +82,16 @@ public function getTelcoFromPhone(int $phone): string
$safReg = '/^(?:254|\+254|0)?((?:7(?:[0129][0-9]|4[0123568]|5[789]|6[89])|(1([1][0-5])))[0-9]{6})$/';
$airReg = '/^(?:254|\+254|0)?((?:(7(?:(3[0-9])|(5[0-6])|(6[27])|(8[0-9])))|(1([0][0-6])))[0-9]{6})$/';
$telReg = '/^(?:254|\+254|0)?(7(7[0-9])[0-9]{6})$/';
$equReg = '/^(?:254|\+254|0)?(7(6[3-6])[0-9]{6})$/';
// $equReg = '/^(?:254|\+254|0)?(7(6[3-6])[0-9]{6})$/';
$faibaReg = '/^(?:254|\+254|0)?(747[0-9]{6})$/';

switch (1) {
case preg_match($safReg, $phone):
$result = Providers::SAFARICOM;
break;
case preg_match($airReg, $phone):
$result = Providers::AIRTEL;
break;
case preg_match($telReg, $phone):
$result = Providers::TELKOM;
break;
// case preg_match($equReg, $phone):
// $result = Providers::EQUITEL;
// break;
case preg_match($faibaReg, $phone):
$result = Providers::FAIBA;
break;
default:
$result = null;
break;
}
$result = match (1) {
preg_match($safReg, $phone) => Providers::SAFARICOM,
preg_match($airReg, $phone) => Providers::AIRTEL,
preg_match($telReg, $phone) => Providers::TELKOM,
preg_match($faibaReg, $phone) => Providers::FAIBA,
default => null,
};

if (!$result) {
throw new TandaException("Phone does not seem to be valid or supported");
Expand Down Expand Up @@ -172,6 +159,7 @@ protected function fireTandaEvent(TandaRequest $request): void
if ($request->status == 000001) {
return;
}

if ($request->status == 000000) {
event(new TandaRequestSuccessEvent($request));
} else {
Expand Down
31 changes: 26 additions & 5 deletions src/Library/Utility.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace DrH\Tanda\Library;

use Carbon\Carbon;
use DrH\Tanda\Exceptions\TandaException;
use DrH\Tanda\Models\TandaRequest;
use GuzzleHttp\Exception\GuzzleException;
Expand Down Expand Up @@ -70,7 +71,6 @@ public function airtimePurchase(
* @param int $accountNo
* @param int $amount
* @param string $provider
* @param int $phone
* @param int|null $relationId
* @param bool $save
* @return array|TandaRequest
Expand All @@ -81,10 +81,11 @@ public function billPayment(
int $accountNo,
int $amount,
string $provider,
int $phone,
int $relationId = null,
bool $save = true
): array | TandaRequest {
$provider = strtoupper($provider);

$allowedProviders = [
Providers::KPLC_PREPAID,
Providers::KPLC_POSTPAID,
Expand All @@ -97,16 +98,20 @@ public function billPayment(

$this->validate($provider, $amount);

if (!in_array(strtoupper($provider), $allowedProviders)) {
if (!in_array($provider, $allowedProviders)) {
throw new TandaException("Provider does not seem to be valid or supported");
}

$this->provider = $provider;
$this->amount = $amount;
$this->destination = $phone;
$this->destination = $accountNo;

$this->setCommand($this->provider);

if (in_array($provider, [Providers::KPLC_PREPAID, Providers::KPLC_POSTPAID])) {
$this->provider = 'KPLC';
}

// TODO: Check whether customerContact is necessary or what it is used for.
// $phone = $this->formatPhoneNumber($phone);
$requestParameters = [
Expand Down Expand Up @@ -146,7 +151,23 @@ public function billPayment(
*/
public function requestStatus(string $reference): array
{
return $this->request(Endpoints::STATUS, [], [':requestId' => $reference]);
$response = $this->request(Endpoints::STATUS, [], [':requestId' => $reference]);

$request = TandaRequest::whereRequestId($response['id'])->first();

if ($request && $request->status !== $response['status']) {
$request->update([
'status' => $response['status'],
'message' => $response['message'],
'receipt_number' => $response['receiptNumber'],
'result' => $response['resultParameters'],
'last_modified' => Carbon::parse($response['datetimeLastModified'])->utc(),
]);

$this->fireTandaEvent($request);
}

return $response;
}

private function setCommand(string $provider)
Expand Down
73 changes: 73 additions & 0 deletions src/Repositories/Tanda.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace DrH\Tanda\Repositories;

use Carbon\Carbon;
use DrH\Tanda\Events\TandaRequestFailedEvent;
use DrH\Tanda\Events\TandaRequestSuccessEvent;
use DrH\Tanda\Exceptions\TandaException;
use DrH\Tanda\Library\BaseClient;
use DrH\Tanda\Library\Utility;
use DrH\Tanda\Models\TandaRequest;
use GuzzleHttp\Exception\GuzzleException;
use JetBrains\PhpStorm\ArrayShape;

class Tanda
{
private Utility $utility;

public function __construct(BaseClient $baseClient)
{
$this->utility = new Utility($baseClient);
}

#[ArrayShape(['successful' => "array", 'errors' => "array"])]
public function queryRequestStatus(): array
{
/** @var TandaRequest[] $tandaRequests */
$tandaRequests = TandaRequest::whereStatus(000001)->get();
$success = $errors = [];

foreach ($tandaRequests as $request) {
try {
$result = $this->utility->requestStatus($request->request_id);

$success[$request->request_id] = $result['message'];

$data = [
'status' => $result['status'],
'message' => $result['message'],
'receipt_number' => $result['receiptNumber'],
'result' => $result['resultParameters'],
'last_modified' => Carbon::parse($result['datetimeLastModified'])->utc(),
];

$transaction = TandaRequest::updateOrCreate(
['request_id' => $result['id']],
$data
);

$this->fireTandaEvent($transaction);
} catch (TandaException | GuzzleException $e) {
$errors[$request->request_id] = $e->getMessage();
}
}

return ['successful' => $success, 'errors' => $errors];
}

/**
* @param TandaRequest $request
* @return void
*/
private static function fireTandaEvent(TandaRequest $request): void
{
if ($request->status == 000001) {
return;
}

$request->status == 000000
? TandaRequestSuccessEvent::dispatch($request)
: TandaRequestFailedEvent::dispatch($request);
}
}
Loading

0 comments on commit 3429e21

Please sign in to comment.