Pushes metering data from within a service instance.
Description
You can call this operation to push only the metering data of a pay-as-you-go Compute Nest service instance. The reporting method of the pushed billable items must be set to Reported by Service Provider.
You can call this operation within the Elastic Compute Service (ECS) or Container Service for Kubernetes (ACK) instances that are created by using Compute Nest to push metering data. To call this operation by using OpenAPI, see Call PushMeteringData by using OpenAPI.
Request parameters
Name | Type | Required | Description | Example |
Metering | String | Yes | The metering data. Parameters in the example value:
Note
|
|
Token | String | Yes | The token that is used by Compute Nest to determine whether the metering data is pushed by a service provider. Use the MD5 encryption algorithm to encrypt
|
|
Response parameters
Name | Type | Description | Example | ||
RequestId | String | The request ID returned by Compute Nest. | e6862d3a-9305-4289-8dd3-9c52a680228b | ||
Success | Boolean | Indicates whether the request was successful. | true | ||
PushMeteringDataRequestId | String | The request ID returned by Alibaba Cloud Marketplace. | 7lc658a2-tr41-****-****-c25es45vc248 | ||
Token | String | The token that is used by a service provider to compare digital signatures. For more information, see Digital signature verification in Compute Nest. | 50130a063c6acf833280d23169898bd4 |
Examples
This example shows how to call the operation from an ECS instance that is created by using a pay-as-you-go Compute Nest product in Alibaba Cloud Marketplace.
Curl example
Obtain the region information of the ECS instance
Before you call PushMeteringData, you need to obtain the region (regionId) information of the ECS instance where the application is deployed. The service provider needs to record the region information because it will be used in subsequent steps.
Access the following URL to obtain the region information.
curl http://100.100.100.200/latest/meta-data/region-idSample output:
cn-hangzhou
Prepare the input parameters
"Metering":"[{\"StartTime\":\"1664451045\",\"EndTime\":\"1664451198\",\"Entities\":[{\"Key\":\"Frequency\",\"Value\":\"6\"}]}]","Token":"7aa81300b2aea77984b772495c8e4e83"Metering:
[{\"StartTime\":\"1664451045\",\"EndTime\":\"1664451198\",\"Entities\":[{\"Key\":\"Frequency\",\"Value\":\"6\"}]}].NoteBecause this example uses curl to call PushMeteringData, you need to add the escape character
\. If you use code to call the operation, you do not need to add escape characters.Token: Use the MD5 encryption algorithm to encrypt the string Metering&Service Key into a 32-character lowercase string
7aa81300b2aea77984b772495c8e4e83.
Query example
curl -H "Content-Type: application/json" -XPOST https://cn-hangzhou.axt.aliyun.com/computeNest/marketplace/push_metering_data -d '{"Metering":"[{\"StartTime\":\"1664451045\",\"EndTime\":\"1664451198\",\"Entities\":[{\"Key\":\"Frequency\",\"Value\":\"6\"}]}]","Token":"7aa81300b2aea77984b772495c8e4e83"}'NoteIn
https://cn-hangzhou.axt.aliyun.com,cn-hangzhouis the region obtained in Step 1. Replace it with the actual region when you call the operation.Sample output
{ "RequestId":"4ca591b5-bc30-****-****-c4d0ec5d24ed", "Success":"true", "PushMeteringDataRequestId":"7lc658a2-tr41-****-****-c25es45vc248", "Token":"50130a063c6acf833280d23169898bd4" }
Code examples
Python
import requests
import json
import hashlib
import time
from urllib.request import urlopen
def get_region_id():
"""Get the region ID (such as cn-hangzhou) through Alibaba Cloud metadata service"""
try:
with urlopen(
"http://100.100.100.200/latest/meta-data/region-id",
timeout=2
) as response:
return response.read().decode().strip()
except Exception as e:
print(f"Failed to get region ID: {str(e)}", file=sys.stderr)
sys.exit(1)
def push_metering_data(entities_map, service_key):
# Dynamically get current time (Unix timestamp in seconds)
current_time = int(time.time())
start_time = current_time
end_time = current_time + 1
# Build Metering data
metering_data = [
{
"StartTime": str(start_time),
"EndTime": str(end_time),
"Entities": [
{"Key": key, "Value": str(value)}
for key, value in entities_map.items()
]
}
]
metering_str = json.dumps(metering_data)
# Dynamically get region ID and build URL
region_id = get_region_id()
url = f"https://{region_id}.axt.aliyun.com/computeNest/marketplace/push_metering_data"
# Calculate Token
token_str = metering_str + "&" + service_key
token = hashlib.md5(token_str.encode()).hexdigest().lower()
# Send POST request
try:
response = requests.post(
url,
json={
"Metering": metering_str,
"Token": token
},
headers={"Content-Type": "application/json"}
)
print(f"Request URL: {url}")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
except Exception as e:
print(f"Request Failed: {str(e)}", file=sys.stderr)
if __name__ == "__main__":
import sys
# Example parameters (replace with actual push data, key is the metering item, value is the value)
entities = {
"Frequency": "6"
}
# Service provider Key
service_key = "your_service_key_here"
# Call function
push_metering_data(entities, service_key)
Running example:

Java
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public class MeteringPusher {
public static void main(String[] args) {
try {
// === Dynamically get region ID === #
String regionId = getRegionId();
System.out.println("Detected Region ID: " + regionId);
// === Build request body === #
Map<String, String> entities = new HashMap<>(); // Build Entities, replace with actual push content
entities.put("Frequency", "6");
String serviceKey = "your_service_key_here"; // Replace with actual service provider Key
JSONObject payload = generateDynamicRequest(regionId, entities, serviceKey);
String paylodString = payload.toString();
// If only testing, you can comment out the above content and directly input the following content, where StartTime, EndTime and other parameters need to be replaced
// String paylodString = "{\"Metering\":\"[{\\\"StartTime\\\":\\\"1664451045\\\",\\\"EndTime\\\":\\\"1664451198\\\",\\\"Entities\\\":[{\\\"Key\\\":\\\"Frequency\\\",\\\"Value\\\":\\\"6\\\"}]}]\",\"Token\":\"7aa81300b2aea77984b772495c8e4e83\"}";
// === Send POST request === #
String urlStr = "https://" + regionId + ".axt.aliyun.com/computeNest/marketplace/push_metering_data";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = paylodString.getBytes("UTF-8");
os.write(input, 0, input.length);
}
// === Read response === #
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine);
}
conn.disconnect();
System.out.println("Response: " + response.toString());
System.out.println("Request URL: " + urlStr);
} catch (Exception e) {
e.printStackTrace();
}
}
// === Dynamically get region ID (Alibaba Cloud metadata service) ===
private static String getRegionId() throws Exception {
String regionIdUrl = "http://100.100.100.200/latest/meta-data/region-id";
HttpURLConnection conn = (HttpURLConnection) new URL(regionIdUrl).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(2000); // 2 second timeout
conn.setReadTimeout(2000);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
return in.readLine().trim();
}
}
// === Dynamically generate request data ===
private static JSONObject generateDynamicRequest(String regionId, Map<String, String> entities, String serviceKey) throws Exception {
// Obtain the current timestamp
long currentTime = System.currentTimeMillis() / 1000;
long startTime = currentTime;
long endTime = currentTime + 1;
// Build Metering data
JSONArray meteringArray = new JSONArray();
JSONObject meteringItem = new JSONObject();
meteringItem.put("StartTime", String.valueOf(startTime));
meteringItem.put("EndTime", String.valueOf(endTime));
JSONArray entitiesArray = new JSONArray();
for (Map.Entry<String, String> entry : entities.entrySet()) {
entitiesArray.put(new JSONObject()
.put("Key", entry.getKey())
.put("Value", entry.getValue()));
}
meteringItem.put("Entities", entitiesArray);
meteringArray.put(meteringItem);
// Calculate Token
String meteringStr = meteringArray.toString();
String tokenStr = meteringStr + "&" + serviceKey;
String token = md5(tokenStr);
// Build complete request body
JSONObject payload = new JSONObject();
payload.put("Metering", meteringStr);
payload.put("Token", token);
return payload;
}
// === MD5 encryption method ===
private static String md5(String input) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
Running example:

Make sure your project includes the org.json library (such as Maven dependency):
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>Error codes
Error code | Error message | Description |
OperationDenied | The serviceInstance does not supported push metering data. | The error message returned because pushing metering data is not supported for service instances that are not pay-as-you-go. |
Only metering entities classified as Custom and associated with a service can be pushed. The entity ${EntityId} is invalid. | The error message returned because the billable item **** does not support pushing. The reporting method must be set to Reported by Service Provider and the billable item must be bound. | |
MissingParameter.${parametersName} | The input parameter "${parametersName}" that is mandatory for processing this request is not supplied. | The error message returned because a required parameter is not specified. |
InvalidParameter.${parametersName} | The provided parameter "${parametersName}" is invalid. | The error message returned because a specified parameter is invalid. |
EntityNotExist.ServiceInstance | The specified service instance cannot be found. | The error message returned because the service instance does not exist (the ECS instance is not created by Compute Nest). |