PHP
Generating Hashed Signatures for Outgoing PHP API Requests
Learn to generate cryptographically secure hashed signatures for outgoing API requests in PHP, enhancing security for interactions with third-party services.
<?php
/**
* Generates a request signature for an API call.
* Many third-party APIs (e.g., payment gateways, financial services) require
* requests to be signed to ensure authenticity and integrity.
*
* The exact signing algorithm (hash function, data to sign, key usage)
* varies greatly by API provider. This is a common pattern.
*
* @param string $secretKey Your API secret key provided by the service.
* @param array $params The request parameters that need to be signed.
* @param string $method The HTTP method (GET, POST, PUT, etc.).
* @param string $endpoint The API endpoint path (e.g., '/v1/payments').
* @return string The generated HMAC-SHA256 signature.
*/
function generateRequestSignature(string $secretKey, array $params, string $method, string $endpoint): string
{
// 1. Sort parameters alphabetically by key.
// This ensures a consistent string representation regardless of input order.
ksort($params);
// 2. Concatenate parameters into a query string format.
// Ensure values are properly encoded.
$queryString = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
// 3. Construct the "string to sign".
// This often includes the HTTP method, endpoint, and the sorted query string.
// Some APIs might include timestamps, request bodies, or other headers.
$stringToSign = sprintf(
"%s
%s
%s",
strtoupper($method),
$endpoint,
$queryString
);
// 4. Generate the HMAC-SHA256 signature.
// The secret key is used as the key for HMAC.
$signature = hash_hmac('sha256', $stringToSign, $secretKey, false); // `false` for hex output
return $signature;
}
// --- Example Usage ---
// Your secret key (should be stored securely, e.g., environment variable)
$apiSecret = 'your_api_secret_key_12345';
// The endpoint you are calling
$apiEndpoint = '/v1/orders';
// The HTTP method
$httpMethod = 'POST';
// Request parameters (e.g., data to send in the request body or query)
$requestParams = [
'orderId' => 'ORD-XYZ-789',
'amount' => 100.50,
'currency' => 'USD',
'timestamp' => time(), // Often required to prevent replay attacks
'callbackUrl' => 'https://your-app.com/webhook/order-status',
];
$signature = generateRequestSignature($apiSecret, $requestParams, $httpMethod, $apiEndpoint);
echo "String to sign example (based on this snippet's logic):
";
echo sprintf("%s
%s
%s", strtoupper($httpMethod), $apiEndpoint, http_build_query($requestParams, '', '&', PHP_QUERY_RFC3986)) . "
";
echo "Generated API Signature: " . $signature . "
";
// --- How you might use it in an actual API call (e.g., with cURL) ---
$url = 'https://api.example.com' . $apiEndpoint;
$headers = [
'Content-Type: application/json',
'X-API-Signature: ' . $signature,
'X-API-Key: some_public_api_key', // If you have a public API key too
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
curl_setopt(CURLOPT_POSTFIELDS, json_encode($requestParams));
curl_setopt(CURLOPT_RETURNTRANSFER, true);
curl_setopt(CURLOPT_HTTPHEADER, $headers);
// $response = curl_exec($ch);
// $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// curl_close($ch);
// echo "API Response Code: " . $httpcode . "
";
// echo "API Response Body: " . $response . "
";
?>
How it works: This PHP snippet provides a reusable function for generating cryptographically hashed signatures for outgoing API requests. Many third-party APIs require such signatures as part of their security model to verify the authenticity of the sender and ensure the request data hasn't been tampered with in transit. The `generateRequestSignature` function takes a secret key, request parameters, HTTP method, and endpoint. It consistently formats these inputs (e.g., by sorting parameters and concatenating them), then uses `hash_hmac` with SHA256 to create a signature. This signature is typically sent in a custom HTTP header (like `X-API-Signature`) alongside the request, allowing the receiving API to validate the request.