PHP

PHP Code to Fetch current Coinbase Assets (Balances)

CK CK 3788 
Created at
Updated at  
438 0 0

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

  1. Authentication:
    • The CB-ACCESS-KEY, CB-ACCESS-SIGN, and CB-ACCESS-TIMESTAMP headers are required for Coinbase API authentication.
  2. HMAC Signature:
    • The signature is generated by hashing the timestamp, HTTP method, and request path together using the API secret.
  3. Request Path:
    • /v2/accounts fetches the balances of all assets in your account.
  4. Error Handling:
    • If the HTTP response code is not 200, the script outputs an error message.
  5. 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"}]}
Tags Coinbase Coinbase API Coinbase Assets Coinbase Balances Facebook X
Comments 0
Similar posts
  1. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    362
  2. Coinbase Python API - Basic Example
    461
  1. When you Postgresql Module is not able to open connection : Doubt your libpq version
    472
  2. How to Get a YouTube Channel ID from a URL in PHP
    1,014
  3. Building a MCP server in PHP
    627
  4. PHP 7 vs PHP 8
    1,240
  5. Upgrading PHP 7.4 to PHP 8.1 in CentOS 7
    642
  6. gRPC Server with PHP
    499
  7. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    362
  8. Google Single Sign-On implementation with PHP
    1,367
  9. PHP Superglobal Variables do not require additional syntax to access it
    2,617
  10. Run Python Code with Virtual Environment in PHP
    671
  11. PHP Simplified Operators
    317
  12. PHP Heredoc (aka Nowdoc)
    428
  13. PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics
    1,800
  14. WordPress Remote Posting with PHP
    1,675
  15. Google BigQuery Example to converted Nested FIelds in JSON
    458
  16. Verifying Apple In-App Purchase validation receipt with PHP
    1,779
  17. Useful code for file-based Unit Test in PHP
    498
  18. Function Overloading Implementation in PHP with Magic Mathods
    1,753
  19. PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL
    1,666
  20. How do I find php.ini on Mac?
    491
  21. Mastering Excel Data Importation in PHP
    553
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,728
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252