Created
February 10, 2026 19:46
-
-
Save erdum/49b0e21c99cf0fff4d228225d0d1b1a6 to your computer and use it in GitHub Desktop.
Http Client Wrapper for Calling Inter-Service API's
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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