

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Contoh kode untuk integrasi produk SaaS
<a name="saas-code-examples"></a>

Anda dapat menggunakan contoh kode berikut untuk mengintegrasikan perangkat lunak Anda sebagai produk layanan (SaaS) dengan AWS Marketplace APIs yang diperlukan untuk menerbitkan dan memelihara produk Anda. Untuk informasi selengkapnya, silakan lihat bagian-bagian berikut ini.

**Topics**
+ [`ResolveCustomer`contoh kode](#saas-resolvecustomer-example)
+ [`GetEntitlement`contoh kode](#saas-getentitlement-example)
+ [`BatchMeterUsage`contoh kode](#saas-batchmeterusage-example)
+ [`BatchMeterUsage`contoh kode: Dengan Lisensi ARN](#saas-batchmeterusage-licensearn-example)
+ [`BatchMeterUsage`dengan contoh kode penandaan alokasi penggunaan (Opsional)](#saas-batchmeterusage-tagging)

## `ResolveCustomer`contoh kode
<a name="saas-resolvecustomer-example"></a>

Contoh kode berikut relevan untuk semua model penetapan harga. Contoh Python menukar `x-amzn-marketplace-token` token untuk`CustomerIdentifier`,, `ProductCode``LicenseArn`, dan. `CustomerAWSAccountId` `CustomerAWSAccountId`Ini adalah Akun AWS ID yang terkait dengan langganan, dan `LicenseArn` merupakan pengidentifikasi unik untuk lisensi tertentu yang diberikan. Ini digunakan untuk perangkat lunak yang dibeli melalui AWS Marketplace. Kode ini berjalan dalam aplikasi di situs web pendaftaran Anda, ketika Anda diarahkan ke sana dari Portal Manajemen AWS Marketplace. Pengalihan adalah permintaan POST yang menyertakan token. 

Untuk informasi selengkapnya`ResolveCustomer`, lihat [ResolveCustomer](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)di *Referensi AWS Marketplace API Layanan Pengukuran*.

**catatan**  
Untuk implementasi baru atau saat memperbarui integrasi Anda, gunakan AWSAccount ID Pelanggan sebagai gantinya 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
```

### Contoh tanggapan
<a name="saas-resolvecustomer-example-response"></a>

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

## `GetEntitlement`contoh kode
<a name="saas-getentitlement-example"></a>

Contoh kode berikut relevan untuk produk SaaS dengan kontrak dan kontrak SaaS dengan model harga konsumsi. Contoh Python memverifikasi bahwa pelanggan memiliki hak aktif.

Untuk informasi selengkapnya`GetEntitlement`, lihat [GetEntitlement](https://docs.aws.amazon.com/marketplaceentitlement/latest/APIReference/API_GetEntitlements.html)di *Referensi API Layanan AWS Marketplace Hak*.

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

### Contoh tanggapan
<a name="saas-getentitlement-example-response"></a>

Nilai yang dikembalikan sesuai dengan dimensi yang dibuat saat Anda membuat produk di Portal Manajemen 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"
}
```

## `BatchMeterUsage`contoh kode
<a name="saas-batchmeterusage-example"></a>

Contoh kode berikut relevan untuk langganan SaaS dan kontrak dengan model harga konsumsi, tetapi tidak untuk produk kontrak SaaS tanpa konsumsi. Contoh Python mengirimkan catatan pengukuran untuk membebankan biaya AWS Marketplace kepada pelanggan Anda. 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. 
# 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'
)
```

Untuk informasi selengkapnya`BatchMeterUsage`, lihat [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)di *Referensi AWS Marketplace API Layanan Pengukuran*.

### Contoh tanggapan
<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`contoh kode: Dengan Lisensi ARN
<a name="saas-batchmeterusage-licensearn-example"></a>

Contoh kode berikut relevan untuk produk SaaS yang mendukung Perjanjian Bersamaan. `LicenseArn`Dan `CustomerAWSAccountId` dikembalikan oleh `ResolveCustomer` API ketika pembeli mendaftar ke produk Anda.

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

### Contoh tanggapan
<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`dengan contoh kode penandaan alokasi penggunaan (Opsional)
<a name="saas-batchmeterusage-tagging"></a>

Contoh kode berikut relevan untuk langganan SaaS dan kontrak dengan model harga penggunaan, tetapi tidak untuk produk kontrak SaaS tanpa penggunaan. Contoh Python mengirimkan catatan pengukuran dengan tag alokasi penggunaan yang sesuai untuk membebankan biaya AWS Marketplace kepada pelanggan Anda. 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. 
# 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"
)
```

Untuk informasi selengkapnya`BatchMeterUsage`, lihat [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)di *Referensi AWS Marketplace Metering Service API*.

### Contoh tanggapan
<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": []
        }
    ]
}
```