

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 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 예제에서는 `x-amzn-marketplace-token` 토큰을 `CustomerIdentifier`, `ProductCode``LicenseArn`, 및 로 교환합니다`CustomerAWSAccountId`. `CustomerAWSAccountId`는 구독과 연결된 AWS 계정 ID이며, 부여된 특정 라이선스의 고유 식별자`LicenseArn`입니다. 이는를 통해 구매한 소프트웨어에 사용됩니다 AWS Marketplace. 이 코드는 AWS Marketplace Management Portal에서 리디렉션될 때 등록 웹 사이트의 애플리케이션에서 실행됩니다. 리디렉션은 토큰을 포함하는 POST 요청입니다.

`ResolveCustomer`에 대한 자세한 내용은 *AWS Marketplace 측정 서비스 API 참조*의 [ResolveCustomer](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)를 참조하세요.

**참고**  
새 구현 또는 통합 업데이트 시 CustomerIdentifier 대신 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 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"
}
```

## `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에서 `LicenseArn` 및를 `CustomerAWSAccountId` 반환합니다.

```
# 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 에 전송하여 고객에게 사용한 만큼만 지불 요금을 청구합니다.

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