

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Exemplos de código para integração de produtos de SaaS
<a name="saas-code-examples"></a>

Você pode usar os exemplos de código a seguir para integrar seu produto de software como serviço (SaaS) às AWS Marketplace APIs necessárias para publicar e manter seu produto. Para obter mais informações, consulte as seções a seguir.

**Topics**
+ [Exemplo de código `ResolveCustomer`](#saas-resolvecustomer-example)
+ [Exemplo de código `GetEntitlement`](#saas-getentitlement-example)
+ [Exemplo de código `BatchMeterUsage`](#saas-batchmeterusage-example)
+ [`BatchMeterUsage`exemplo de código: Com ARN de licença](#saas-batchmeterusage-licensearn-example)
+ [Exemplo de código `BatchMeterUsage` com marcação de alocação de uso (opcional)](#saas-batchmeterusage-tagging)

## Exemplo de código `ResolveCustomer`
<a name="saas-resolvecustomer-example"></a>

O exemplo de código a seguir é relevante para todos os modelos de definição de preço. O exemplo do Python troca um `x-amzn-marketplace-token` token por um`CustomerIdentifier`, `ProductCode``LicenseArn`, e. `CustomerAWSAccountId` `CustomerAWSAccountId`É o Conta da AWS ID associado à assinatura e `LicenseArn` é um identificador exclusivo para uma licença específica concedida. Eles são usados para software adquirido por meio de AWS Marketplace. Este código é executado em um aplicativo em seu site de registro, quando o Portal de gerenciamento do AWS Marketplace o redireciona para lá. O redirecionamento é uma solicitação POST que inclui o token. 

Para obter mais informações sobre`ResolveCustomer`, consulte [ResolveCustomer](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)na *Referência da API do AWS Marketplace Metering Service*.

**nota**  
Para uma nova implementação ou ao atualizar sua integração, use o CustomerAWSAccountId em vez de CustomerIdentifier.

```
# Import AWS Python SDK and urllib.parse 
import boto3
import urllib.parse as urlparse 

# Resolving Customer Registration Token
formFields = urlparse.parse_qs(postBody)
regToken = formFields['x-amzn-marketplace-token'][0]

# If regToken present in POST request, exchange for customerID
if (regToken):
    marketplaceClient = boto3.client('meteringmarketplace')
    customerData = marketplaceClient.resolve_customer(RegistrationToken=regToken)
    productCode = customerData['ProductCode']
    customerID = customerData['CustomerIdentifier']
    customerAWSAccountId = customerData['CustomerAWSAccountId']
    licenseARN = customerData['LicenseArn']

    # TODO: Store customer information 
    # TODO: Validate no other accounts share the same customerID
```

### Exemplo de resposta
<a name="saas-resolvecustomer-example-response"></a>

```
{
    'CustomerIdentifier': 'string',
    'CustomerAWSAccountId':'string',
    'ProductCode': 'string',
    'LicenseArn' : 'string'
}
```

## Exemplo de código `GetEntitlement`
<a name="saas-getentitlement-example"></a>

O exemplo de código a seguir é relevante para produtos de SaaS com contrato e contrato de SaaS com modelo de definição de preço de consumo. O exemplo Python verifica se um cliente tem uma autorização ativa.

Para obter mais informações sobre`GetEntitlement`, consulte a Referência [GetEntitlement](https://docs.aws.amazon.com/marketplaceentitlement/latest/APIReference/API_GetEntitlements.html)da *API do AWS Marketplace Entitlement Service*.

```
# Import AWS Python SDK
import boto3

marketplaceClient = boto3.client('marketplace-entitlement', region_name='us-east-1')

# Filter entitlements for a specific customerID
#
# productCode is supplied after the AWS Marketplace Ops team has published 
# the product to limited
# 
# customerID is obtained from the ResolveCustomer response
entitlement = marketplaceClient.get_entitlements({
    'ProductCode': 'productCode',
    'Filter' : {
        # Option 1: Using CustomerIdentifier (for new or updated integrations, use the customer AWS account ID)
        'CUSTOMER_IDENTIFIER': [
            'customerID',
        ]
        # Option 2: Using CustomerAWSAccountId (preferred)
        # 'CUSTOMER_AWS_ACCOUNT_ID': [
        #     'awsAccountId',
        # ]
        # Option 3: Using LICENSE_ARN (to get entitlements for the license)
        # 'LICENSE_ARN': [
        #     'licenseARN',
        # ]
    },
    'NextToken' : 'string',
    'MaxResults': 123
})

# TODO: Verify the dimension a customer is subscribed to and the quantity, 
# if applicable
```

### Exemplo de resposta
<a name="saas-getentitlement-example-response"></a>

O valor retornado corresponde às dimensões criadas quando você criou o produto no Portal de gerenciamento do AWS Marketplace.

```
{
   "Entitlements": [ 
      { 
         "CustomerIdentifier": "string",
         "CustomerAWSAccountId": "string",
         "Dimension": "string",
         "ExpirationDate": number,
         "ProductCode": "string",
         "LicenseArn": "string",
         "Value": { 
            "BooleanValue": boolean,
            "DoubleValue": number,
            "IntegerValue": number,
            "StringValue": "string"
         }
      }
   ],
   "NextToken": "string"
}
```

## Exemplo de código `BatchMeterUsage`
<a name="saas-batchmeterusage-example"></a>

O exemplo de código a seguir é relevante para assinatura SaaS e contrato com modelos de definição de preço de consumo, mas não para produtos de contrato de SaaS sem consumo. O exemplo do Python envia um registro de medição para cobrar de seus clientes AWS Marketplace as taxas de pagamento conforme o uso.

```
# NOTE: Your application will need to aggregate usage for the 
#       customer for the hour and set the quantity as seen below. 
# AWS Marketplace can only accept records for up to an hour in the past. 
#
# productCode is supplied after the AWS Marketplace Ops team has 
# published the product to limited
#
# You can use either:
# - customerID from the ResolveCustomer response
# - AWS account ID of the buyer

# Import AWS Python SDK
import boto3
from datetime import datetime

# Option 1: Using CustomerIdentifier (for new or updated integrations, use the customer AWS account ID)
usageRecord = [
    {
        'Timestamp': datetime(2015, 1, 1),
        'CustomerIdentifier': 'customerID',
        'Dimension': 'string',
        'Quantity': 123
    }
]

# Option 2: Using CustomerAWSAccountId (preferred)
# usageRecord = [
#     {
#         'Timestamp': datetime(2015, 1, 1),
#         'CustomerAWSAccountId': 'awsAccountId',
#         'Dimension': 'string',
#         'Quantity': 123
#     }
# ]

marketplaceClient = boto3.client('meteringmarketplace')

response = marketplaceClient.batch_meter_usage(
    UsageRecords=usageRecord,
    ProductCode='productCode'
)
```

Para obter mais informações sobre`BatchMeterUsage`, consulte [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)na *Referência da API do AWS Marketplace Metering Service*.

### Exemplo de resposta
<a name="saas-batchmeterusage-example-response"></a>

```
{
    'Results': [
        {
            'UsageRecord': {
                'Timestamp': datetime(2015, 1, 1),
                'CustomerIdentifier': 'string',
                'CustomerAWSAccountId': 'string',
                'Dimension': 'string',
                'Quantity': 123
            },
            'MeteringRecordId': 'string',
            'Status': 'Success' | 'CustomerNotSubscribed' | 'DuplicateRecord'
        },
    ],
    'UnprocessedRecords': [
        {
            'Timestamp': datetime(2015, 1, 1),
            'CustomerIdentifier': 'string',
            'CustomerAWSAccountId': 'string',
            'Dimension': 'string',
            'Quantity': 123
        }
    ]
}
```

## `BatchMeterUsage`exemplo de código: Com ARN de licença
<a name="saas-batchmeterusage-licensearn-example"></a>

O exemplo de código a seguir é relevante para produtos SaaS que oferecem suporte a contratos simultâneos. Os `LicenseArn` e `CustomerAWSAccountId` são retornados pela `ResolveCustomer` API quando um comprador se registra no seu produto.

```
# NOTE: Your application will need to aggregate usage for the
#       customer for the hour and set the quantity as seen below.
# AWS Marketplace can only accept records for up to an hour in the past.
#
# LicenseArn and CustomerAWSAccountId are returned by the ResolveCustomer
# API when a buyer registers to your product

# Import AWS Python SDK
import boto3
from datetime import datetime


usageRecord = [{
    'LicenseArn' : 'licenseArn',
    'Timestamp': datetime(2015, 1, 1),
    'CustomerAWSAccountId': 'awsAccountId',
    'Dimension': 'string',
    'Quantity': 123
}]


marketplaceClient = boto3.client('meteringmarketplace')

response = marketplaceClient.batch_meter_usage(
    UsageRecords = usageRecord
)
```

### Exemplo de resposta
<a name="saas-batchmeterusage-licensearn-example-response"></a>

```
{
    'Results': [
        {
            'UsageRecord': {
                'Timestamp': datetime(2015, 1, 1),
                'CustomerIdentifier': 'string',
                'CustomerAWSAccountId': 'string',
                'Dimension': 'string',
                'Quantity': 123,
                'LicenseArn': 'string'
            },
            'MeteringRecordId': 'string',
            'Status': 'Success' | 'CustomerNotSubscribed' | 'DuplicateRecord'
        },
    ],
    'UnprocessedRecords': [
        {
            'Timestamp': datetime(2015, 1, 1),
            'CustomerIdentifier': 'string',
            'CustomerAWSAccountId': 'string',
            'Dimension': 'string',
            'Quantity': 123,
            'LicenseArn': 'string'
        }
    ]
}
```

## Exemplo de código `BatchMeterUsage` com marcação de alocação de uso (opcional)
<a name="saas-batchmeterusage-tagging"></a>

O exemplo de código a seguir é relevante para assinatura de SaaS e contrato com modelos da definição de preço do consumo, mas não para produtos de contrato de SaaS sem uso. O exemplo Python envia um registro de medição com tags apropriadas de alocação de uso para o AWS Marketplace para cobrar seus clientes por taxas de pagamento conforme o uso.

Este exemplo usa `LicenseArn` and`CustomerAWSAccountId`, que são retornados pela `ResolveCustomer` API quando um comprador se registra em seu produto. O Using `LicenseArn` oferece suporte a produtos com contratos simultâneos, em que um único comprador pode ter vários contratos ativos para o mesmo produto.

```
# NOTE: Your application will need to aggregate usage for the 
#       customer for the hour and set the quantity as seen below. 
# AWS Marketplace can only accept records for up to an hour in the past. 
#
# LicenseArn and CustomerAWSAccountId are returned by the
# ResolveCustomer API when a buyer registers to your product.

# Import AWS Python SDK
import boto3
from datetime import datetime, timezone

usageRecords = [
    {
        "Timestamp": datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0),
        "CustomerAWSAccountId": "111122223333",
        "Dimension": "Dimension1",
        "LicenseArn": "arn:aws:license-manager::123456789012:license:l-exampleLicense12345",
        "Quantity": 10000,
        "UsageAllocations": [
            {
                "AllocatedUsageQuantity": 5000,
                "Tags": [
                    {"Key": "user", "Value": "john"},
                    {"Key": "feature", "Value": "data-processing"},
                    {"Key": "job-name", "Value": "job11111"},
                ]
            },
            {
                "AllocatedUsageQuantity": 2500,
                "Tags": [
                    {"Key": "user", "Value": "john"},
                    {"Key": "feature", "Value": "data-storage"},
                    {"Key": "cluster-name", "Value": "cluster11111"},
                ]
            },
            {
                "AllocatedUsageQuantity": 2500,
                "Tags": [
                    {"Key": "user", "Value": "jane"},
                    {"Key": "feature", "Value": "data-storage"},
                    {"Key": "cluster-name", "Value": "cluster22222"},
                ]
            },
        ]
    },
    {
        "Timestamp": datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0),
        "CustomerAWSAccountId": "111122223333",
        "Dimension": "Dimension2",
        "LicenseArn": "arn:aws:license-manager::123456789012:license:l-exampleLicense12345",
        "Quantity": 2000,
        "UsageAllocations": [
            {
                "AllocatedUsageQuantity": 1000,
                "Tags": [
                    {"Key": "user", "Value": "john"},
                    {"Key": "feature", "Value": "data-processing"},
                    {"Key": "job-name", "Value": "job11111"},
                ]
            },
            {
                "AllocatedUsageQuantity": 1000,
                "Tags": [
                    {"Key": "user", "Value": "jane"},
                    {"Key": "feature", "Value": "data-processing"},
                    {"Key": "job-name", "Value": "job22222"},
                ]
            },
        ]
    }
]

marketplaceClient = boto3.client('meteringmarketplace', region_name='us-east-1')

response = marketplaceClient.batch_meter_usage(
    UsageRecords=usageRecords
)
```

Para obter mais informações sobre`BatchMeterUsage`, consulte [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)na *Referência AWS Marketplace Metering Service da API*.

### Exemplo de resposta
<a name="saas-batchmeterusage-tagging-response"></a>

```
{
    "Results": [
        {
            "UsageRecord": {
                "Timestamp": "2025-06-05T14:00:00Z",
                "CustomerIdentifier": "customerID",
                "CustomerAWSAccountId": "111122223333",
                "Dimension": "Dimension1",
                "Quantity": 10000,
                "LicenseArn": "arn:aws:license-manager::123456789012:license:l-exampleLicense12345",
                "UsageAllocations": [
                    {
                        "AllocatedUsageQuantity": 5000,
                        "Tags": [
                            { "Key": "user", "Value": "john" },
                            { "Key": "feature", "Value": "data-processing" },
                            { "Key": "job-name", "Value": "job11111" }
                        ]
                    },
                    {
                        "AllocatedUsageQuantity": 2500,
                        "Tags": [
                            { "Key": "user", "Value": "john" },
                            { "Key": "feature", "Value": "data-storage" },
                            { "Key": "cluster-name", "Value": "cluster11111" }
                        ]
                    },
                    {
                        "AllocatedUsageQuantity": 2500,
                        "Tags": [
                            { "Key": "user", "Value": "jane" },
                            { "Key": "feature", "Value": "data-storage" },
                            { "Key": "cluster-name", "Value": "cluster22222" }
                        ]
                    }
                ]
            },
            "MeteringRecordId": "8fjef98ejf",
            "Status": "Success"
        }
    ],
    "UnprocessedRecords": []
}
```