Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[sc-7785] Add webhook signature helpers & tests #47

Merged
merged 2 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -19,6 +19,7 @@

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

/**
* Class Smartpay.
Expand Down Expand Up @@ -344,6 +345,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);
}
}