Skip to content

Commit

Permalink
Merge pull request #12 from andrei-ghenov/feature/T-005-api-client-test
Browse files Browse the repository at this point in the history
T-005: Refactor ApiClient to use HMAC SHA256 for auth key and password hashing
  • Loading branch information
andrei-ghenov authored Mar 2, 2024
2 parents 5e73261 + 55db1f4 commit b27a3b3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
25 changes: 9 additions & 16 deletions src/Api/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ public function sendRequest(
array $data = []
): mixed {
$timestamp = gmdate('c');
$authKey = $this->generateAuthKey($timestamp);
$hashedPassword = $this->hashPassword();
$authKey = $this->generateAuthHmac($timestamp, $this->apiSecurityKey);
$hashedPassword = $this->generateAuthHmac($this->apiPassword, $authKey);

// Add authentication parameters to the request data.
$data = array_merge([
Expand All @@ -101,21 +101,14 @@ public function sendRequest(
}

/**
* Generate the authentication key using the API security key.
*/
private function generateAuthKey($timestamp): string {
return base64_encode(
hash_hmac(
'sha256', $timestamp, $this->apiSecurityKey, TRUE
)
);
}

/**
* Hash the API password using SHA256.
* Generates an HMAC SHA256 hash using the API security key.
*
* @param string $message The message to hash.
* @param string $secret The secret key for HMAC.
* @return string The base64-encoded HMAC hash.
*/
private function hashPassword(): string {
return hash('sha256', $this->apiPassword);
private function generateAuthHmac($message, $secret): string {
return base64_encode(hash_hmac('sha256', $message, $secret, true));
}

}
3 changes: 1 addition & 2 deletions src/Service/PurchaseService.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ public function __construct(ApiClient $apiClient) {
* @return array
* The purchase response.
*/
public function sendPurchase($productID, $amount, $phoneNumber, $ctid
): array {
public function sendPurchase($productID, $amount, $phoneNumber, $ctid): array {
$endpoint = 'WSSendTopUpPurchaseRequest';
$body = [
'Product' => $productID,
Expand Down

0 comments on commit b27a3b3

Please sign in to comment.