Skip to content

Instantly share code, notes, and snippets.

@erdum
Created February 10, 2026 19:46
Show Gist options
  • Select an option

  • Save erdum/49b0e21c99cf0fff4d228225d0d1b1a6 to your computer and use it in GitHub Desktop.

Select an option

Save erdum/49b0e21c99cf0fff4d228225d0d1b1a6 to your computer and use it in GitHub Desktop.
Http Client Wrapper for Calling Inter-Service API's
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
class HmacHttpClient
{
public static function request(
string $method,
string $url,
array|string|null $body = null,
array $headers = []
): Response {
$timestamp = time();
$nonce = str()->uuid()->toString();
if (is_array($body)) {
$body_payload = json_encode($body, JSON_UNESCAPED_SLASHES);
} elseif (is_string($body)) {
$body_payload = $body;
} else {
$body_payload = '';
}
$body_hash = hash('sha256', $body_payload);
$path = parse_url($url, PHP_URL_PATH) ?? '/';
$canonical = implode("\n", [
strtoupper($method),
'/' . ltrim($path, '/'),
$body_hash,
$timestamp,
$nonce,
]);
$signature = hash_hmac(
'sha256',
$canonical,
config('services.hmac.key')
);
return Http::withHeaders(array_merge([
'X-Signature' => $signature,
'X-Timestamp' => $timestamp,
'X-Nonce' => $nonce,
'Content-Type' => 'application/json',
'Accept' => 'application/json'
], $headers))
->send($method, $url, [
'body' => $body_payload,
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment