| Below is a PHP implementation to fetch your current assets (balances) from the Coinbase API using authenticated requests: PHP Code: Fetch Current Assets <?php
// Coinbase API credentials
$apiKey = 'your_api_key';
$apiSecret = 'your_api_secret';
// API endpoint and request method
$method = 'GET';
$requestPath = '/v2/accounts';
$baseUrl = 'https://api.coinbase.com';
// Current timestamp
$timestamp = time();
// Message to sign
$message = $timestamp . $method . $requestPath;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $message, $apiSecret);
// Prepare headers
$headers = [
'CB-ACCESS-KEY: ' . $apiKey,
'CB-ACCESS-SIGN: ' . $signature,
'CB-ACCESS-TIMESTAMP: ' . $timestamp,
'Content-Type: application/json',
];
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseUrl . $requestPath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute the API call
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Handle response
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "Your current assets:\n";
foreach ($data['data'] as $account) {
echo $account['currency'] . ": " . $account['balance']['amount'] . "\n";
}
} else {
echo "Failed to fetch assets. HTTP Code: $httpCode\nResponse: $response\n";
}
?>
Explanation of the Code - Authentication:
- The
CB-ACCESS-KEY, CB-ACCESS-SIGN, and CB-ACCESS-TIMESTAMP headers are required for Coinbase API authentication.
- HMAC Signature:
- The signature is generated by hashing the
timestamp, HTTP method, and request path together using the API secret.
- Request Path:
/v2/accounts fetches the balances of all assets in your account.
- Error Handling:
- If the HTTP response code is not
200, the script outputs an error message.
- Output:
- For each account, it prints the currency code and the balance.
Example Output If the API call is successful: Your current assets:
BTC: 0.01234567
ETH: 2.50000000
USD: 150.00
If there's an issue (e.g., invalid API key): Failed to fetch assets. HTTP Code: 401
Response: {"errors":[{"id":"authentication_error","message":"Invalid API Key"}]}
|