接入教程
1. 访问Etherscan官网并注册账户
2. 在API设置页面申请免费API密钥
3. 查阅API文档了解可用端点
4. 使用密钥通过HTTP请求调用接口
5. 解析返回的JSON数据并集成到应用中
Python示例:获取以太坊账户余额
python
import requests
url = "https://api.etherscan.io/api"
params = {
"module": "account",
"action": "balance",
"address": "0x1234567890123456789012345678901234567890",
"tag": "latest",
"apikey": "YOUR_API_KEY"
}
response = requests.get(url, params=params)
data = response.json()
if data["status"] == "1":
print(f"Balance: {int(data['result']) / 10**18} ETH")
else:
print(f"Error: {data['message']}")
PHP示例:获取最新区块号
php
<?php
$url = "https://api.etherscan.io/api";
$params = [
"module" => "proxy",
"action" => "eth_blockNumber",
"apikey" => "YOUR_API_KEY"
];
$ch = curl_init($url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data["result"])) {
echo "Latest block number: " . hexdec($data["result"]) . "\n";
} else {
echo "Error: " . $data["message"] . "\n";
}
?>
JavaScript示例:查询交易详情
javascript
const axios = require('axios');
async function getTransaction() {
const url = "https://api.etherscan.io/api";
const params = {
module: "proxy",
action: "eth_getTransactionByHash",
txhash: "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
apikey: "YOUR_API_KEY"
};
try {
const response = await axios.get(url, { params });
const data = response.data;
if (data.status === "1") {
console.log("Transaction details:", data.result);
} else {
console.log("Error:", data.message);
}
} catch (error) {
console.error("Request failed:", error);
}
}
getTransaction();
常见问题
如何获取Etherscan API密钥?
访问Etherscan官网(https://etherscan.io/apis),注册账户后登录,在API页面点击"Create Free API Key"按钮即可生成密钥。免费版有每日请求限制,可根据需求升级套餐。
Etherscan API支持哪些类型的查询?
Etherscan API支持账户余额、交易记录、智能合约事件日志、区块信息、Gas价格、代币信息、验证节点数据等多种查询,涵盖以太坊生态大部分链上数据需求。
API请求频率有限制吗?
是的,免费API密钥有请求频率限制(通常为每秒5次),付费套餐可提高限制。建议在代码中添加适当的延迟和错误处理,避免因超限导致请求失败。
Aitishiku.com