Obter itens de linha de consumo comercial faturados

Nota

Você ainda pode usar essa API após 30 de setembro de 2024 para seus novos dados de uso de comércio gerados antes de setembro de 2022. Escolha a versão certa com base nestes detalhes:

  • Para acessar os itens de linha de uso diário para faturas de setembro de 2022 a setembro de 2024, use esta API até 30 de setembro de 2024, a menos que você já tenha mudado para a API v2 GA.
  • Para períodos de cobrança anteriores a setembro de 2022, obtenha itens de linha de uso com classificação diária somente com esta API.
  • Para obter itens de linha de uso classificados diariamente para faturas a partir de setembro de 2022, use apenas a API v2 GA.

Siga este link para se preparar para as novas APIs:

API de reconciliação de uso nominal diária faturada e não faturada v2 (GA)

Você pode usar os seguintes métodos para obter uma coleção de detalhes para itens de linha da fatura de consumo comercial (também conhecidos como itens de linha de uso diário fechado) para uma fatura especificada.

Importante

Os dados de utilização diária nominal não incluem os encargos relativos a estes produtos:

  • Reserva do Azure
  • Plano de poupança do Azure
  • Office
  • Dynamics
  • Microsoft Power Apps
  • Software perpétuo
  • Subscrição de software
  • Produto SaaS de terceiros

Pré-requisitos

  • Credenciais conforme descrito na autenticação do Partner Center. Este cenário oferece suporte à autenticação com credenciais autônomas de Aplicativo e Aplicativo+Usuário.

  • O ID da fatura para obter os itens de linha.

C#

Para obter os itens de linha comercial para a fatura especificada, você deve recuperar o objeto da fatura:

  1. Chame o método ById para obter uma interface para operações de fatura para a fatura especificada.

  2. Chame o método Get ou GetAsync para recuperar o objeto de fatura. O objeto de fatura contém todas as informações para a fatura especificada.

O Provedor identifica a fonte das informações detalhadas faturadas (por exemplo, uma vez). O InvoiceLineItemType especifica o tipo (por exemplo, UsageLineItem).

O código de exemplo a seguir usa um loop foreach para processar a coleção de itens de linha. Uma coleção separada de itens de linha é recuperada para cada InvoiceLineItemType.

Para obter uma coleção de itens de linha que correspondem a uma instância InvoiceDetail :

  1. Passe BillingProvider e InvoiceLineItemType da instância para o método By.

  2. Chame o método Get ou GetAsync para recuperar os itens de linha associados.

  3. Crie um enumerador para percorrer a coleção, conforme mostrado no exemplo a seguir.

// IAggregatePartner partnerOperations;
// string invoiceId;
// string curencyCode;
// string period;
// int pageMaxSizeReconLineItems = 2000;

// all the operations executed on this partner operation instance will share the same correlation Id but will differ in request Id
IPartner scopedPartnerOperations = partnerOperations.With(RequestContextFactory.Instance.Create(Guid.NewGuid()));

var seekBasedResourceCollection = scopedPartnerOperations.Invoices.ById(invoiceId).By("onetime", "usagelineitems", curencyCode, period, pageMaxSizeReconLineItems).Get();

var fetchNext = true;

ConsoleKeyInfo keyInfo;

var itemNumber = 1;
while (fetchNext)
{
    Console.Out.WriteLine("\tLine line items count: " + seekBasedResourceCollection.Items.Count());

    seekBasedResourceCollection.Items.ToList().ForEach(item =>
    {
        // Instance of type DailyRatedUsageLineItem
        if (item is DailyRatedUsageLineItem)
        {
            Type t = typeof(DailyRatedUsageLineItem);
            PropertyInfo[] properties = t.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                // Insert code here to work with the line item properties
            }
        }
        itemNumber++;
    });

    Console.Out.WriteLine("\tPress any key to fetch next data. Press the Escape (Esc) key to quit: \n");
    keyInfo = Console.ReadKey();

    if (keyInfo.Key == ConsoleKey.Escape)
    {
        break;
    }

    fetchNext = !string.IsNullOrWhiteSpace(seekBasedResourceCollection.ContinuationToken);

    if (fetchNext)
    {
        if (seekBasedResourceCollection.Links.Next.Headers != null && seekBasedResourceCollection.Links.Next.Headers.Any())
        {
            seekBasedResourceCollection = scopedPartnerOperations.Invoices.ById(invoiceId).By("onetime", "usagelineitems", curencyCode, period, pageMaxSizeReconLineItems).Seek(seekBasedResourceCollection.ContinuationToken, SeekOperation.Next);
        }
    }
}

Veja um exemplo:

Pedido REST

Sintaxe da solicitação

Use a primeira sintaxe para retornar uma lista completa de cada item de linha para a fatura fornecida. Para faturas grandes, use a segunda sintaxe com um tamanho especificado e deslocamento baseado em 0 para retornar uma lista paginada de itens de linha. Use a terceira sintaxe para obter a próxima página de itens de linha de reconhecimento usando seekOperation = "Next".

Método URI do pedido
GET {baseURL}/v1/invoices/{invoice-id}/lineitems?provider=onetime&invoicelineitemtype=usagelineitems¤cycode={currencycode} HTTP/1.1
GET {baseURL}/v1/invoices/{invoice-id}/lineitems?provider=onetime&invoicelineitemtype=usagelineitems¤cycode={currencycode}&size={size} HTTP/1.1
GET {baseURL}/v1/invoices/{invoice-id}/lineitems?provider=onetime&invoicelineitemtype=usagelineitems¤cycode={currencycode}&size={size}&seekOperation=Next

Parâmetros de URI

Use o seguinte URI e parâmetros de consulta ao criar a solicitação.

Nome Type Obrigatório Description
ID da fatura string Sim Uma cadeia de caracteres que identifica a fatura.
fornecedor string Sim O provedor: "OneTime".
tipo de item de linha de fatura string Sim O tipo de detalhe da fatura: "UsageLineItems".
currencyCode string Sim O código de moeda para os itens de linha cobrados.
período string Sim O período para o reconhecimento faturado. exemplo: atual, anterior.
size Número Não O número máximo de itens a devolver. O tamanho padrão é 2000
seekOperation string Não Defina seekOperation=Next para obter a próxima página de itens de linha de reconhecimento.

Cabeçalhos do pedido

Para obter mais informações, consulte Cabeçalhos REST do Partner Center.

Corpo do pedido

Nenhum.

Resposta do REST

Se bem-sucedida, a resposta contém a coleção de detalhes do item de linha.

Para o item de linha ChargeType, o valor Compra é mapeado para Novo. O valor Reembolso é mapeado para Cancelar.

Códigos de sucesso e erro de resposta

Cada resposta vem com um código de status HTTP que indica sucesso ou falha e outras informações de depuração. Use uma ferramenta de rastreamento de rede para ler esse código, tipo de erro e mais parâmetros. Para obter a lista completa, consulte Códigos de erro REST do Partner Center.

Exemplos REST

Exemplo de solicitação-resposta 1

Os detalhes para este exemplo de solicitação e resposta REST são os seguintes:

  • Fornecedor: OneTime
  • InvoiceLineItemType: UsageLineItems
  • Período: Anterior

Exemplo de solicitação 1

GET https://api.partnercenter.microsoft.com/v1/invoices/T000001234/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode=usd&period=previous&size=2000 HTTP/1.1
Authorization: Bearer <token>
Accept: application/json
MS-RequestId: 1234ecb8-37af-45f4-a1a1-358de3ca2b9e
MS-CorrelationId: 5e612512-4345-4bb0-866e-47aeda031234
X-Locale: en-US
MS-PartnerCenter-Application: Partner Center .NET SDK Samples
Host: api.partnercenter.microsoft.com

Importante

A partir de junho de 2023, a versão 3.4.0 mais recente do SDK do .NET do Partner Center foi arquivada. Você pode baixar a versão do SDK do GitHub, juntamente com um arquivo readme que contém informações úteis.

Os parceiros são incentivados a continuar a usar as APIs REST do Partner Center.

Exemplo de resposta 1

HTTP/1.1 200 OK
Content-Length: 2484
Content-Type: application/json; charset=utf-8
MS-CorrelationId: 5e612512-4345-4bb0-866e-47aeda031234
MS-RequestId: 1234ecb8-37af-45f4-a1a1-358de3ca2b9e
MS-CV: bpqyomePDUqrSSYC.0
MS-ServerId: 202010406
Date: Wed, 20 Feb 2019 19:59:27 GMT

{
    "totalCount": 2,
    "items": [
        {
            "partnerId": "2b8940db-5089-539c-e757-520ed1d1bc88",
            "partnerName": "",
            "customerId": "",
            "customerName": "",
            "customerDomainName": "",
            "invoiceNumber": "T000001234",
            "productId": "",
            "skuId": "",
            "availabilityId": "",
            "skuName": "Test Test on Windows 2012 R2 (WebHost)",
            "productName": "Test Test on Windows",
            "publisherName": "Test",
            "publisherId": "28503520",
            "subscriptionId": "12345678-9d62-4a85-8fd0-91a87c261bc4",
            "subscriptionDescription": "Subscription 10",
            "chargeStartDate": "2018-11-01T00:00:00Z",
            "chargeEndDate": "2018-12-01T00:00:00Z",
            "usageDate": "2018-11-13T00:00:00Z",
            "meterType": "1 Compute Hour - 1core",
            "meterCategory": "Virtual Machine Licenses",
            "meterId": "1core",
            "meterSubCategory": "Test Test on Windows",
            "meterName": "Test Test on Windows - Test Test on Windows 2012 R2 (WebHost) - 1 Core Hours",
            "meterRegion": "",
            "unitOfMeasure": "1 Hour",
            "resourceLocation": "EASTUS2",
            "consumedService": "Microsoft.Compute",
            "resourceGroup": "TestWINRG",
            "resourceUri": "/subscriptions/12345678-9d62-4a85-8fd0-91a87c261bc4/resourceGroups/TestWINRG/providers/Microsoft.Compute/virtualMachines/testWinTest",
            "tags": "",
            "additionalInfo": "{  \"ImageType\": null,  \"ServiceType\": \"Standard_B1s\",  \"VMName\": null,  \"VMProperties\": null,  \"UsageType\": \"ComputeHR_SW\"}",
            "serviceInfo1": "",
            "serviceInfo2": "",
            "customerCountry": "",
            "mpnId": "1234567",
            "resellerMpnId": "",
            "chargeType": "new",
            "unitPrice": 0.0209496384791679,
            "quantity": 23.200004,
            "unitType": "1 Hour",
            "billingPreTaxTotal": 0.486031696515249,
            "billingCurrency": "USD",
            "pricingPreTaxTotal": 0.486031696515249,
            "pricingCurrency": "USD",
            "entitlementId": "3f47bcf1-965d-40a1-a2bc-3d5db3653250",
	    "entitlementDescription": "Partner Subscription",
	    "pcToBCExchangeRate": 1,
	    "pcToBCExchangeRateDate": "2019-08-01T00:00:00Z",
	    "effectiveUnitPrice": 0,
	    "rateOfPartnerEarnedCredit": 0,
	    "rateOfCredit": 0,
	    "creditType": "Credit Not Applied",
	    "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
	    "benefitOrderId": "5ea053d6-4a0d-46ef-bc82-15065b475d01",
	    "benefitId": "28ddab06-2c5b-479e-88bb-7b7bfda4e7fd",
	    "benefitType": "SavingsPlan",
            "attributes": {
                "objectType": "DailyRatedUsageLineItem"
            }
        },
        {
            "partnerId": "2b8940db-5089-539c-e757-520ed1d1bc88",
            "partnerName": "",
            "customerId": "",
            "customerName": "",
            "customerDomainName": "",
            "invoiceNumber": "T000001234",
            "productId": "",
            "skuId": "",
            "availabilityId": "",
            "skuName": "Test Test on Ubuntu 16.04 (WebHost)",
            "productName": "Test Test on Linux",
            "publisherName": "Test",
            "publisherId": "28503520",
            "subscriptionId": "12345678-9d62-4a85-8fd0-91a87c261bc4",
            "subscriptionDescription": "Subscription 10",
            "chargeStartDate": "2018-11-01T00:00:00Z",
            "chargeEndDate": "2018-12-01T00:00:00Z",
            "usageDate": "2018-11-13T00:00:00Z",
            "meterType": "1 Compute Hour - 1core",
            "meterCategory": "Virtual Machine Licenses",
            "meterId": "1core",
            "meterSubCategory": "Test Test on Linux",
            "meterName": "Test Test on Linux - Test Test on Ubuntu 16.04 (WebHost) - 1 Core Hours",
            "meterRegion": "",
            "unitOfMeasure": "1 Hour",
            "resourceLocation": "EASTUS",
            "consumedService": "Microsoft.Compute",
            "resourceGroup": "TESTRG",
            "resourceUri": "/subscriptions/12345678-9d62-4a85-8fd0-91a87c261bc4/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/testUbuntuTest",
            "tags": "",
            "additionalInfo": "{  \"ImageType\": null,  \"ServiceType\": \"Standard_B1s\",  \"VMName\": null,  \"VMProperties\": null,  \"UsageType\": \"ComputeHR_SW\"}",
            "serviceInfo1": "",
            "serviceInfo2": "",
            "customerCountry": "",
            "mpnId": "1234567",
            "resellerMpnId": "",
            "chargeType": "new",
            "unitPrice": 0.0209951014286867,
            "quantity": 23.350007,
            "unitType": "1 Hour",
            "billingPreTaxTotal": 0.490235765325545,
            "billingCurrency": "USD",
            "pricingPreTaxTotal": 0.490235765325545,
            "pricingCurrency": "USD",
            "entitlementId": "66bada28-271e-4b7a-aaf5-c0ead6312345",
            "entitlementDescription": "Partner Subscription",
            "pcToBCExchangeRate": 1,
            "pcToBCExchangeRateDate": "2019-08-01T00:00:00Z",
            "effectiveUnitPrice": 0.1999968000511991808131,
            "rateOfPartnerEarnedCredit": 0,
            "rateOfCredit": 1,
            "creditType": "Azure Credit Applied",
            "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
	    "benefitOrderId": "",
            "benefitId": "",
            "benefitType": "Charge",
            "attributes": {
                "objectType": "DailyRatedUsageLineItem"
            }
        }
    ],
    "links": {
        "self": {
            "uri": "/invoices/T000001234/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode=usd&period=previous&size=2000",
            "method": "GET",
            "headers": []
        },
        "next": {
            "uri": "/invoices/T000001234/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode=usd&period=previous&size=2000&seekOperation=Next",
            "method": "GET",
            "headers": [
                {
                    "key": "MS-ContinuationToken",
                    "value": "AQAAAA=="
                }
            ]
        }
    },
    "attributes": {
        "objectType": "Collection"
    }
}

Exemplo de solicitação-resposta 2

Os detalhes para este exemplo de solicitação e resposta REST são os seguintes:

  • Fornecedor: OneTime
  • InvoiceLineItemType: UsageLineItems
  • Período: Anterior
  • SeekOperation: Seguinte

Exemplo de solicitação 2

GET https://api.partnercenter.microsoft.com/v1/invoices/T000001234/lineitems?provider=onetime&invoiceLineItemType=usagelineitems&currencyCode=usd&period=previous&size=2000&seekoperation=next HTTP/1.1
Authorization: Bearer <token>
Accept: application/json
MS-ContinuationToken: d19617b8-fbe5-4684-a5d8-0230972fb0cf,0705c4a9-39f7-4261-ba6d-53e24a9ce47d_a4ayc/80/OGda4BO/1o/V0etpOqiLx1JwB5S3beHW0s=,0d81c700-98b4-4b13-9129-ffd5620f72e7
MS-RequestId: 1234ecb8-37af-45f4-a1a1-358de3ca2b9e
MS-CorrelationId: 5e612512-4345-4bb0-866e-47aeda031234
X-Locale: en-US
MS-PartnerCenter-Application: Partner Center .NET SDK Samples
Host: api.partnercenter.microsoft.com

Exemplo de resposta 2

HTTP/1.1 200 OK
Content-Length: 2484
Content-Type: application/json; charset=utf-8
MS-CorrelationId: 5e612512-4345-4bb0-866e-47aeda031234
MS-RequestId: 1234ecb8-37af-45f4-a1a1-358de3ca2b9e
MS-CV: bpqyomePDUqrSSYC.0
MS-ServerId: 202010406
Date: Wed, 20 Feb 2019 19:59:27 GMT

{
    "totalCount": 1,
    "items": [
          {
            "partnerId": "2b8940db-5089-539c-e757-520ed1d1bc88",
            "partnerName": "",
            "customerId": "",
            "customerName": "",
            "customerDomainName": "",
            "invoiceNumber": "T000001234",
            "productId": "",
            "skuId": "",
            "availabilityId": "",
            "skuName": "Test Test on Windows 2012 R2 (WebHost)",
            "productName": "Test Test on Windows",
            "publisherName": "Test",
            "publisherId": "28503520",
            "subscriptionId": "12345678-9d62-4a85-8fd0-91a87c261bc4",
            "subscriptionDescription": "Subscription 10",
            "chargeStartDate": "2018-11-01T00:00:00Z",
            "chargeEndDate": "2018-12-01T00:00:00Z",
            "usageDate": "2018-11-13T00:00:00Z",
            "meterType": "1 Compute Hour - 1core",
            "meterCategory": "Virtual Machine Licenses",
            "meterId": "1core",
            "meterSubCategory": "Test Test on Windows",
            "meterName": "Test Test on Windows - Test Test on Windows 2012 R2 (WebHost) - 1 Core Hours",
            "meterRegion": "",
            "unitOfMeasure": "1 Hour",
            "resourceLocation": "EASTUS2",
            "consumedService": "Microsoft.Compute",
            "resourceGroup": "TestWINRG",
            "resourceUri": "/subscriptions/12345678-9d62-4a85-8fd0-91a87c261bc4/resourceGroups/TestWINRG/providers/Microsoft.Compute/virtualMachines/testWinTest",
            "tags": "",
            "additionalInfo": "{  \"ImageType\": null,  \"ServiceType\": \"Standard_B1s\",  \"VMName\": null,  \"VMProperties\": null,  \"UsageType\": \"ComputeHR_SW\"}",
            "serviceInfo1": "",
            "serviceInfo2": "",
            "customerCountry": "",
            "mpnId": "1234567",
            "resellerMpnId": "",
            "chargeType": "new",
            "unitPrice": 0.0209496384791679,
            "quantity": 23.200004,
            "unitType": "1 Hour",
            "billingPreTaxTotal": 0.486031696515249,
            "billingCurrency": "USD",
            "pricingPreTaxTotal": 0.486031696515249,
            "pricingCurrency": "USD",
            "entitlementId": "66bada28-271e-4b7a-aaf5-c0ead6312345",
            "entitlementDescription": "Partner Subscription",
            "pcToBCExchangeRate": 1,
            "pcToBCExchangeRateDate": "2019-08-01T00:00:00Z",
            "effectiveUnitPrice": 0.1835431430074643112595,
            "rateOfPartnerEarnedCredit": 0.15,
            "rateOfCredit": 0.15,
            "creditType": "Partner Earned Credit Applied",
            "benefitOrderId": "",
            "benefitId": "",
            "benefitType": "Charge",
            "attributes": {
                "objectType": "DailyRatedUsageLineItem"
            }
        }
    ],
    "links": {
        "self": {
             "uri": "/invoices/T000001234/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode=usd&period=previous&size=2000",
            "method": "GET",
            "headers": []
        }
    },
    "attributes": {
        "objectType": "Collection"
    }
}