forked from bitcoinz-sites/bitcoinz-donation-page
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.php
237 lines (199 loc) · 7.7 KB
/
api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
<?php
require 'vendor/autoload.php';
use Dotenv\Dotenv;
// Load environment variables from .env file in /var/www
$dotenv = Dotenv::createImmutable('/var/www');
$dotenv->load();
const BTCZ_ADDRESSES = [
't1fHHnAXxoPWGY77sG5Zw2sFfGUTpW6BcSZ',
't1L7TtcRPKztgScLnfUToe4sa2aFKf9rQ14',
't3hTi3fXhcjgjRktoiucUKRtDXxV4GfEL1w',
];
const ETH_ADDRESS = '0x4E3154bc8691BC480D0F317E866C064cC2c9455D';
const BTC_ADDRESS = '1BzBfikDBGyWXGnPPk58nVVBppzfcGGXMx';
const BNB_ADDRESS = '0xd9fa5b8480dfc2a86488eaf500d729dd26dda981';
const LTC_ADDRESS = 'LR8bPo7NjPNRVy6nPLVgr9zHee2C7RepKA';
const USDTE_ADDRESS = '0xD36591b20f738f6929272a4391B8C133CB2e5C96';
const CACHE_PATH = __DIR__ . '/cache/';
const CACHE_DURATION = 3600; // 1 hour in seconds
function getCache($key) {
$cacheFile = CACHE_PATH . $key . '.cache';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < CACHE_DURATION) {
return json_decode(file_get_contents($cacheFile), true);
}
return false;
}
function setCache($key, $data) {
$cacheFile = CACHE_PATH . $key . '.cache';
if (file_put_contents($cacheFile, json_encode($data)) === false) {
debugLog("Failed to write cache file: " . $cacheFile);
} else {
debugLog("Cache file written: " . $cacheFile);
}
}
function debugLog($message) {
error_log(print_r($message, true));
}
function getCoinPrice($coin) {
$cacheKey = 'price_' . $coin;
$cachedData = getCache($cacheKey);
if ($cachedData !== false) {
return $cachedData; // Return cached data if available and not expired
}
$standardSymbols = [
'bitcoinz' => 'BTCZ',
'ethereum' => 'ETH',
'bitcoin' => 'BTC',
'binance' => 'BNB',
'litecoin' => 'LTC',
'tether' => 'USDT'
];
$symbol = array_key_exists($coin, $standardSymbols) ? $standardSymbols[$coin] : strtoupper($coin);
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=' . $symbol . '&convert=USD';
$headers = [
"Accepts: application/json",
"X-CMC_PRO_API_KEY: " . getenv('CMC_API_KEY')
];
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", $headers),
'timeout' => 10
]
]);
try {
$data = file_get_contents($url, false, $context);
if ($data === false) {
throw new Exception("Error fetching data from URL: " . $url);
}
$decodedData = json_decode($data, true);
if (is_null($decodedData) || !isset($decodedData['data'][$symbol])) {
throw new Exception("Invalid JSON structure or data for $symbol not found");
}
if (!isset($decodedData['data'][$symbol]['quote']['USD']['price'])) {
throw new Exception("Price for $symbol not found in response");
}
$priceData = ['error' => false, 'value' => (float) $decodedData['data'][$symbol]['quote']['USD']['price']];
setCache($cacheKey, $priceData); // Set cache here
return $priceData;
} catch (Exception $e) {
debugLog("Error in getCoinPrice for $symbol: " . $e->getMessage());
return ['error' => true, 'value' => null];
}
}
function getBtczBalance() {
debugLog("getBtczBalance called");
$total = 0;
foreach (BTCZ_ADDRESSES as $address) {
debugLog("Fetching balance for BTCZ address: " . $address);
$addressTotal = file_get_contents('https://explorer.btcz.rocks/api/addr/' . $address . '/balance');
if ($addressTotal === false) {
debugLog("Failed to fetch balance for BTCZ address: " . $address);
continue;
}
// Convert the balance to a number and log it
$addressTotal = floatval($addressTotal);
debugLog("Fetched balance for address $address: $addressTotal");
$total += $addressTotal;
}
debugLog("Total before conversion: " . $total);
// Convert total balance from satoshi to BTCZ using the correct conversion factor (1e8)
$totalInBtcz = $total / 100000000;
debugLog("Total BTCZ balance: " . $totalInBtcz);
return $totalInBtcz;
}
function getEthBalance() {
debugLog("getEthBalance called");
$url = 'https://api.etherscan.io/api?module=account&action=balance&address='. ETH_ADDRESS .'&tag=latest&apikey=' . getenv('ETH_API_KEY');
$data = file_get_contents($url);
if ($data === false) {
debugLog("Failed to fetch ETH balance");
return null;
}
$data = json_decode($data, true);
if ($data['status'] !== "1") {
debugLog("Error in ETH balance response");
return null;
}
$balanceInWei = $data['result'];
$balanceInEth = bcdiv($balanceInWei, '1000000000000000000', 18);
debugLog("ETH balance: " . $balanceInEth);
// setCache('eth-balance', $balanceInEth);
return $balanceInEth;
}
function getBtcBalance() {
debugLog("getBtcBalance called");
$data = file_get_contents('https://chainz.cryptoid.info/btc/api.dws?q=getbalance&a=' . BTC_ADDRESS);
if ($data === false) {
debugLog("Failed to fetch BTC balance");
return null;
}
// Assuming the API returns the balance in Bitcoin, not in satoshis
$balanceInBtc = floatval($data);
debugLog("BTC balance: " . $balanceInBtc);
return $balanceInBtc;
}
function getBnbBalance() {
debugLog("getBnbBalance called");
$url = 'https://api.bscscan.com/api?module=account&action=balance&address='. BNB_ADDRESS .'&tag=latest&apikey=' . getenv('BNB_API_KEY');
$data = file_get_contents($url);
if ($data === false) {
debugLog("Failed to fetch BNB balance");
return null;
}
$data = json_decode($data, true);
if ($data['status'] !== "1") {
debugLog("Error in BNB balance response");
return null;
}
$balanceInWei = $data['result'];
$balanceInBnb = bcdiv($balanceInWei, '1000000000000000000', 18);
debugLog("BNB balance: " . $balanceInBnb);
// setCache('bnb-balance', $balanceInEth);
return $balanceInBnb;
}
function getLtcBalance() {
debugLog("getLtcBalance called");
$data = file_get_contents('https://chainz.cryptoid.info/ltc/api.dws?q=getbalance&a=' . LTC_ADDRESS);
if ($data === false) {
debugLog("Failed to fetch LTC balance");
return null;
}
debugLog("LTC balance: " . $data);
// setCache('ltc-balance', $data);
return $data;
}
function getUSDTEBalance() {
debugLog("getUSDTEBalance called");
$url = 'https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=0xdac17f958d2ee523a2206206994597c13d831ec7&address=' . USDTE_ADDRESS . '&tag=latest&apikey=' . getenv('ETH_API_KEY');
$data = file_get_contents($url);
if ($data === false) {
debugLog("Failed to fetch USDTE balance");
return null;
}
$data = json_decode($data, true);
if (!isset($data['status']) || $data['status'] !== "1") {
debugLog("Error in USDTE balance response");
return null;
}
$balanceInUSDTE = bcdiv($data['result'], '1000000', 6); // Tether has 6 decimal places
debugLog("USDTE balance: " . $balanceInUSDTE);
// setCache('USDTE-balance', $balanceInUSDTE);
return $balanceInUSDTE;
}
$response = [
'btczBalance' => getBtczBalance(),
'ethBalance' => getEthBalance(),
'btcBalance' => getBtcBalance(),
'bnbBalance' => getBnbBalance(),
'ltcBalance' => getLtcBalance(),
'USDTEBalance' => getUSDTEBalance(),
'btczUsd' => getCoinPrice('bitcoinz'),
'ethUsd' => getCoinPrice('ethereum'),
'btcUsd' => getCoinPrice('bitcoin'),
'bnbUsd' => getCoinPrice('binance'),
'ltcUsd' => getCoinPrice('litecoin'),
'USDTEUsd' => getCoinPrice('tether')
];
debugLog("Response: " . json_encode($response));
echo json_encode($response);