

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Esempi di codice per l'integrazione di prodotti SaaS
<a name="saas-code-examples"></a>

È possibile utilizzare i seguenti esempi di codice per integrare il prodotto SaaS (Software as a Service) con Marketplace AWS APIs quelli necessari per la pubblicazione e la manutenzione del prodotto. Per ulteriori informazioni, consultare le sezioni indicate di seguito.

**Topics**
+ [`ResolveCustomer`esempio di codice](#saas-resolvecustomer-example)
+ [`GetEntitlement`esempio di codice](#saas-getentitlement-example)
+ [`BatchMeterUsage`esempio di codice](#saas-batchmeterusage-example)
+ [`BatchMeterUsage`esempio di codice: Con licenza ARN](#saas-batchmeterusage-licensearn-example)
+ [`BatchMeterUsage`con un esempio di codice di etichettatura per l'allocazione dell'utilizzo (opzionale)](#saas-batchmeterusage-tagging)

## `ResolveCustomer`esempio di codice
<a name="saas-resolvecustomer-example"></a>

Il seguente esempio di codice è rilevante per tutti i modelli di prezzo. L'esempio Python scambia un `x-amzn-marketplace-token` token con un`CustomerIdentifier`, `ProductCode``LicenseArn`, e. `CustomerAWSAccountId` `CustomerAWSAccountId`è l' Account AWS ID associato all'abbonamento ed `LicenseArn` è un identificatore univoco per una licenza specifica concessa. Vengono utilizzati per il software acquistato tramite Marketplace AWS. Questo codice viene eseguito in un'applicazione sul sito Web di registrazione, quando si viene reindirizzati lì da. Portale di gestione Marketplace AWS Il reindirizzamento è una richiesta POST che include il token. 

Per ulteriori informazioni [ResolveCustomer](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)in merito`ResolveCustomer`, consulta la sezione *Marketplace AWS Metering Service API* Reference.

**Nota**  
Per una nuova implementazione o per aggiornare l'integrazione, utilizza l'AWSAccountID cliente anziché 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
```

### Esempio di risposta
<a name="saas-resolvecustomer-example-response"></a>

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

## `GetEntitlement`esempio di codice
<a name="saas-getentitlement-example"></a>

Il seguente esempio di codice è rilevante per i prodotti SaaS con contratto e contratto SaaS con modello di prezzo al consumo. L'esempio Python verifica che un cliente disponga di un'autorizzazione attiva.

Per ulteriori informazioni in merito`GetEntitlement`, consulta l'articolo *Marketplace AWS Entitlement [GetEntitlement](https://docs.aws.amazon.com/marketplaceentitlement/latest/APIReference/API_GetEntitlements.html)*Service API Reference.

```
# 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 Marketplace AWS 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
```

### Esempio di risposta
<a name="saas-getentitlement-example-response"></a>

Il valore restituito corrisponde alle dimensioni create quando è stato creato il prodotto in. Portale di gestione Marketplace AWS

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

## `BatchMeterUsage`esempio di codice
<a name="saas-batchmeterusage-example"></a>

Il seguente esempio di codice è rilevante per i modelli di abbonamento e contratto SaaS con prezzi al consumo, ma non per i prodotti contrattuali SaaS senza consumo. L'esempio di Python invia un record di misurazione per addebitare Marketplace AWS le commissioni ai clienti. pay-as-you-go

```
# NOTE: Your application will need to aggregate usage for the 
#       customer for the hour and set the quantity as seen below. 
# Marketplace AWS can only accept records for up to an hour in the past. 
#
# productCode is supplied after the Marketplace AWS 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'
)
```

Per ulteriori informazioni [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)in merito`BatchMeterUsage`, consulta la sezione *Marketplace AWS Metering Service* API Reference.

### Esempio di risposta
<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`esempio di codice: Con licenza ARN
<a name="saas-batchmeterusage-licensearn-example"></a>

Il seguente esempio di codice è rilevante per i prodotti SaaS che supportano gli accordi concorrenti. I `LicenseArn` e `CustomerAWSAccountId` vengono restituiti dall'`ResolveCustomer`API quando un acquirente si registra al tuo prodotto.

```
# NOTE: Your application will need to aggregate usage for the
#       customer for the hour and set the quantity as seen below.
# Marketplace AWS 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
)
```

### Esempio di risposta
<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 esempio di codice di etichettatura per l'allocazione dell'utilizzo (opzionale)
<a name="saas-batchmeterusage-tagging"></a>

Il seguente esempio di codice è rilevante per gli abbonamenti e i contratti SaaS con modelli di prezzo di utilizzo, ma non per i prodotti contrattuali SaaS senza utilizzo. L'esempio di Python invia un record di misurazione con i tag di allocazione dell'uso appropriati per addebitare le Marketplace AWS commissioni ai clienti. pay-as-you-go

```
# NOTE: Your application will need to aggregate usage for the 
#       customer for the hour and set the quantity as seen below. 
# Marketplace AWS can only accept records for up to an hour in the past. 
#
# productCode is supplied after the Marketplace AWS 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"
)
```

*Per ulteriori informazioni in merito`BatchMeterUsage`, consulta l'API [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)Reference.AWS Marketplace Metering Service *

### Esempio di risposta
<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": []
        }
    ]
}
```