

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# SaaS 產品整合的程式碼範例
<a name="saas-code-examples"></a>

您可以使用下列程式碼範例，將軟體即服務 (SaaS) 產品與發佈和維護產品所需的 AWS Marketplace APIs 整合。如需詳細資訊，請參閱下列區段。

**Topics**
+ [`ResolveCustomer` 程式碼範例](#saas-resolvecustomer-example)
+ [`GetEntitlement` 程式碼範例](#saas-getentitlement-example)
+ [`BatchMeterUsage` 程式碼範例](#saas-batchmeterusage-example)
+ [`BatchMeterUsage` 程式碼範例：使用授權 ARN](#saas-batchmeterusage-licensearn-example)
+ [`BatchMeterUsage` 使用用量配置標記程式碼範例 （選用）](#saas-batchmeterusage-tagging)

## `ResolveCustomer` 程式碼範例
<a name="saas-resolvecustomer-example"></a>

下列程式碼範例適用於所有定價模型。Python 範例會交換 `CustomerIdentifier`、`LicenseArn`、 `ProductCode`和 的`x-amzn-marketplace-token`字符`CustomerAWSAccountId`。`CustomerAWSAccountId` 是與訂閱相關聯的 AWS 帳戶 ID，`LicenseArn`也是特定授權的唯一識別符。這些用於透過 購買的軟體 AWS Marketplace。當您從 重新導向時，此程式碼會在註冊網站上的應用程式中執行 AWS Marketplace 管理入口網站。重新導向是包含字符的 POST 請求。

如需 的詳細資訊`ResolveCustomer`，請參閱*AWS Marketplace 《計量服務 API 參考*》中的 [ResolveCustomer](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)。

**注意**  
對於新實作或更新整合時，請使用 CustomerAWSAccountId 而非 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
```

### 回應範例
<a name="saas-resolvecustomer-example-response"></a>

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

## `GetEntitlement` 程式碼範例
<a name="saas-getentitlement-example"></a>

下列程式碼範例適用於具有合約的 SaaS 產品，以及具有消耗定價模型的 SaaS 合約。Python 範例會驗證客戶是否具有作用中的權限。

如需 的詳細資訊`GetEntitlement`，請參閱*AWS Marketplace 《權利服務 API 參考*》中的 [GetEntitlement](https://docs.aws.amazon.com/marketplaceentitlement/latest/APIReference/API_GetEntitlements.html)。

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

### 回應範例
<a name="saas-getentitlement-example-response"></a>

傳回的值對應於您在 中建立產品時所建立的維度 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` 程式碼範例
<a name="saas-batchmeterusage-example"></a>

下列程式碼範例與使用定價模式的 SaaS 訂閱和合約相關，但不與不使用 的 SaaS 合約產品相關。Python 範例會將計量記錄傳送至 AWS Marketplace ，向您的客戶收取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'
)
```

如需 的詳細資訊`BatchMeterUsage`，請參閱*AWS Marketplace 《計量服務 API 參考*》中的 [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)。

### 回應範例
<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` 程式碼範例：使用授權 ARN
<a name="saas-batchmeterusage-licensearn-example"></a>

下列程式碼範例與支援並行協議的 SaaS 產品相關。當買方註冊您的產品時，`ResolveCustomer`API `CustomerAWSAccountId`會傳回 `LicenseArn`和 。

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

### 回應範例
<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` 使用用量配置標記程式碼範例 （選用）
<a name="saas-batchmeterusage-tagging"></a>

下列程式碼範例與 SaaS 訂閱和具有用量定價模型的合約相關，但不適用於不使用 的 SaaS 合約產品。Python 範例會傳送具有適當用量分配標籤的計量記錄給 AWS Marketplace ，以向您的客戶收取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"
)
```

如需 的詳細資訊`BatchMeterUsage`，請參閱《 *AWS Marketplace Metering Service API 參考*》中的 [BatchMeterUsage](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_BatchMeterUsage.html)。

### 回應範例
<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": []
        }
    ]
}
```