Saiba como verificar a validade de uma instância de serviço com a API CheckOutLicense.
Limitações
O serviço deve atender a um dos seguintes requisitos:
Configuração para vendas personalizadas.
Listagem no Alibaba Cloud Marketplace.
Como funciona
Ao provisionar uma instância de serviço, o Compute Nest aplica tags automaticamente aos recursos subjacentes. Essas tags incluem o ID da instância de serviço (ServiceInstanceId) e o ID do serviço (ServiceId). A API CheckOutLicense usa essas tags para identificar a instância de serviço associada ao recurso que inicia a chamada.
Obtenha o
ServiceIddo serviço no console do Compute Nest.Passe o
ServiceIdcomo parâmetro ao chamar a APICheckOutLicense. O Compute Nest compara esse parâmetro com o ID do serviço nas tags do recurso. Em caso de correspondência, a API retorna os detalhes da licença.
Exemplo de chamada de API
Este exemplo demonstra como chamar a API CheckOutLicense a partir de uma instância ECS pertencente a um serviço que atende aos requisitos descritos em Limitações.
-
Obtenha o ID da região da instância ECS
Antes de chamar a API CheckOutLicense, obtenha o ID da região da instância ECS onde sua aplicação está implantada. Salve este ID para a próxima etapa.
-
Execute o comando a seguir para obter o ID da região.
curl http://100.100.100.200/latest/meta-data/region-id -
Exemplo de saída:
cn-hangzhou
-
-
Obtenha o
ServiceIdno console do Compute Nest.
-
Exemplo de solicitação
Este exemplo mostra uma chamada iniciada na região China (Hangzhou). Substitua a região na URL e o ServiceId pelos seus valores reais.
# Replace the value of ServiceId with your actual service ID. curl -H "Content-Type: application/json" -XPOST https://cn-hangzhou.axt.aliyun.com/computeNest/license/check_out_license -d '{"ServiceId":"service-8fff945fe6844906****"}' -
Exemplo de resposta
{ "code":200, "requestId":"6af1efb7-c59c-4cee-9094-e1e3bbefb639", "instanceId":"i-0jl957dfri612gxxxxxx", "result":{ "RequestId":"B22723B7-FC31-18F5-A33E-1AF4C82736AA", "ServiceInstanceId":"si-0f14037f30c14292****", "LicenseMetadata":"{\"TemplateName\":\"Custom_Image_Ecs\",\"SpecificationName\":\"\",\"CustomData\":\"xxxx\"}", "TrialType":"NotTrial", "Token":"58d4574bd0d967bb431cd8936b5e80c4", "ExpireTime":"2024-08-28T06:27:08Z", "ServiceId":"service-8fff945fe6844906****", "Components":"{\"package_version\":\"yuncode55xxxxxxxx\",\"SystemDiskSize\":\"40\",\"DataDiskSize\":\"100\"}" } }A tabela a seguir descreve os principais parâmetros da resposta.
Parâmetro
Descrição
Exemplo
ServiceInstanceId
ID da instância de serviço.
si-0f14037f30c14292****
ServiceId
ID do serviço.
service-8fff945fe6844906****
ExpireTime
Data de expiração da instância de serviço.
2024-08-28T06:27:08Z
LicenseMetadata
Metadados personalizados.
Definidos na configuração de vendas personalizadas.
{\"TemplateName\":\"Custom_Image_Ecs\",\"SpecificationName\":\"\",\"CustomData\":\"xxxx\"}
Components
Detalhes dos componentes de faturamento adicionais do Alibaba Cloud Marketplace.
{\"package_version\":\"yuncode55xxxxxxxx\",\"SystemDiskSize\":\"40\",\"DataDiskSize\":\"100\"}
Exemplos de código
Python
import requests
import json
import hashlib
import time
import sys
from urllib.request import urlopen
def get_region_id():
"""Get the region ID (for example, cn-hangzhou) from the 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 checkout_license():
# Dynamically get the region ID and build the URL.
region_id = get_region_id()
url = f"https://{region_id}.axt.aliyun.com/computeNest/license/check_out_license"
# Send the POST request.
try:
response = requests.post(
url,
json={
# Optional: Include ServiceId to scope the check to a specific service.
# If omitted, Compute Nest identifies the service from resource tags.
# "ServiceId": "service-ec9cbf77f9be443db938"
},
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__":
# Call the function.
checkout_license()
Exemplo de saída:

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
public class CheckoutLicense {
public static void main(String[] args) {
try {
// === Dynamically get the region ID ===
String regionId = getRegionId();
System.out.println("Detected Region ID: " + regionId);
String checkoutLicenseString = "{}";
// Optional: Include ServiceId to scope the check to a specific service.
// If omitted, Compute Nest identifies the service from resource tags.
// String checkoutLicenseString = "{\"ServiceId\": \"service-ec9cbf77f9be443db938\"}";
// === Send the POST request ===
String urlStr = "https://" + regionId + ".axt.aliyun.com/computeNest/license/check_out_license";
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 = checkoutLicenseString.getBytes("UTF-8");
os.write(input, 0, input.length);
}
// === Read the response ===
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine);
}
System.out.println("Response: " + response.toString());
}
conn.disconnect();
System.out.println("Request URL: " + urlStr);
} catch (Exception e) {
e.printStackTrace();
}
}
// === Get the region ID from the 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();
}
}
}
Exemplo de saída:
