# 使用 API 密钥通过 API 购买能源

如何获取api密钥

[选项 1：在 Tronsave 网站上生成 API 密钥。](https://docs.tronsave.io/chinese/developer/get-api-key/on-the-website)

[选项 2：在 Telegram 上生成 API 密钥。](https://docs.tronsave.io/chinese/developer/get-api-key/on-telegram)

**要求：TronWeb 版本 5.3.2**

npm i tronweb\@5.3.2 @noble/secp256k1\@1.7.1

(了解更多：<https://tronweb.network/docu/docs/5.3.2/Release%20Note/>)

{% tabs %}
{% tab title="Javascript" %}

```javascript
const API_KEY = `your_api_key`; // 请更改此处
const TRONSAVE_API_URL = "https://api.tronsave.io" // 在测试网络模式下更改为 "https://api-dev.tronsave.io"
const RECEIVER_ADDRESS = 'your_receiver_address' // 请更改此处
const BUY_AMOUNT = 100000 // 请更改此处
const DURATION = 3600 * 1000 // 当前值：1小时，请更改此处
const MAX_PRICE_ACCEPTED = 100 // 请更改此处

const sleep = async (ms) => {
    await new Promise((resolver, reject) => {
        setTimeout(() => resolver("OK"), ms)
    })
}

const GetOrderBook = async (api_key, receiver_address) => {
    const url = `${TRONSAVE_API_URL}/v0/order-book?address=${receiver_address}`
    const data = await fetch(url, {
        headers: {
            'apikey': api_key
        }
    })
    const response = await data.json()
    /**
     * 示例响应 
     * @link https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/get-order-book
      [
        {
            "price": -1,
            "available_energy_amount": 177451
        },
        {
            "price": 30,
            "available_energy_amount": 331088
        },
        {
            "price": 35,
            "available_energy_amount": 2841948
        },
    ]
     */
    return response
}

const GetAccountInfo = async (api_key) => {
    const url = `${TRONSAVE_API_URL}/v0/user-info`
    const data = await fetch(url, {
        headers: {
            'apikey': api_key
        }
    })
    const response = await data.json()
    /**
     * 示例响应 
     * @link https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/get-internal-account-info
    {
        "id": "user_id",
        "balance": "1000000",
        "represent_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        "deposit_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
    }
     */
    return response
}


const BuyEnergy = async (api_key, target_address, amount, duration_ms, max_price_accepted) => {
    const url = `${TRONSAVE_API_URL}/v0/internal-buy-energy`
    // 更多信息请参见 https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
    const body = {
        "resource_type": "ENERGY",
        "buy_energy_type": "MEDIUM", // 价格以 sun 计，或者使用 "SLOW"|"MEDIUM"|"FAST"
        "amount": amount, // 想要购买的资源量
        "allow_partial_fill": true,
        "target_address": target_address,
        "duration_millisec": duration_ms, // 订单持续时间（毫秒）。默认值：259200000（3天）
        "only_create_when_fulfilled": false,
        "max_price_accepted": max_price_accepted,
        "add_order_incomplete": false
    }
    const data = await fetch(url, {
        method: "POST",
        headers: {
            'apikey': api_key,
            "content-type": "application/json",
        },
        body: JSON.stringify(body)
    })
    const response = await data.json()
    /**
     * 示例响应 
     * @link  https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/buy-energy
   {
      "order_id": "651d2306e55c073f6ca0992e",
      "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
      "resource_amount": 100000,
      "resource_type": "ENERGY",
      "remain_amount": 0,
      "price": 67.5,
      "duration": 3600,
      "allow_partial_fill": true,
      "payout_amount": 6750000,
      "fulfilled_percent": 100
}
     */
    return response
}

const GetOneOrderDetails = async (api_key, order_id) => {
    const url = `${TRONSAVE_API_URL}/v0/orders/${order_id}`
    const data = await fetch(url, {
        headers: {
            'apikey': api_key
        }
    })
    const response = await data.json()
    /**
     * 示例响应 
     * @link https://docs.tronsave.io/buy-energy-on-telegram/using-api-key-to/get-internal-account-order-history
        {
            "id": "651d2306e55c073f6ca0992e",
            "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
            "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
            "resource_amount": 100000,
            "resource_type": "ENERGY",
            "remain_amount": 0,
            "price": 67.5,
            "duration": 3600,
            "allow_partial_fill": true,
            "payout_amount": 6750000,
            "fulfilled_percent": 100,
            "matched_delegates": [
                        {
                            "delegator": "TKVSaJQDWeKFSEXmA44pjxduGTxy888888",
                            "amount": 100000,
                            "txid": "transaction_id_1"
                        }
                    ]
        }
     */
    return response
}

const CreateOrderByUsingApiKey = async () => {
    // 检查可用能量
    const order_book = await GetOrderBook(API_KEY, RECEIVER_ADDRESS)
    console.log(order_book)
    /*
      [
        {
            "price": -1,
            "available_energy_amount": 177451
        },
        {
            "price": 30,
            "available_energy_amount": 331088
        },
        {
            "price": 35,
            "available_energy_amount": 2841948
        },
    ]
    */
    // 查看上面的响应，我们有 177k 能量，价格低于 30，有 331k 能量，价格为 30，有 2841k 能量，价格为 35
    // 例如，如果要在 3 天内购买 500k 能量，则必须以至少 35 能量的价格下单以完成订单（如果订单持续时间少于 3 天，则价格可能更高）

    const need_trx = MAX_PRICE_ACCEPTED * BUY_AMOUNT

    // 检查内部余额是否足够购买
    const account_info = await GetAccountInfo(API_KEY)
    console.log(account_info)
    /*
     {
        "id": "user_id",
        "balance": "1000000",
        "represent_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        "deposit_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
    }
    */
    const is_balance_enough = Number(account_info.balance) >= need_trx
    if (is_balance_enough) {

        const buy_energy_order = await BuyEnergy(API_KEY, RECEIVER_ADDRESS, BUY_AMOUNT, DURATION, MAX_PRICE_ACCEPTED)
        console.log(buy_energy_order)
        /*
          {
          "order_id": "651d2306e55c073f6ca0992e",
          "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
          "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
          "resource_amount": 100000,
          "resource_type": "ENERGY",
          "remain_amount": 0,
          "price": 67.5,
          "duration": 3600,
          "allow_partial_fill": true,
          "payout_amount": 6750000,
          "fulfilled_percent": 100
        }
        */
        // 购买后等待 3-5 秒，然后检查
        if (buy_energy_order.order_id) {
            while (true) {
                await sleep(3000)
                const order_details = await GetOneOrderDetails(API_KEY, buy_energy_order.order_id)
                console.log(order_details)
                /*
                    {
                        "id": "651d2306e55c073f6ca0992e",
                        "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
                        "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
                        "resource_amount": 100000,
                        "resource_type": "ENERGY",
                        "remain_amount": 0,
                        "price": 67.5,
                        "duration": 3600,
                        "allow_partial_fill": true,
                        "payout_amount": 6750000,
                        "fulfilled_percent": 100,
                        "matched_delegates": [
                                    {
                                        "delegator": "TKVSaJQDWeKFSEXmA44pjxduGTxy888888",
                                        "amount": 100000,
                                        "txid": "transaction_id_1"
                                    }
                                ]
                    }
                */
                if (order_details && order_details.fulfilled_percent === 100 || order_details.remain_amount === 0) {
                    console.log(`您的订单已经完成`)
                    break;
                } else {
                    console.log(`您的订单尚未完成，请等待 3 秒后重新检查`)
                }
            }
        } else {
            console.log({ buy_energy_order })
            throw new Error(`购买订单失败`)
        }
    }
}

CreateOrderByUsingApiKey()

```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class Main {
    static final String API_KEY = "your_api_key"; // 更改我
    static final String TRONSAVE_API_URL = "https://api.tronsave.io"; // 在测试网模式下更改为 "https://api-dev.tronsave.io"
    static final String RECEIVER_ADDRESS = "your_receiver_address"; // 更改我
    static final int BUY_AMOUNT = 100000; // 更改我
    static final long DURATION = 3600 * 1000; // 当前值: 1小时。更改我
    static final int MAX_PRICE_ACCEPTED = 100; // 更改我

    public static void main(String[] args) {
        try {
            createOrderByUsingApiKey();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void createOrderByUsingApiKey() throws IOException {
        // 检查可用能量
        String orderBookJson = getOrderBook(API_KEY, RECEIVER_ADDRESS);
        System.out.println(orderBookJson);

        // 查看上面的响应，我们有 177k 能量，价格低于 30，331k 能量，价格为 30，以及 2841k 能量，价格为 35
        // 例如，如果您想在 3 天内购买 500k 能量，则必须以至少 35 能量的价格下订单，以满足您的订单
        // （如果订单持续时间少于 3 天，则价格可能更高）

        int needTrx = MAX_PRICE_ACCEPTED * BUY_AMOUNT;

        // 检查您的内部余额是否足够购买
        String accountInfoJson = getAccountInfo(API_KEY);
        System.out.println(accountInfoJson);

        // 解析 JSON 以检查余额是否足够
        // 在这里，您需要实现 JSON 解析

        // 假设余额检查成功，继续购买能量
        String buyEnergyOrderJson = buyEnergy(API_KEY, RECEIVER_ADDRESS, BUY_AMOUNT, DURATION, MAX_PRICE_ACCEPTED);
        System.out.println(buyEnergyOrderJson);

        // 购买后等待 3-5 秒，然后检查
        // 在这里，您需要实现等待机制

        // 假设订单已完成，您将收到类似以下内容的响应：
        // {
        //    "order_id": "651d2306e55c073f6ca0992e",
        //    "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        //    "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        //    "resource_amount": 100000,
        //    "resource_type": "ENERGY",
        //    "remain_amount": 0,
        //    "price": 67.5,
        //    "duration": 3600,
        //    "allow_partial_fill": true,
        //    "payout_amount": 6750000,
        //    "fulfilled_percent": 100
        // }

        // 在这里，您需要实现逻辑以持续检查订单状态直到完成
    }

    static String getOrderBook(String apiKey, String receiverAddress) throws IOException {
        URL url = new URL(TRONSAVE_API_URL + "/v0/order-book?address=" + receiverAddress);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("apikey", apiKey);
        conn.connect();
        Scanner scanner = new Scanner(conn.getInputStream());
        StringBuilder response = new StringBuilder();
        while (scanner.hasNextLine()) {
            response.append(scanner.nextLine());
        }
        return response.toString();
    }

    static String getAccountInfo(String apiKey) throws IOException {
        URL url = new URL(TRONSAVE_API_URL + "/v0/user-info");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("apikey", apiKey);
        conn.connect();
        Scanner scanner = new Scanner(conn.getInputStream());
        StringBuilder response = new StringBuilder();
        while (scanner.hasNextLine()) {
            response.append(scanner.nextLine());
        }
        return response.toString();
    }

    static String buyEnergy(String apiKey, String targetAddress, int amount, long durationMs, int maxPriceAccepted) throws IOException {
        URL url = new URL(TRONSAVE_API_URL + "/v0/internal-buy-energy");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("apikey", apiKey);
        conn.setRequestProperty("content-type", "application/json");
        conn.setDoOutput(true);
        String body = "{\n" +
                "        \"resource_type\": \"ENERGY\",\n" +
                "        \"buy_energy_type\": \"MEDIUM\",\n" +
                "        \"amount\": " + amount + ",\n" +
                "        \"allow_partial_fill\": true,\n" +
                "        \"target_address\": \"" + targetAddress + "\",\n" +
                "        \"duration_millisec\": " + durationMs + ",\n" +
                "        \"only_create_when_fulfilled\": false,\n" +
                "        \"max_price_accepted\": " + maxPriceAccepted + ",\n" +
                "        \"add_order_incomplete\": false\n" +
                "    }";
        conn.getOutputStream().write(body.getBytes());
        conn.connect();
        Scanner scanner = new Scanner(conn.getInputStream());
        StringBuilder response = new StringBuilder();
        while (scanner.hasNextLine()) {
            response.append(scanner.nextLine());
        }
        return response.toString();
    }
}

```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require 'net/http'
require 'uri'
require 'json'

API_KEY = 'your_api_key' # 更改我
TRONSAVE_API_URL = 'https://api.tronsave.io' # 在测试网模式下更改为 'https://api-dev.tronsave.io'
RECEIVER_ADDRESS = 'your_receiver_address' # 更改我
BUY_AMOUNT = 100_000 # 更改我
DURATION = 3_600 * 1_000 # 当前值: 1小时。 更改我
MAX_PRICE_ACCEPTED = 100 # 更改我

def sleep_ms(ms)
  sleep(ms / 1_000.0)
end

def get_order_book(api_key, receiver_address)
  url = URI.parse("#{TRONSAVE_API_URL}/v0/order-book?address=#{receiver_address}")
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(url)
  request['apikey'] = api_key
  response = http.request(request)
  JSON.parse(response.body)
end

def get_account_info(api_key)
  url = URI.parse("#{TRONSAVE_API_URL}/v0/user-info")
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(url)
  request['apikey'] = api_key
  response = http.request(request)
  JSON.parse(response.body)
end

def buy_energy(api_key, target_address, amount, duration_ms, max_price_accepted)
  url = URI.parse("#{TRONSAVE_API_URL}/v0/internal-buy-energy")
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(url)
  request['apikey'] = api_key
  request['content-type'] = 'application/json'
  body = {
    "resource_type": "ENERGY",
    "buy_energy_type": "MEDIUM",
    "amount": amount,
    "allow_partial_fill": true,
    "target_address": target_address,
    "duration_millisec": duration_ms,
    "only_create_when_fulfilled": false,
    "max_price_accepted": max_price_accepted,
    "add_order_incomplete": false
  }
  request.body = body.to_json
  response = http.request(request)
  JSON.parse(response.body)
end

def get_one_order_details(api_key, order_id)
  url = URI.parse("#{TRONSAVE_API_URL}/v0/orders/#{order_id}")
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(url)
  request['apikey'] = api_key
  response = http.request(request)
  JSON.parse(response.body)
end

def create_order_by_using_api_key
  # 检查可用能量
  order_book = get_order_book(API_KEY, RECEIVER_ADDRESS)
  puts order_book

  # 查看上面的响应，我们有 177k 能量，价格低于 30，331k 能量，价格为 30，以及 2841k 能量，价格为 35
  # 例如，如果您想在 3 天内购买 500k 能量，则必须以至少 35 能量的价格下订单，以满足您的订单
  # （如果订单持续时间少于 3 天，则价格可能更高）

  need_trx = MAX_PRICE_ACCEPTED * BUY_AMOUNT

  # 检查您的内部余额是否足够购买
  account_info = get_account_info(API_KEY)
  puts account_info

  # 解析 JSON 以检查余额是否足够
  # 在这里，您需要实现 JSON 解析

  # 假设余额检查成功，继续购买能量
  buy_energy_order = buy_energy(API_KEY, RECEIVER_ADDRESS, BUY_AMOUNT, DURATION, MAX_PRICE_ACCEPTED)
  puts buy_energy_order

  # 购买后等待 3-5 秒，然后检查
  # 在这里，您需要实现等待机制

  # 假设订单已完成，您将收到类似以下内容的响应：
  # {
  #    "order_id": "651d2306e55c073f6ca0992e",
  #    "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
  #    "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
  #    "resource_amount": 100000,
  #    "resource_type": "ENERGY",
  #    "remain_amount": 0,
  #    "price": 67.5,
  #    "duration": 3600,
  #    "allow_partial_fill": true,
  #    "payout_amount": 6750000,
  #    "fulfilled_percent": 100
  # }

  # 在这里，您需要实现逻辑以持续检查订单状态直到完成
end

create_order_by_using_api_key
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$API_KEY = 'your_api_key'; // 更改我
$TRONSAVE_API_URL = 'https://api.tronsave.io'; // 在测试网络模式下更改为 'https://api-dev.tronsave.io'
$RECEIVER_ADDRESS = 'your_receiver_address'; // 更改我
$BUY_AMOUNT = 100000; // 更改我
$DURATION = 3600 * 1000; // 当前值: 1小时。更改我
$MAX_PRICE_ACCEPTED = 100; // 更改我

function sleep_ms($ms) {
    usleep($ms * 1000);
}

function get_order_book($api_key, $receiver_address) {
    global $TRONSAVE_API_URL;
    $url = $TRONSAVE_API_URL . "/v0/order-book?address=" . $receiver_address;
    $options = array(
        'http' => array(
            'header' => "apikey: $api_key\r\n",
            'method' => 'GET'
        )
    );
    $context = stream_context_create($options);
    $data = file_get_contents($url, false, $context);
    return json_decode($data, true);
}

function get_account_info($api_key) {
    global $TRONSAVE_API_URL;
    $url = $TRONSAVE_API_URL . "/v0/user-info";
    $options = array(
        'http' => array(
            'header' => "apikey: $api_key\r\n",
            'method' => 'GET'
        )
    );
    $context = stream_context_create($options);
    $data = file_get_contents($url, false, $context);
    return json_decode($data, true);
}

function buy_energy($api_key, $target_address, $amount, $duration_ms, $max_price_accepted) {
    global $TRONSAVE_API_URL;
    $url = $TRONSAVE_API_URL . "/v0/internal-buy-energy";
    $body = json_encode(array(
        "resource_type" => "ENERGY",
        "buy_energy_type" => "MEDIUM",
        "amount" => $amount,
        "allow_partial_fill" => true,
        "target_address" => $target_address,
        "duration_millisec" => $duration_ms,
        "only_create_when_fulfilled" => false,
        "max_price_accepted" => $max_price_accepted,
        "add_order_incomplete" => false
    ));
    $options = array(
        'http' => array(
            'header' => "Content-type: application/json\r\n" .
                        "apikey: $api_key\r\n",
            'method' => 'POST',
            'content' => $body
        )
    );
    $context = stream_context_create($options);
    $data = file_get_contents($url, false, $context);
    return json_decode($data, true);
}

function get_one_order_details($api_key, $order_id) {
    global $TRONSAVE_API_URL;
    $url = $TRONSAVE_API_URL . "/v0/orders/" . $order_id;
    $options = array(
        'http' => array(
            'header' => "apikey: $api_key\r\n",
            'method' => 'GET'
        )
    );
    $context = stream_context_create($options);
    $data = file_get_contents($url, false, $context);
    return json_decode($data, true);
}

function create_order_by_using_api_key() {
    global $API_KEY, $RECEIVER_ADDRESS, $BUY_AMOUNT, $DURATION, $MAX_PRICE_ACCEPTED;
    // 检查可用能源
    $order_book = get_order_book($API_KEY, $RECEIVER_ADDRESS);
    print_r($order_book);
    /*
      [
        {
            "price": -1,
            "available_energy_amount": 177451
        },
        {
            "price": 30,
            "available_energy_amount": 331088
        },
        {
            "price": 35,
            "available_energy_amount": 2841948
        },
    ]
    */
    // 查看上面的响应，我们有177k能量，价格低于30，331k能量，价格为30，以及2841k能量，价格为35
    // 例如，如果您想要在3天内购买500k能量，则必须以至少35能量的价格下订单，以满足您的订单
    // （如果订单持续时间少于3天，则价格可能更高）

    $need_trx = $MAX_PRICE_ACCEPTED * $BUY_AMOUNT;

    // 检查您的内部余额是否足够购买
    $account_info = get_account_info($API_KEY);
    print_r($account_info);
    /*
     {
        "id": "user_id",
        "balance": "1000000",
        "represent_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
        "deposit_address": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
    }
    */
    $is_balance_enough = intval($account_info["balance"]) >= $need_trx;
    if ($is_balance_enough) {
        $buy_energy_order = buy_energy($API_KEY, $RECEIVER_ADDRESS, $BUY_AMOUNT, $DURATION, $MAX_PRICE_ACCEPTED);
        print_r($buy_energy_order);
        /*
          {
          "order_id": "651d2306e55c073f6ca0992e",
          "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
          "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
          "resource_amount": 100000,
          "resource_type": "ENERGY",
          "remain_amount": 0,
          "price": 67.5,
          "duration": 3600,
          "allow_partial_fill": true,
          "payout_amount": 6750000,
          "fulfilled_percent": 100
        }
        */
        // 购买后等待3-5秒，然后检查
        if ($buy_energy_order["order_id"]) {
            while (true) {
                sleep_ms(3000);
                $order_details = get_one_order_details($API_KEY, $buy_energy_order["order_id"]);
                print_r($order_details);
                /*
                    {
                        "id": "651d2306e55c073f6ca0992e",
                        "requester": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
                        "target": "TKVSaJQDWeKFSEXmA44pjxduGTxy999999",
                        "resource_amount": 100000,
                        "resource_type": "ENERGY",
                        "remain_amount": 0,
                        "price": 67.5,
                        "duration": 3600,
                        "allow_partial_fill": true,
                        "payout_amount": 6750000,
                        "fulfilled_percent": 100,
                        "matched_delegates": [
                                    {
                                        "delegator": "TKVSaJQDWeKFSEXmA44pjxduGTxy888888",
                                        "amount": 100000,
                                        "txid": "transaction_id_1"
                                    }
                                ]
                    }
                */
                if ($order_details && ($order_details["fulfilled_percent"] === 100 || $order_details["remain_amount"] === 0)) {
                    echo "Your order already fulfilled\n";
                    break;
                } else {
                    echo "Your order is not fulfilled, wait 3s and recheck\n";
                }
            }
        } else {
            print_r($buy_energy_order);
            throw new Exception("Buy Order Failed");
        }
    }
}

create_order_by_using_api_key();
?>

```

{% endtab %}
{% endtabs %}
