### Order Query Implementation Examples Source: https://develop.itrx.io/api/order-query.html Client-side implementation examples for querying orders across various programming languages. ```python import requests API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4" URL = "https://itrx.io/api/v1/frontend/order/query" params = {'serial': '58b451473d290f92443eabf0322b9907'} headers = { "API-KEY": API_KEY } response = requests.get(f"{URL}", params=params, headers=headers) print(response.json()) ``` ```php '58b451473d290f92443eabf0322b9907'); $headers = array('API-KEY' => $API_KEY); $context = stream_context_create(array( 'http' => array( 'method' => 'GET', 'header' => "API-KEY: " . $API_KEY, ) )); $response = file_get_contents($URL . "?" . http_build_query($params), false, $context); var_dump(json_decode($response, true)); ?> ``` ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Main { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); String url = "https://itrx.io/api/v1/frontend/order/query?serial=58b451473d290f92443eabf0322b9907"; Request request = new Request.Builder() .url(url) .addHeader("API-KEY", "B433BFF1CDE7450AA38A56BEAC690DD4") .build(); try { Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } ``` ```go package main import ( "io/ioutil" "net/http" "fmt" ) func main() { API_KEY := "B433BFF1CDE7450AA38A56BEAC690DD4" URL := "https://itrx.io/api/v1/frontend/order/query?serial=58b451473d290f92443eabf0322b9907" client := &http.Client{} req, _ := http.NewRequest("GET", URL, nil) req.Header.Set("API-KEY", API_KEY) resp, err := client.Do(req) if err != nil { fmt.Printf("The HTTP request failed with error %s\n", err) } else { data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) } } ``` ```bash API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" URL="https://itrx.io/api/v1/frontend/order/query" params="serial=58b451473d290f92443eabf0322b9907" curl -X GET -H "API-KEY:$API_KEY" "$URL?$params" ``` -------------------------------- ### Normal Return Example Source: https://develop.itrx.io/api/order-price.html Example of a successful response from the estimated order price API. ```JSON { "period": "3D", "energy_amount": 32000, "price": 100, "total_price": 10192000, "addition": 600000 } ``` -------------------------------- ### Normal Response Example Source: https://develop.itrx.io/api/order-count-policy.html This is an example of a successful response from the Purchase Count API. The 'balance' field indicates the remaining balance in sun. ```JSON { "errno": 0, "balance": 813900029257 } ``` -------------------------------- ### Order Query Response Examples Source: https://develop.itrx.io/api/order-query.html JSON structures for successful order retrieval and error handling. ```json { "errno": 0, "receive_address": "TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw", "order_no": "58b451473d290f92443eabf0322b9907", "energy_amount": 32000, "pay_amount": 0.0, "amount": 3800000, "details": [ // Large orders may be split into multiple orders { "delegate_hash": "e2e71df638a9e01492a50bebba072a39eb75f673e91d5374ccf517f44e113f3", "delegate_time": "2023-10-09T10:21:07.840478Z", "reclaim_hash": "f4672a9563947cf78e5534b4025451dfd75efa5481a67b20ee55b9be368c900", "reclaim_time": "2023-10-12T10:21:07.840478Z", "reclaim_time_real": "2023-10-09T10:26:12.617456Z", "status": 30 // 20-in commission, 30-recycled } ], "create_time": "2023-06-15T21:42:13.200565+08:00", "api_name": "MY API", "period": 0, "status": 30, // 30 indicates that the commission was completely successful "refund_amount": 0 } ``` ```json { "errno": 404, "message": "Order not found" } ``` -------------------------------- ### ITRX API Order Transfer Examples Source: https://develop.itrx.io/api/order-transfer-trx.html Examples for authenticating and sending a POST request to the ITRX order transfer endpoint. Each example demonstrates generating a timestamp, sorting request data, and creating an HMAC-SHA256 signature. ```python import hmac import json import requests import hashlib import time API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4" API_SECRET = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" timestamp = str(int(time.time())) URL = "https://itrx.io/api/v1/frontend/order/transfer" data = { 'amount': 345000, 'receive_address': 'TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw',, } json_data = json.dumps(data, sort_keys=True, separators=(',', ':')) message = f'{timestamp}&{json_data}' signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() headers = { "API-KEY": API_KEY, "TIMESTAMP": timestamp, "SIGNATURE": signature, 'Content-Type': 'application/json', } response = requests.post(f"{URL}", data=json_data, headers=headers) print(response.json()) ``` ```php 345000, 'receive_address' => 'TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw', ]; ksort($data); $json_data = json_encode($data, JSON_UNESCAPED_SLASHES); $message = $timestamp . '&' . $json_data; $signature = hash_hmac('sha256', $message, $API_SECRET); $options = [ 'http' => [ 'header' => "Content-Type: application/json\r\n" . "API-KEY: $API_KEY\r\n" . "TIMESTAMP: $timestamp\r\n" . "SIGNATURE: $signature\r\n", 'method' => 'POST', 'content' => $json_data, ], ]; $context = stream_context_create($options); $result = file_get_contents("https://itrx.io/api/v1/frontend/order/transfer", false, $context); var_dump($result); ?> ``` ```java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import okhttp3.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Main { private static final String API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4"; private static final String API_SECRET = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8"; public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient().newBuilder().build(); MediaType mediaType = MediaType.parse("application/json"); String timestamp = String.valueOf(Instant.now().getEpochSecond()); Map data = new HashMap<>(); data.put("amount", 345000); data.put("receive_address", "TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw"); // Sorting the keys TreeMap sortedData = new TreeMap<>(data); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String json_data = gson.toJson(sortedData); String message = timestamp + "&" + json_data; String signature = encodeHmacSHA256(message, API_SECRET); RequestBody body = RequestBody.create(json_data, mediaType); Request request = new Request.Builder() .url("https://itrx.io/api/v1/frontend/order/transfer") .method("POST", body) .addHeader("API-KEY", API_KEY) .addHeader("TIMESTAMP", timestamp) .addHeader("SIGNATURE", signature) .addHeader("Content-Type", "application/json") .build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } private static String encodeHmacSHA256(String data, String key) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] bytes = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)); StringBuilder hash = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if(hex.length() == 1) hash.append('0'); hash.append(hex); } return hash.toString(); } } ``` ```go package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "time" jsoniter "github.com/json-iterator/go" ) const ( APIKey = "B433BFF1CDE7450AA38A56BEAC690DD4" APISecret = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" URL = "https://itrx.io/api/v1/frontend/order/transfer" ) type Data struct { Amount int `json:"amount"` ReceiveAddress string `json:"receive_address"` } func main() { timestamp := strconv.FormatInt(time.Now().Unix(), 10) data := Data{ Amount: 345000, ``` -------------------------------- ### Java API Usage Summary Request Source: https://develop.itrx.io/api/api-summary.html Example of how to fetch the API usage summary using Java with OkHttp. This demonstrates setting the API-KEY header for the request. ```Java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Main { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); String url = "https://itrx.io/api/v1/frontend/userapi/summary"; Request request = new Request.Builder() .url(url) .addHeader("API-KEY", "B433BFF1CDE7450AA38A56BEAC690DD4") .build(); try { Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Go API Usage Summary Request Source: https://develop.itrx.io/api/api-summary.html Example of how to fetch the API usage summary using Go. This code sets the API-KEY header and handles the HTTP response. ```Go package main import ( "io/ioutil" "net/http" "fmt" ) func main() { API_KEY := "B433BFF1CDE7450AA38A56BEAC690DD4" URL := "https://itrx.io/api/v1/frontend/userapi/summary" client := &http.Client{} req, _ := http.NewRequest("GET", URL, nil) req.Header.Set("API-KEY", API_KEY) resp, err := client.Do(req) if err != nil { fmt.Printf("The HTTP request failed with error %s\n", err) } else { data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) } } ``` -------------------------------- ### PHP API Usage Summary Request Source: https://develop.itrx.io/api/api-summary.html Example of how to fetch the API usage summary using PHP. This code uses stream contexts to set the necessary headers. ```PHP $API_KEY); $context = stream_context_create(array( 'http' => array( 'method' => 'GET', 'header' => "API-KEY: " . $API_KEY, ) )); $response = file_get_contents($URL, false, $context); var_dump(json_decode($response, true)); ?> ``` -------------------------------- ### ITRX API: Query Auto-Delegate Policies Source: https://develop.itrx.io/api/order-auto-policy.html This is an example of a GET request to query auto-delegate policies. It shows the endpoint and the optional `receive_address` query parameter. ```http GET /api/v1/frontend/auto-delegate-policy?receive_address= ``` -------------------------------- ### GET /api/v1/frontend/userapi/summary Source: https://develop.itrx.io/api/api-summary.html Retrieves the summary of API usage, including order counts and energy/TRX consumption metrics. ```APIDOC ## GET /api/v1/frontend/userapi/summary ### Description Retrieves a summary of user API usage, including total, daily, and yesterday's order counts and consumption metrics. ### Method GET ### Endpoint /api/v1/frontend/userapi/summary ### Response #### Success Response (200) - **name** (string) - API name - **create_time** (string) - Creation time - **total_count** (int) - Total number of orders - **total_sum_energy** (int) - Total order energy - **total_sum_trx** (int) - Total consumption TRX (unit sun) - **today_count** (int) - Number of orders placed today - **today_sum_energy** (int) - Today's single energy - **today_sum_trx** (int) - TRX consumed today (unit: sun) - **yesterday_count** (int) - Number of orders placed yesterday - **yesterday_sum_energy** (int) - Yesterday’s order energy - **yesterday_sum_trx** (int) - Yesterday's consumption of TRX (unit: sun) #### Response Example { "name": "MY API", "create_time": "2023-04-28 12:31:04", "total_count": 46, "total_sum_energy": 3696000, "total_sum_trx": 598165000, "today_count": 0, "today_sum_energy": 0, "today_sum_trx": 0, "yesterday_count": 1, "yesterday_sum_energy": 1300000, "yesterday_sum_trx": 197600000 } ``` -------------------------------- ### Estimate Order Price with Java Source: https://develop.itrx.io/api/order-price.html Implement an HTTP GET request using OkHttp in Java to fetch the estimated order price. The API key is passed as a header. ```Java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Main { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); String url = "https://itrx.io/api/v1/frontend/order/price?period=3D&energy_amount=32000"; Request request = new Request.Builder() .url(url) .addHeader("API-KEY", "B433BFF1CDE7450AA38A56BEAC690DD4") .build(); try { Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Shell API Usage Summary Request Source: https://develop.itrx.io/api/api-summary.html Example of how to fetch the API usage summary using curl in a shell environment. This command includes the API-KEY in the request header. ```Shell API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" URL="https://itrx.io/api/v1/frontend/userapi/summary" curl -X GET -H "API-KEY:$API_KEY" "$URL" ``` -------------------------------- ### Perform API Request in Bash Source: https://develop.itrx.io/api/order-recliam.html Uses curl and openssl to generate a signature and execute the request. Requires jq and xxd installed on the system. ```bash #!/bin/bash API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" API_SECRET="0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" URL="https://itrx.io/api/v1/frontend/order/reclaim" timestamp=$(date +%s) data=$(echo '{ "serial": "xxyyzz" }' | jq -c -S '.') message="${timestamp}&${data}" signature=$(echo -n "${message}" | openssl dgst -sha256 -hmac ${API_SECRET} -binary | xxd -p) curl --location --request POST ${URL} \ --header "API-KEY: ${API_KEY}" \ --header "TIMESTAMP: ${timestamp}" \ --header "SIGNATURE: ${signature}" \ --header "Content-Type: application/json" \ --data-raw "${data}" ``` -------------------------------- ### Java: Collect Manual Order Source: https://develop.itrx.io/api/order-collect.html This Java example shows how to integrate with the ITRX API using OkHttp and Gson. It includes a helper method for generating SHA256 HMAC signatures. Ensure you have the OkHttp and Gson libraries added to your project. ```java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import okhttp3.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Main { private static final String API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4"; private static final String API_SECRET = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8"; public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient().newBuilder().build(); MediaType mediaType = MediaType.parse("application/json"); String timestamp = String.valueOf(Instant.now().getEpochSecond()); Map data = new HashMap<>(); data.put("scene", 2); data.put("receive_address", "TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw"); data.put("callback_url", "http://{mydomain}/callback"); data.put("out_trade_no", "123456"); // Sorting the keys TreeMap sortedData = new TreeMap<>(data); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String json_data = gson.toJson(sortedData); String message = timestamp + "&" + json_data; String signature = encodeHmacSHA256(message, API_SECRET); RequestBody body = RequestBody.create(json_data, mediaType); Request request = new Request.Builder() .url("https://itrx.io/api/v1/frontend/order/collect-manual") .method("POST", body) .addHeader("API-KEY", API_KEY) .addHeader("TIMESTAMP", timestamp) .addHeader("SIGNATURE", signature) .addHeader("Content-Type", "application/json") .build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } private static String encodeHmacSHA256(String data, String key) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] bytes = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)); StringBuilder hash = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if(hex.length() == 1) hash.append('0'); hash.append(hex); } return hash.toString(); } } ``` -------------------------------- ### Estimate Order Price with Python Source: https://develop.itrx.io/api/order-price.html Use the requests library to get the estimated order price. Ensure your API key is correctly set. ```Python import requests API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4" URL = "https://itrx.io/api/v1/frontend/order/price" params = {'period': '3D', 'energy_amount': 32000} headers = { "API-KEY": API_KEY } response = requests.get(f"{URL}", params=params, headers=headers) print(response.json()) ``` -------------------------------- ### Python API Usage Summary Request Source: https://develop.itrx.io/api/api-summary.html Example of how to fetch the API usage summary using Python's requests library. Ensure the API-KEY is correctly set in the headers. ```Python import requests API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4" URL = "https://itrx.io/api/v1/frontend/userapi/summary" headers = { "API-KEY": API_KEY } response = requests.get(f"{URL}", headers=headers) print(response.json()) ``` -------------------------------- ### Estimate Order Price with PHP Source: https://develop.itrx.io/api/order-price.html Utilize stream contexts in PHP to make a GET request for estimated order price. The API key must be included in the headers. ```PHP '3D', 'energy_amount': 32000); $headers = array('API-KEY' => $API_KEY); $context = stream_context_create(array( 'http' => array( 'method' => 'GET', 'header' => "API-KEY: " . $API_KEY, ) )); $response = file_get_contents($URL . "?" . http_build_query($params), false, $context); var_dump(json_decode($response, true)); ?> ``` -------------------------------- ### Order success response Source: https://develop.itrx.io/api/order-create.html Example of a successful API response containing the order serial number and cost details. ```json { "errno": 0, "serial": "7297a8a2a9e39b86fc5bad0d2e9edda2", "amount": 3120000, "balance": 813900029257 } ``` -------------------------------- ### Verify Signature in Java Source: https://develop.itrx.io/general/callback.html Java example for verifying request signatures using HMAC-SHA256. It requires Apache Commons Codec and Commons Lang libraries. ```java import org.apache.commons.codec.digest.HmacAlgorithms; import org.apache.commons.codec.digest.HmacUtils; import org.apache.commons.lang3.StringUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.*; public class Main { public static void main(String[] args) { String apiSecret = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8"; Map headers = new HashMap<>(); // your headers here Map body = new HashMap<>(); // your body data here String timestamp = headers.get("TIMESTAMP"); String signature = headers.get("SIGNATURE"); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); TreeMap sortedBody = new TreeMap<>(body); String jsonData = gson.toJson(sortedBody); String message = timestamp + "&" + jsonData; String expectedSignature = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, apiSecret).hmacHex(message); if (StringUtils.equals(signature, expectedSignature)) { System.out.println("Signature is valid."); System.out.println(body); } else { System.out.println("Signature is invalid."); } } } ``` -------------------------------- ### Estimate Order Price with Shell Source: https://develop.itrx.io/api/order-price.html Use curl in shell to send a GET request for the estimated order price. The API key is provided in the headers. ```Shell API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" URL="https://itrx.io/api/v1/frontend/order/price" params="period=3D&energy_amount=32000" curl -X GET -H "API-KEY:$API_KEY" "$URL?$params" ``` -------------------------------- ### Get Public Data Source: https://develop.itrx.io/api/index-data.html Fetches public data using Java with OkHttp. The API key must be included in the request headers. ```Java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Main { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); String url = "https://itrx.io/api/v1/frontend/index-data"; Request request = new Request.Builder() .url(url) .addHeader("API-KEY", "B433BFF1CDE7450AA38A56BEAC690DD4") .build(); try { Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Estimate Order Price with Go Source: https://develop.itrx.io/api/order-price.html Make an HTTP GET request in Go to retrieve the estimated order price. The API key is set in the request headers. ```Go package main import ( "io/ioutil" "net/http" "fmt" ) func main() { API_KEY := "B433BFF1CDE7450AA38A56BEAC690DD4" URL := "https://itrx.io/api/v1/frontend/order/price?period=3D&energy_amount=32000" client := &http.Client{} req, _ := http.NewRequest("GET", URL, nil) req.Header.Set("API-KEY", API_KEY) resp, err := client.Do(req) if err != nil { fmt.Printf("The HTTP request failed with error %s\n", err) } else { data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) } } ``` -------------------------------- ### Submit Order via ITRX API Source: https://develop.itrx.io/general/sign.html Examples for authenticating requests using API keys and HMAC-SHA256 signatures across multiple programming languages. ```python import hmac import json import requests import hashlib import time API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4" API_SECRET = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" timestamp = str(int(time.time())) URL = "https://itrx.io/api/v1/frontend/order" data = { 'energy_amount': 32000, 'period': '1D', 'receive_address': 'TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw', 'callback_url': 'http://{mydomain}/callback', 'out_trade_no': '123456', } json_data = json.dumps(data, sort_keys=True, separators=(',', ':')) message = f'{timestamp}&{json_data}' signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() headers = { "API-KEY": API_KEY, "TIMESTAMP": timestamp, "SIGNATURE": signature, 'Content-Type': 'application/json', } response = requests.post(f"{URL}", data=json_data, headers=headers) print(response.json()) ``` ```php 32000, 'period' => '1D', 'receive_address' => 'TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw', 'callback_url' => 'http://{mydomain}/callback', 'out_trade_no' => '123456', ]; ksort($data); $json_data = json_encode($data, JSON_UNESCAPED_SLASHES); $message = $timestamp . '&' . $json_data; $signature = hash_hmac('sha256', $message, $API_SECRET); $ch = curl_init("https://itrx.io/api/v1/frontend/order"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "API-KEY: $API_KEY", "TIMESTAMP: $timestamp", "SIGNATURE: $signature" ]); $result = curl_exec($ch); curl_close($ch); var_dump($result); ?> ``` ```java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import okhttp3.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Main { private static final String API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4"; private static final String API_SECRET = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8"; public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient().newBuilder().build(); MediaType mediaType = MediaType.parse("application/json"); String timestamp = String.valueOf(Instant.now().getEpochSecond()); Map data = new HashMap<>(); data.put("energy_amount", 32000); data.put("period", "1D"); data.put("receive_address", "TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw"); data.put("callback_url", "http://{mydomain}/callback"); data.put("out_trade_no", "123456"); // Sorting the keys TreeMap sortedData = new TreeMap<>(data); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String json_data = gson.toJson(sortedData); String message = timestamp + "&" + json_data; String signature = encodeHmacSHA256(message, API_SECRET); RequestBody body = RequestBody.create(json_data, mediaType); Request request = new Request.Builder() .url("https://itrx.io/api/v1/frontend/order") .method("POST", body) .addHeader("API-KEY", API_KEY) .addHeader("TIMESTAMP", timestamp) .addHeader("SIGNATURE", signature) .addHeader("Content-Type", "application/json") .build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } private static String encodeHmacSHA256(String data, String key) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] bytes = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)); StringBuilder hash = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if(hex.length() == 1) hash.append('0'); hash.append(hex); } return hash.toString(); } } ``` ```go package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "time" jsoniter "github.com/json-iterator/go" ) const ( APIKey = "B433BFF1CDE7450AA38A56BEAC690DD4" APISecret = "0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" ) ``` -------------------------------- ### ITRX API: Normal Return Example for Query Source: https://develop.itrx.io/api/order-auto-policy.html This JSON structure represents a successful response when querying auto-delegate policies. It includes pagination details and a list of policy results. ```json { "count": 2, "code": 0, "page": 1, "next": null, "previous": null, "results": [ { "id": 21, "receive_address": "TNfdtE7p8pEfTTbfRb88gikf2tt5ENc86b", "status": 1, // Is it valid? "last_step": 1, // See the table below for explanation "main_delegated": false, // Delegated status, valid during automatic renewal "expired_time": null, "create_time": "2023-10-09T11:13:12.288373+08:00", "update_time": "2023-10-09T16:35:36.559760+08:00", "last_step_display": "delegated", "status_display": "on", "auto_type": 1, // 1 is smart hosting, 2 is automatic renewal only "auto_type_display": "smart hosting", "next_delegate_time": null, // Valid during automatic renewal "max_energy": 50000, // maintain energy "period": 3, // Commission period }, ... ] } ``` -------------------------------- ### GET /api/v1/frontend/order/price Source: https://develop.itrx.io/api/order-price.html Retrieves the estimated order amount for energy rentals. You can specify the rental period and energy amount, or provide a target address for automatic estimation. ```APIDOC ## GET /api/v1/frontend/order/price ### Description Retrieves the estimated order amount for energy rentals. You can specify the rental period and energy amount, or provide a target address for automatic estimation. ### Method GET ### Endpoint /api/v1/frontend/order/price ### Parameters #### Query Parameters - **period** (string) - Required - Rental period, options: 1H/1D/3D/30D. H means 1 hour, D means day. - **energy_amount** (int) - Optional - Estimated energy, minimum 10000. - **to_address** (Tron address) - Optional - Target address for the transaction. If you are unsure how much energy is needed, you can skip energy_amount and only specify the target address. The system will automatically estimate the required energy for a USDT transaction. ### Response #### Success Response (200) - **period** (string) - Rental duration. - **energy_amount** (int) - The energy of placing the order. - **price** (int) - Unit price in sun. - **total_price** (int) - TRX to be paid, in sun. - **addition** (int) - Small handling fee (for less than 50,000 energy requirements), in sun. #### Response Example ```json { "period": "3D", "energy_amount": 32000, "price": 100, "total_price": 10192000, "addition": 600000 } ``` ### Request Example ```json { "period": "3D", "energy_amount": 32000 } ``` ``` -------------------------------- ### GET /api/v1/frontend/auto-delegate-policy Source: https://develop.itrx.io/api/order-auto-policy.html Retrieves a list of auto-delegate policies, optionally filtered by address. ```APIDOC ## GET /api/v1/frontend/auto-delegate-policy ### Description Query auto-delegate policies. If receive_address is not provided, returns all policies. ### Method GET ### Endpoint /api/v1/frontend/auto-delegate-policy ### Parameters #### Query Parameters - **receive_address** (string) - Optional - Tron address to filter by ### Response #### Success Response (200) - **count** (int) - Total number of results - **results** (array) - List of policy objects ### Response Example { "count": 1, "results": [ { "id": 21, "receive_address": "TNfdtE7p8pEfTTbfRb88gikf2tt5ENc86b", "status": 1, "max_energy": 50000, "period": 3 } ] } ``` -------------------------------- ### Successful Collection Response Source: https://develop.itrx.io/api/order-collect.html Example of a successful JSON response returned by the collection API. ```json { "errno": 0, "serial": "7297a8a2a9e39b86fc5bad0d2e9edda2", "scene": 1, "amount": 4000000, "balance": 813900029257 } ``` -------------------------------- ### Submit Order via Bash Source: https://develop.itrx.io/general/sign.html Uses curl, jq, and openssl to perform the API request from the command line. ```bash #!/bin/bash API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" API_SECRET="0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" URL="https://itrx.io/api/v1/frontend/order" timestamp=$(date +%s) data=$(echo '{ "energy_amount": 32000, "period": "1D", "receive_address": "TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw", "callback_url": "http://{mydomain}/callback", "out_trade_no": "123456" }' | jq -c -S '.') message="${timestamp}&${data}" signature=$(echo -n "${message}" | openssl dgst -sha256 -hmac ${API_SECRET} -binary | xxd -p) curl --location --request POST ${URL} \ --header "API-KEY: ${API_KEY}" \ --header "TIMESTAMP: ${timestamp}" \ --header "SIGNATURE: ${signature}" \ --header "Content-Type: application/json" \ --data-raw "${data}" ``` -------------------------------- ### Get Public Data Source: https://develop.itrx.io/api/index-data.html Retrieves public data from the ITRX platform. Requires an API key for authentication. ```Python import requests API_KEY = "B433BFF1CDE7450AA38A56BEAC690DD4" URL = "https://itrx.io/api/v1/frontend/index-data" headers = { "API-KEY": API_KEY } response = requests.get(f"{URL}", headers=headers) print(response.json()) ``` -------------------------------- ### Get Public Data Source: https://develop.itrx.io/api/index-data.html Retrieves public data using Go. The API key is set in the request headers. ```Go package main import ( "io/ioutil" "net/http" "fmt" ) func main() { API_KEY := "B433BFF1CDE7450AA38A56BEAC690DD4" URL := "https://itrx.io/api/v1/frontend/index-data" client := &http.Client{} req, _ := http.NewRequest("GET", URL, nil) req.Header.Set("API-KEY", API_KEY) resp, err := client.Do(req) if err != nil { fmt.Printf("The HTTP request failed with error %s\n", err) } else { data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) } } ``` -------------------------------- ### Get Public Data Source: https://develop.itrx.io/api/index-data.html Uses curl to fetch public data from the ITRX platform. The API key is passed in the headers. ```Shell API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" URL="https://itrx.io/api/v1/frontend/index-data" curl -X GET -H "API-KEY:$API_KEY" "$URL" ``` -------------------------------- ### Collect Manual Order in Bash Source: https://develop.itrx.io/api/order-collect.html Uses curl, jq, and openssl to perform the API request via command line. ```bash #!/bin/bash API_KEY="B433BFF1CDE7450AA38A56BEAC690DD4" API_SECRET="0285A2741D0E76E2E187260EB23E51851D48403A756333E7D0CF845406ABF3E8" URL="https://itrx.io/api/v1/frontend/order/collect-manual" timestamp=$(date +%s) data=$(echo '{ "scene": 2, "receive_address": "TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw", "callback_url": "http://{mydomain}/callback", "out_trade_no": "123456" }' | jq -c -S '.') message="${timestamp}&${data}" signature=$(echo -n "${message}" | openssl dgst -sha256 -hmac ${API_SECRET} -binary | xxd -p) curl --location --request POST ${URL} \ --header "API-KEY: ${API_KEY}" \ --header "TIMESTAMP: ${timestamp}" \ --header "SIGNATURE: ${signature}" \ --header "Content-Type: application/json" \ --data-raw "${data}" ``` -------------------------------- ### GET API Usage Summary Endpoint Source: https://develop.itrx.io/api/api-summary.html This is the endpoint for retrieving the API usage summary. It requires an API-KEY in the request headers for authentication. ```HTTP GET /api/v1/frontend/userapi/summary ``` -------------------------------- ### Authenticate and Request with PHP Source: https://develop.itrx.io/api/order-count-policy.html Uses stream_context_create to perform a signed POST request. Data must be sorted using ksort before JSON encoding to ensure signature validity. ```php 5, 'receive_address' => 'TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw' ]; ksort($data); $json_data = json_encode($data, JSON_UNESCAPED_SLASHES); $message = $timestamp . '&' . $json_data; $signature = hash_hmac('sha256', $message, $API_SECRET); $options = [ 'http' => [ 'header' => "Content-Type: application/json\r\n" . "API-KEY: $API_KEY\r\n" . "TIMESTAMP: $timestamp\r\n" . "SIGNATURE: $signature\r\n", 'method' => 'POST', 'content' => $json_data, ], ]; $context = stream_context_create($options); $result = file_get_contents("https://itrx.io/api/v1/frontend/count-delegate-policy", false, $context); var_dump($result); ?> ``` -------------------------------- ### Define Order Parameters Source: https://develop.itrx.io/general/sign.html The initial JSON object containing order details. ```json { 'energy_amount': 32000, 'period': '1H', 'receive_address': 'TExWKszFWYTKZH8LYiovAPKzS3L9MLZ4kw', 'callback_url': 'http://{mydomain}/callback', 'out_trade_no': '123456', } ``` -------------------------------- ### Get Public Data Source: https://develop.itrx.io/api/index-data.html Retrieves public data from the ITRX platform using PHP. Ensure the API key is correctly set in the headers. ```PHP $API_KEY); $context = stream_context_create(array( 'http' => array( 'method' => 'GET', 'header' => "API-KEY: " . $API_KEY, ) )); $response = file_get_contents($URL, false, $context); var_dump(json_decode($response, true)); ?> ```