

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Ejemplos de código para la integración de productos de SaaS
<a name="saas-code-examples"></a>

Puede usar los siguientes ejemplos de código para integrar su producto de software como servicio (SaaS) con las AWS Marketplace API necesarias para publicar y mantener su producto. Para obtener más información, consulte las siguientes secciones.

**Topics**
+ [ejemplo de código `ResolveCustomer`](#saas-resolvecustomer-example)
+ [ejemplo de código `GetEntitlement`](#saas-getentitlement-example)
+ [ejemplo de código `BatchMeterUsage`](#saas-batchmeterusage-example)
+ [`BatchMeterUsage`ejemplo de código: Con licencia ARN](#saas-batchmeterusage-licensearn-example)
+ [`BatchMeterUsage` con un ejemplo de código de etiquetado de asignación de uso (opcional)](#saas-batchmeterusage-tagging)

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

El siguiente ejemplo de código es relevante para todos los modelos de precios. El ejemplo de Python intercambia un `x-amzn-marketplace-token` token por un `CustomerIdentifier``ProductCode`,`LicenseArn`, y`CustomerAWSAccountId`. `CustomerAWSAccountId`Es el Cuenta de AWS ID asociado a la suscripción y `LicenseArn` es un identificador único para una licencia específica concedida. Se utilizan para el software adquirido a través de AWS Marketplace. Este código se ejecuta en una aplicación en el sitio web de registro, cuando se redirija a ella desde el AWS Marketplace Management Portal. La redirección es una solicitud POST que incluye el token. 

Para obtener más información al respecto`ResolveCustomer`, consulte [ResolveCustomer](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)la *referencia de la API del servicio de AWS Marketplace medición*.

**nota**  
Para una nueva implementación o al actualizar su integración, utilice el CustomerAWSAccountId en lugar 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
```

### Ejemplo de respuesta
<a name="saas-resolvecustomer-example-response"></a>

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

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

El siguiente ejemplo de código es relevante para los productos SaaS con el modelo de precios de contratos y contratos SaaS con consumo. En el ejemplo de Python se comprueba que un cliente tenga un derecho activo.

Para obtener más información al respecto`GetEntitlement`, consulte la [GetEntitlement](https://docs.aws.amazon.com/marketplaceentitlement/latest/APIReference/API_GetEntitlements.html)referencia de la *API de 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
```

### Ejemplo de respuesta
<a name="saas-getentitlement-example-response"></a>

El valor devuelto se corresponde con las dimensiones creadas al crear el producto en AWS Marketplace Management Portal.

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

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

El siguiente ejemplo de código es relevante para los modelos de precios de suscripciones y contratos SaaS con consumo, pero no para los productos de contrato SaaS sin consumo. El ejemplo de Python envía un registro de medición para cobrar AWS Marketplace a tus clientes las tarifas de pago por 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 obtener más información al respecto`BatchMeterUsage`, consulte la referencia de la API del servicio de [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)medición.AWS Marketplace *

### Ejemplo de respuesta
<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`ejemplo de código: Con licencia ARN
<a name="saas-batchmeterusage-licensearn-example"></a>

El siguiente ejemplo de código es relevante para los productos SaaS que admiten acuerdos simultáneos. La `ResolveCustomer` API `LicenseArn` `CustomerAWSAccountId` los devuelve cuando un comprador se registra en tu producto.

```
# 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
)
```

### Ejemplo de respuesta
<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'
        }
    ]
}
```

## `BatchMeterUsage` con un ejemplo de código de etiquetado de asignación de uso (opcional)
<a name="saas-batchmeterusage-tagging"></a>

El siguiente ejemplo de código es relevante para los modelos de precios de suscripciones y contratos SaaS con uso, pero no para los productos de contrato SaaS sin uso. En el ejemplo de Python se envía un registro de medición con etiquetas de asignación de uso adecuada a AWS Marketplace para cobrar a sus clientes las tarifas de pago por uso.

En este ejemplo`CustomerAWSAccountId`, se utilizan `LicenseArn` y, que la `ResolveCustomer` API devuelve cuando un comprador se registra en tu producto. El uso `LicenseArn` es compatible con productos con acuerdos simultáneos, en los que un solo comprador puede tener varios acuerdos activos para el mismo producto.

```
# 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 obtener más información al respecto`BatchMeterUsage`, consulte [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)la *referencia de la AWS Marketplace Metering Service API*.

### Ejemplo de respuesta
<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": []
}
```