

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 AWS Marketplace APIs los necesarios 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 AWSAccount ID de cliente 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 AWS Marketplace para cobrar pay-as-you-go comisiones a tus clientes.

```
# 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 [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)referencia de la *API del servicio de AWS Marketplace medición*.

### 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. El ejemplo de Python envía un registro de medición con las etiquetas de asignación de uso adecuadas AWS Marketplace para cobrar pay-as-you-go las tarifas a sus clientes.

```
# 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
import time

# Option 1: Using CustomerIdentifier (for new or updated integrations, use the customer AWS account ID)
usageRecords = [
    {
        "Timestamp": int(time.time()),
        "CustomerIdentifier": "customerID",
        "Dimension": "Dimension1",
        "Quantity": 3,
        "UsageAllocations": [ 
            { 
                "AllocatedUsageQuantity": 2, 
                "Tags": [ 
                    { "Key": "BusinessUnit", "Value": "IT" },
                    { "Key": "AccountId", "Value": "*********" },
                ]
            },
            { 
                "AllocatedUsageQuantity": 1, 
                "Tags": [ 
                    { "Key": "BusinessUnit", "Value": "Finance" },
                    { "Key": "AccountId", "Value": "*********" },
                ]
            },
        ]
    }    
]

# Option 2: Using CustomerAWSAccountId (preferred)
# usageRecords = [
#     {
#         "Timestamp": int(time.time()),
#         "CustomerAWSAccountId": "awsAccountId",
#         "Dimension": "Dimension1",
#         "Quantity": 3,
#         "UsageAllocations": [ 
#             { 
#                 "AllocatedUsageQuantity": 2, 
#                 "Tags": [ 
#                     { "Key": "BusinessUnit", "Value": "IT" },
#                     { "Key": "AccountId", "Value": "*********" },
#                 ]
#             },
#             { 
#                 "AllocatedUsageQuantity": 1, 
#                 "Tags": [ 
#                     { "Key": "BusinessUnit", "Value": "Finance" },
#                     { "Key": "AccountId", "Value": "*********" },
#                 ]
#             },
#         ]
#     }    
# ]

marketplaceClient = boto3.client('meteringmarketplace')

response = marketplaceClient.batch_meter_usage(
    UsageRecords=usageRecords,
    ProductCode="testProduct"
)
```

Para obtener más información al respecto`BatchMeterUsage`, consulta [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": [
        {
            "Timestamp": "1634691015",
            "CustomerIdentifier": "customerId",
            "CustomerAWSAccountId": "awsAccountId",
            "Dimension": "Dimension1",
            "Quantity": 3,
            "UsageAllocations": [ 
                { 
                    "AllocatedUsageQuantity": 2, 
                    "Tags": [ 
                        { "Key": "BusinessUnit", "Value": "IT" },
                        { "Key": "AccountId", "Value": "*********" }
                    ]
                },
                { 
                    "AllocatedUsageQuantity": 1, 
                    "Tags": [ 
                        { "Key": "BusinessUnit", "Value": "Finance" },
                        { "Key": "AccountId", "Value": "*********" }
                    ]
                }
            ],
            "MeteringRecordId": "8fjef98ejf",
            "Status": "Success"
        }
    ],
    "UnprocessedRecords": [
        {
            "Timestamp": "1634691015",
            "CustomerIdentifier": "customerId",
            "CustomerAWSAccountId": "awsAccountId",
            "Dimension": "Dimension1",
            "Quantity": 3,
            "UsageAllocations": []
        }
    ]
}
```