Skip to content

Commit

Permalink
[sc-7785] Add webhook signature helpers & tests (#47)
Browse files Browse the repository at this point in the history
* Add webhook signature helpers & tests

Signed-off-by: Ash Wu <hsatac@gmail.com>

* Make php-cs-fixer happy

Signed-off-by: Ash Wu <hsatac@gmail.com>

---------

Signed-off-by: Ash Wu <hsatac@gmail.com>
  • Loading branch information
hSATAC authored Feb 6, 2023
1 parent bb6175f commit c495a16
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"php": ">= 5.6",
"guzzlehttp/guzzle": ">=6.5",
"ircmaxell/random-lib": "^1.2",
"caseyamcl/guzzle_retry_middleware": "^2.2"
"caseyamcl/guzzle_retry_middleware": "^2.2",
"tuupola/base62": ">= 1.0"
},
"require-dev": {
"phpunit/phpunit": ">= 5.7",
Expand Down
17 changes: 17 additions & 0 deletions src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

use Smartpay\Responses\Base as BaseResponse;
use Smartpay\Responses\CheckoutSession as CheckoutSessionResponse;
use Tuupola\Base62;

/**
* Class Smartpay.
Expand Down Expand Up @@ -383,6 +384,22 @@ public function disableToken($params, $idempotencyKey = null)
);
}

/**
* Webhook Signature Helpers
*/

public function calculateWebhookSignature($data)
{
$base62 = new Base62(["characters" => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789']);
return hash_hmac('sha256', $data, $base62->decode(Smartpay::getSecretKey()));
}

public function validateWebhookSignature($data, $signature, $signatureTimestamp)
{
$calculatedSignature = $this->calculateWebhookSignature($signatureTimestamp . '.' . $data);
return $signature === $calculatedSignature;
}

/**
* @param $params
* @return array
Expand Down
18 changes: 18 additions & 0 deletions tests/ApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,22 @@ public function testGetOrders()
$api = new Api('sk_test_mock', 'pk_test_mock', $client);
$this->assertSame([], $api->getOrders()->asJson());
}

public function testCalculateWebhookSignature()
{
$api = new Api('MOCKSECRETKEY');
$calculatedSignature = $api->calculateWebhookSignature("test data");
$this->assertEquals('ae82b27dd6dafd0dbfc65faff07160833776cf60915782ef991557e51e4d1782', $calculatedSignature);
}

public function testValidateWebhookSignature()
{
$api = new Api('MOCKSECRETKEY');
$signatureValid = $api->validateWebhookSignature(
"test data",
"30f01ff4be78d2a2b053ad4a7922c4b4eb2aee75aa5326f2c9b84b52fe4e620e",
"test timestamp"
);
$this->assertEquals(true, $signatureValid);
}
}

0 comments on commit c495a16

Please sign in to comment.