callfi_api/coinmarketcap.php
2024-06-20 23:34:56 +08:00

87 lines
2.6 KiB
PHP

<?php
function GetTokenPrice($tokenSymbol) {
// Dexscreener Search API URL
$searchApiUrl = "https://api.dexscreener.com/latest/dex/search?q=" . urlencode($tokenSymbol);
// echo $searchApiUrl;
// Initialize cURL session for the search API
$ch = curl_init();
// Set the URL and other options for the cURL session
curl_setopt($ch, CURLOPT_URL, $searchApiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the cURL session and store the result
$searchResponse = curl_exec($ch);
// Check for errors in cURL execution
if ($searchResponse === false) {
echo 'cURL Error: ' . curl_error($ch);
return null;
}
// Decode the JSON search response
$searchData = json_decode($searchResponse, true);
$pairs = $searchData['pairs'];
$highestPair = $pairs[0];
foreach($pairs as $pair){
$vol = $pair["volume"]["h24"];
$pairSymbolLow = strtolower($pair["baseToken"]["symbol"]);
$tokenSymbolLow = strtolower($tokenSymbol);
if($vol > $highestPair["volume"]["h24"] &&($pairSymbolLow == $tokenSymbolLow || $pairSymbolLow == "$".$tokenSymbolLow)){
// echo "New High" . $pair["baseToken"]["symbol"];
$highestPair =$pair;
}
}
echo json_encode($highestPair);
return $highestPair["priceUsd"];
}
function sGetTokenPrice($tokenSymbol){
$apiKey = '8faf016d-9cbd-40b3-889d-a45354621601';
// Replace with the token symbol you want to fetch (e.g., BTC, ETH, ADA)
// CoinMarketCap API endpoint
$endpoint = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';
// Parameters for the API request
$params = [
'symbol' => $tokenSymbol,
'convert' => 'USD'
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-CMC_PRO_API_KEY: ' . $apiKey,
'Accept: application/json'
]);
// Execute cURL session
$response = curl_exec($ch);
// Check for cURL errors
if(curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Close cURL session
curl_close($ch);
// Decode JSON response
$data = json_decode($response, true);
// Check if data was retrieved successfully
if(isset($data['data'][$tokenSymbol]['quote']['USD']['price'])) {
$priceUSD = $data['data'][$tokenSymbol]['quote']['USD']['price'];
return $priceUSD;
} else {
return -1;
}
}