PHP调用Tron API:交易前获取销毁TRX数量及网络手续费
基于PHP的Tron链相关功能实现
1. 获取已销毁TRX数量
TRX的已销毁总量对应链上官方销毁地址的余额,可通过调用TronGrid API获取该地址余额并转换为TRX单位:
<?php // TRX官方销毁地址 $burnAddress = 'TQAE8gVWWPep8pc4fzc1wW4kmpzBeRrV2b'; // TronGrid公开API端点 $apiUrl = "https://api.trongrid.io/v1/accounts/{$burnAddress}"; // 发起请求 $ch = curl_init($apiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); // 解析并转换单位(1 TRX = 1,000,000 SUN) if (isset($data['data'][0]['balance'])) { $burnedTrx = bcdiv($data['data'][0]['balance'], 1000000, 6); echo "已销毁TRX数量: {$burnedTrx} TRX"; } else { echo "获取已销毁TRX数量失败,请检查API请求"; } ?>
2. 模拟Trust Wallet的交易手续费计算
TRX转账手续费由Gas Limit和Gas Price共同决定,普通TRX转账的Gas Limit为固定值,Gas Price可通过API获取当前链上建议值,以下是完整的表单交互实现:
<?php $networkFee = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 接收表单输入 $senderAddress = trim($_POST['sender_address']); $sendAmount = trim($_POST['send_amount']); // 1. 获取当前链上Gas价格(单位:SUN) $gasPriceApi = 'https://api.trongrid.io/wallet/getgasprice'; $ch = curl_init($gasPriceApi); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $gasPriceRes = curl_exec($ch); curl_close($ch); $gasPriceData = json_decode($gasPriceRes, true); $gasPrice = $gasPriceData['gas_price'] ?? 100; // 接口失败时使用默认值100 SUN // 2. 普通TRX转账的Gas Limit(无备注用21000,带备注建议用25000) $gasLimit = 21000; // 3. 计算手续费并转换为TRX $feeSun = bcmul($gasLimit, $gasPrice, 0); $feeTrx = bcdiv($feeSun, 1000000, 3); // 保留3位小数 $networkFee = "Network Fee: ~{$feeTrx} TRX"; } ?> <!-- 用户交互表单 --> <form method="POST"> <div> <label>发送方钱包地址:</label> <input type="text" name="sender_address" placeholder="例如:TXxxxx..." required> </div> <div> <label>发送TRX数量:</label> <input type="number" name="send_amount" step="0.001" placeholder="例如:100" required> </div> <button type="submit">继续</button> </form> <!-- 显示手续费结果 --> <?php if (!empty($networkFee)): ?> <p><?php echo $networkFee; ?></p> <?php endif; ?>
注意事项
- 若API请求频率受限,可前往TronGrid申请免费API密钥,添加
TRON-PRO-API-KEY: 你的密钥到请求头中 - 带备注的TRX转账需要提高Gas Limit至25000左右,可根据实际场景调整
- 手续费为近似值,链上Gas Price可能实时波动,因此用
~标记近似值
内容的提问来源于stack exchange,提问作者The Edward
相关产品推荐
相关产品推荐

