CatFee.IO
中文
中文
  • 简介
  • 开始使用
    • 快速开始指南
    • 直接转账购买能量
    • DApp购买能量
    • 通过 API购买能量
      • API概览
      • Java调用示例
      • Python 调用示例
      • PHP 调用示例
      • Node.js 调用示例
      • Go 调用示例
    • API支持幂等请求
    • 能量转租服务
    • 速充能量服务
    • 💎电报会员转卖
    • 一单一支付解决方案
    • 区块链监控
    • 波场节点连接指南
    • API常见问题
    • 服务条款
  • API参考文档
    • 账户信息
    • 购买能量
    • 订单详情
    • 预估价格
    • 购买电报会员
  • 能量知识库
    • 什么是波场能量?
    • 为什么要租赁能量?
    • 如何解决“OUT OF ENERGY” 错误?
    • 为什么不能用中心化交易所的钱包购买能量?
    • 什么是中心化交易所?
    • 波场上转USDT需要多少能量?
    • 已经租赁了能量,为什么转账还是失败?
  • 为什么有些能量租赁特别便宜?
  • 波场能量租赁10常见问题
  • Trx能量机器人
    • 如何申请 Telegram 机器人并在 CatFee 上托管
Powered by GitBook
On this page
  • 前提条件
  • 示例代码
  • 代码解析
  • 注意事项
  • 总结

Was this helpful?

  1. 开始使用
  2. 通过 API购买能量

Python 调用示例

Python 调用 CatFee.IO Rest API 示例

PreviousJava调用示例NextPHP 调用示例

Last updated 6 days ago

Was this helpful?

前提条件

  1. 。

  2. 确保您的环境已安装 requests 库,可以使用以下命令安装:

    pip install requests
  3. 使用 Python 3.6 及以上版本。

示例代码

import hashlib
import hmac
import base64
import time
import requests
from urllib.parse import urlencode

API_KEY = "your_api_key"  # 请替换为您的API Key
API_SECRET = "your_api_secret"  # 请替换为您的API Secret
BASE_URL = "https://api.catfee.io"

def generate_timestamp():
    """生成当前的时间戳(ISO 8601格式)"""
    return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())

def build_request_path(path, query_params):
    """构建请求路径,包括查询参数"""
    if not query_params:
        return path
    query_string = urlencode(query_params)
    return f"{path}?{query_string}"

def generate_signature(timestamp, method, request_path):
    """生成签名"""
    sign_string = timestamp + method + request_path
    return hmac_sha256(sign_string, API_SECRET)

def hmac_sha256(data, secret):
    """使用 HMAC-SHA256 算法生成签名"""
    return base64.b64encode(hmac.new(secret.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).digest()).decode()

def create_request(url, method, timestamp, signature):
    """创建 HTTP 请求"""
    headers = {
        "Content-Type": "application/json",
        "CF-ACCESS-KEY": API_KEY,
        "CF-ACCESS-SIGN": signature,
        "CF-ACCESS-TIMESTAMP": timestamp,
    }
    
    if method == "POST":
        response = requests.post(url, headers=headers)
    elif method == "GET":
        response = requests.get(url, headers=headers)
    elif method == "PUT":
        response = requests.put(url, headers=headers)
    elif method == "DELETE":
        response = requests.delete(url, headers=headers)
    else:
        raise ValueError(f"Unsupported HTTP method: {method}")
    
    return response

def main():
    method = "POST"  # 可以修改为 "GET", "PUT", "DELETE" 等方法
    path = "/v1/order"
    
    # 示例:创建订单
    query_params = {
        "quantity": "65000",
        "receiver": "TRON_ADDRESS",
        "duration": "1h"
    }
    
    # 生成请求头
    timestamp = generate_timestamp()
    request_path = build_request_path(path, query_params)
    signature = generate_signature(timestamp, method, request_path)
    
    # 创建请求 URL
    url = BASE_URL + request_path
    
    # 发送请求
    response = create_request(url, method, timestamp, signature)
    
    # 打印响应
    print("Response Code:", response.status_code)
    print("Response Body:", response.text)
    
    # 处理可能的错误信息
    if response.status_code != 200:
        print("Error:", response.json())

if __name__ == "__main__":
    main()

代码解析

  1. generate_timestamp(): 生成当前的 UTC 时间戳(ISO 8601 格式)。使用 time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) 生成时间戳。

  2. build_request_path(): 该函数接收 path 和查询参数(query_params),并构建包含查询参数的完整请求路径。如果没有查询参数,直接返回 path。

  3. generate_signature(): 使用 timestamp、method 和 request_path 拼接成签名字符串,然后调用 hmac_sha256() 来生成签名。

  4. hmac_sha256(): 使用 HMAC-SHA256 算法生成签名,使用 API Secret 作为密钥进行加密,并对结果进行 Base64 编码。

  5. create_request(): 根据 HTTP 方法(POST、GET、PUT、DELETE)发送请求。通过 requests 库创建 HTTP 请求并返回响应。

  6. main(): 在 main() 函数中,设置请求方法为 POST,构建查询参数,生成时间戳、签名和请求路径,最终发送请求并打印响应。

注意事项

  • API Key 和 Secret: 请确保将 API_KEY 和 API_SECRET 替换为您从 CatFee.IO 获取的实际值。

  • 错误处理: 示例代码中处理了请求失败的情况,如果响应码不为 200,会打印错误信息。

  • 请求方法: 支持 POST、GET、PUT 和 DELETE 请求,您可以根据实际需求修改请求方法。

总结

此示例展示了如何使用 Python 调用 CatFee.IO Rest API,利用 HMAC-SHA256 签名确保请求的安全性。您可以根据需要调整代码,支持 GET、POST、PUT 和 DELETE 等 HTTP 方法。

您需要一个有效的 API Key 和 API Secret