Obter itens de linha de consumo comercial cobrados da faturaGet invoice billed commercial consumption line items

Aplica-se a:Applies to:

  • Partner CenterPartner Center

Você pode usar os métodos a seguir para obter uma coleção de detalhes de itens de linha de fatura de consumo comercial (também conhecidos como itens de linha de uso com classificação diária) para uma fatura especificada.You can use the following methods to get a collection of details for commercial consumption invoice line items (also known as closed daily rated usage line items) for a specified invoice.

Essa API também dá suporte a tipos de provedor do Azure para assinaturas Microsoft Azure (MS-AZR-0145P).This API also supports azure provider types for Microsoft Azure (MS-AZR-0145P) subscriptions. Isso significa que essa API é um recurso compatível com versões anteriores.This means this API is a backward-compatible feature.

Pré-requisitosPrerequisites

  • Credenciais, conforme descrito em Autenticação do Partner Center.Credentials as described in Partner Center authentication. Esse cenário dá suporte à autenticação com aplicativos autônomos e aplicativos + credenciais de usuário.This scenario supports authentication with both standalone App and App+User credentials.

  • Um identificador de nota fiscal.An invoice identifier. Isso identifica a nota fiscal para a qual os itens de linha são recuperados.This identifies the invoice for which to retrieve the line items.

C#C#

Para obter os itens de linha comercial da fatura especificada, você deve recuperar o objeto de nota fiscal:To get the commercial line items for the specified invoice, you must retrieve the invoice object:

  1. Chame o método ById para obter uma interface para operações de faturas para a fatura especificada.Call the ById method to get an interface to invoice operations for the specified invoice.

  2. Chame o método Get ou getasync para recuperar o objeto de fatura.Call the Get or GetAsync method to retrieve the invoice object. O objeto de fatura contém todas as informações da fatura especificada.The invoice object contains all of the information for the specified invoice.

O provedor identifica a origem das informações de detalhe cobradas (por exemplo, OneTime).The Provider identifies the source of the billed detail information (for example, onetime). O InvoiceLineItemType especifica o tipo (por exemplo, UsageLineItem).The InvoiceLineItemType specifies the type (for example, UsageLineItem).

O código de exemplo a seguir usa um loop foreach para processar a coleção de itens de linha.The following example code uses a foreach loop to process the line items collection. Uma coleção separada de itens de linha é recuperada para cada InvoiceLineItemType.A separate collection of line items is retrieved for each InvoiceLineItemType.

Para obter uma coleção de itens de linha que correspondem a uma instância de InvoiceDetail :To get a collection of line items that correspond to an InvoiceDetail instance:

  1. Passe o billprovider e InvoiceLineItemType da instância para o método by .Pass the instance's BillingProvider and InvoiceLineItemType to the By method.

  2. Chame o método Get ou getasync para recuperar os itens de linha associados.Call the Get or GetAsync method to retrieve the associated line items.

  3. Crie um enumerador para atravessar a coleção, conforme mostrado no exemplo a seguir.Create an enumerator to traverse the collection as shown in the following example.

// 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);
        }
    }
}

Para obter um exemplo semelhante, consulte o seguinte:For a similar example, see the following:

  • Exemplo: Aplicativo de teste do consoleSample: Console test app
  • Projeto: exemplos de SDK do Partner CenterProject: Partner Center SDK Samples
  • Classe: GetBilledConsumptionReconLineItemsPaging.csClass: GetBilledConsumptionReconLineItemsPaging.cs

Solicitação RESTREST request

Sintaxe da solicitaçãoRequest syntax

Use a primeira sintaxe para retornar uma lista completa de cada item de linha para a fatura determinada.Use the first syntax to return a full list of every line item for the given invoice. Para grandes faturas, use a segunda sintaxe com um tamanho especificado e o deslocamento de base 0 para retornar uma lista paginada de itens de linha.For large invoices, use the second syntax with a specified size and 0-based offset to return a paged list of line items. Use a terceira sintaxe para obter a próxima página de itens de linha reconhecimento usando seekOperation = "Next" .Use the third syntax to get the next page of recon line items using seekOperation = "Next".

MétodoMethod URI da solicitaçãoRequest URI
GETGET {baseURL}/v1/invoices/{Invoice-ID}/LineItems? Provider = OneTime&invoicelineitemtype = usagelineitems&CurrencyCode = {CURRENCYCODE} http/1.1{baseURL}/v1/invoices/{invoice-id}/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode={currencycode} HTTP/1.1
GETGET {baseURL}/v1/invoices/{Invoice-ID}/LineItems? Provider = OneTime&invoicelineitemtype = usagelineitems&CurrencyCode = {currencycode} &tamanho = {size} http/1.1{baseURL}/v1/invoices/{invoice-id}/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode={currencycode}&size={size} HTTP/1.1
GETGET {baseURL}/v1/invoices/{Invoice-ID}/LineItems? Provider = OneTime&invoicelineitemtype = usagelineitems&CurrencyCode = {currencycode} &tamanho = {size} &SeekOperation = próximo{baseURL}/v1/invoices/{invoice-id}/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode={currencycode}&size={size}&seekOperation=Next

Parâmetros do URIURI parameters

Use os parâmetros de consulta e de URI a seguir ao criar a solicitação.Use the following URI and query parameters when creating the request.

NomeName TipoType ObrigatórioRequired DescriçãoDescription
ID da faturainvoice-id stringstring SimYes Uma cadeia de caracteres que identifica a nota fiscal.A string that identifies the invoice.
providerprovider stringstring SimYes O provedor: "OneTime".The provider: "OneTime".
invoice-line-item-typeinvoice-line-item-type stringstring SimYes O tipo de detalhe da nota fiscal: "UsageLineItems".The type of invoice detail: "UsageLineItems".
currencyCodecurrencyCode stringstring SimYes O código de moeda para os itens de linha cobrados.The currency code for the billed line items.
periodperiod stringstring SimYes O período para reconhecimento cobrado.The period for billed recon. exemplo: atual, anterior.example: current, previous.
tamanhosize númeronumber NãoNo O número máximo de itens a serem retornados.The maximum number of items to return. O tamanho padrão é 2000Default size is 2000
seekOperationseekOperation Cadeia de caracteresstring NoNo Defina seekOperation = Next para obter a próxima página de itens de linha reconhecimento.Set seekOperation=Next to get the next page of recon line items.

Cabeçalhos de solicitaçãoRequest headers

Para obter mais informações, confira Cabeçalhos REST do Partner Center.For more information, see Partner Center REST headers.

Corpo da solicitaçãoRequest body

Nenhum.None.

Resposta RESTREST response

Se for bem-sucedida, a resposta conterá a coleção de detalhes do item de linha.If successful, the response contains the collection of line item details.

Para o encargode item de linha, o valor Purchase é mapeado para New.For the line item ChargeType, the value Purchase is mapped to New. O valor de reembolso é mapeado para cancelamento.The value Refund is mapped to Cancel.

Códigos de êxito e de erro de respostaResponse success and error codes

Cada resposta vem com um código de status HTTP que indica êxito ou falha e informações de depuração adicionais.Each response comes with an HTTP status code that indicates success or failure and additional debugging information. Use uma ferramenta de rastreamento de rede para ler esse código, o tipo de erro e os parâmetros adicionais.Use a network trace tool to read this code, error type, and additional parameters. Para obter a lista completa, confira Códigos de erro REST do Partner Center.For the full list, see Partner Center REST error codes.

Exemplos de RESTREST examples

Exemplo de resposta de solicitação 1Request-response example 1

Os detalhes dessa solicitação e resposta REST de exemplo são os seguintes:The details for this example REST request and response are as follows:

  • Provedor: OneTimeProvider: OneTime
  • InvoiceLineItemType: UsageLineItemsInvoiceLineItemType: UsageLineItems
  • Período: anteriorPeriod: Previous

Exemplo de solicitação 1Request example 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

Exemplo de resposta 1Response example 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",
            "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
            "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,
            "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
            "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 resposta de solicitação 2Request-response example 2

Os detalhes dessa solicitação e resposta REST de exemplo são os seguintes:The details for this example REST request and response are as follows:

  • Provedor: OneTimeProvider: OneTime
  • InvoiceLineItemType: UsageLineItemsInvoiceLineItemType: UsageLineItems
  • Período: anteriorPeriod: Previous
  • SeekOperation: próximoSeekOperation: Next

Exemplo de solicitação 2Request example 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 2Response example 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,

            "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"
    }
}