To interact with the Kraken API, you will need to create an API key through your Kraken account and then use that key to send signed requests. In PHP, you can construct the API-Signature required for authentication.
Here’s a basic example of how to sign a request to the Kraken API using PHP:
### Step 1: Generate API Key
1. Log into your Kraken account.
2. Go to "API" in your account settings.
3. Generate a new API key with the appropriate permissions for your needs.
### Step 2: Prepare PHP Code
Here is an example of how you might implement the `API-Sign` in PHP:
```php
<?php
function kraken_api_sign($urlpath, $data, $secret) {
// Encode the data
$data = http_build_query($data, '', '&');
// Create the nonce
$nonce = time();
$data = array_merge(['nonce' => $nonce], $data);
// Create the post data
$postdata = http_build_query($data);
// Create the API signature
$path = '/' . $urlpath;
$nonce = time(); // Use a new nonce
$encoded = base64_encode(hash_hmac('sha512', $path . hash('sha256', $nonce . $postdata, true), base64_decode($secret), true));
return $encoded;
}
// Your API key and secret from the Kraken account
$apiKey = 'your_api_key';
$apiSecret = 'your_api_secret';
// Define the API endpoint and parameters
$urlpath = '0/private/Balance'; // Example endpoint
$data = [];
// Call the function to get the signature
$signature = kraken_api_sign($urlpath, $data, $apiSecret);
// Prepare the headers
$headers = [
'API-Key: ' . $apiKey,
'API-Sign: ' . $signature,
];
// Initialize cURL
$ch = curl_init('https://api.kraken.com/' . $urlpath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute the request
$response = curl_exec($ch);
curl_close($ch);
// Output the response
echo $response;
?>
```
### A Breakdown of the Code:
- **Nonce Generation**: A nonce is a number used once, which is required for each API call to prevent replay attacks. In this sample, a simple timestamp is used, but you might want a counter or a way to ensure uniqueness.
- **Signature Creation**:
- The path of the API endpoint is concatenated with a HMAC of the `nonce` and the encoded post data.
- `base64_encode` is used to encode the HMAC result.
- **HTTP Request**: Uses cURL to send an authenticated request with the generated headers.
### Important Notes:
- Ensure that your server and client time are synchronized, as the nonce relies on it.
- Check Kraken's API documentation for the latest and specific details for your endpoints: [Kraken API Documentation](https://docs.kraken.com/rest/)
- Make sure to handle errors and responses adequately in production code.
With this setup, you should be able to interact with the Kraken API securely using PHP.