Merge branch 'signature' into future-public

This commit is contained in:
mahdi msr 2025-09-28 13:24:08 +03:30
commit bea493935b
3 changed files with 98 additions and 5 deletions

50
src/Requests/Header.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace Msr\LaravelBitunixApi\Requests;
class Header
{
public static function sortQueryParameters(array $parameters): ?array
{
$sortableParameters = $parameters;
if (!count($sortableParameters)) {
return [];
}
ksort($sortableParameters, SORT_LOCALE_STRING);
return $sortableParameters;
}
public static function digestQueryParameters(array $parameters): ?string
{
if (!count($parameters)) {
return null;
}
$sortedParameters = self::sortQueryParameters($parameters);
return implode('', array_map(
fn($k, $v) => $k . $v,
array_keys($sortedParameters),
array_values($sortedParameters)
));
}
public static function generateNonce(): ?string
{
return md5(uniqid(mt_rand(), true));
}
public static function generateSignValue(array $queryParams = [], string $body = '', string $randomNonce = ''): string
{
$apiKey = config('bitunix-api.api_key');
$apiSecret = config('bitunix-api.api_secret');
$timeStamp = (string)round(microtime(true) * 1000);
$digestedQueryParam = self::digestQueryParameters($queryParams);
$digestedHeader = $randomNonce . $timeStamp . $apiKey . $digestedQueryParam . $body;
$hash = hash('sha256', $digestedHeader);
$sign = $hash . $apiSecret;
return hash('sha256', $sign);
}
}

48
tests/AuthHeaderTest.php Normal file
View File

@ -0,0 +1,48 @@
<?php
use Msr\LaravelBitunixApi\Requests\Header;
it('sort query parameters', function () {
$emptyQuery = Header::sortQueryParameters([]);
expect($emptyQuery)->toBeEmpty();
$params = [
'z_index' => 'z value',
'a_index' => 'a value',
'b_index' => 'b value',
];
$sortedParams = Header::sortQueryParameters($params);
expect($sortedParams)
->toMatchArray([
'a_index' => 'a value',
'b_index' => 'b value',
'z_index' => 'z value',
]);
});
it('get sorted query params as string value', function () {
$digestedParam = Header::digestQueryParameters([]);
expect($digestedParam)->toBeNull();
$params = [
'z_index' => 'z_value',
'a_index' => 'a_value',
'b_index' => 'b_value',
];
$sortedParams = Header::digestQueryParameters($params);
expect($sortedParams)->toEqual('a_indexa_valueb_indexb_valuez_indexz_value');
});
it('get some random string 32 bit', function () {
$firstRandom = Header::generateNonce();
$secondRandom = Header::generateNonce();
expect($firstRandom)
->toBeString()
->toHaveLength(32)
->not()->toEqual($secondRandom)
->not()->toBeNull();
});

View File

@ -1,5 +0,0 @@
<?php
it('can test', function () {
expect(true)->toBeTrue();
});