Obter itens de linha de consumo comercial não cobrados da faturaGet invoice unbilled commercial consumption line items

Aplica-se a:Applies to:

  • Partner CenterPartner Center

Como obter uma coleção de detalhes do item de linha de consumo comercial não cobrado.How to get a collection of unbilled commercial consumption line item details.

Você pode usar os seguintes métodos para obter uma coleção de detalhes de itens de linha de consumo comercial não faturados (também conhecidos como itens de linha de uso aberto) programaticamente.You can use the following methods to get a collection of details unbilled commercial consumption line items (also known as open usage line items) programmatically.

Observação

O uso com classificação diária normalmente leva 24 horas para aparecer no Partner Center ou para ser acessado por meio da API.Daily-rated usage normally takes 24 hours to appear in Partner Center or to be accessed through the API.

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 para a fatura especificada:To get the line items for the specified invoice:

  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 detalhes não faturados (por exemplo, OneTime).The Provider identifies the source of the unbilled 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 InvoiceLineItems .The following example code uses a foreach loop to process the InvoiceLineItems 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 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("unbilled").By("onetime", "usagelineitems", curencyCode, period, pageMaxSizeReconLineItems).Get();

var fetchNext = true;

ConsoleKeyInfo keyInfo;

var itemNumber = 1;
while (fetchNext)
{
    Console.Out.WriteLine("\tLine 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("unbilled").By("onetime", "usagelineitems", curencyCode, period, pageMaxSizeReconLineItems).Seek(seekBasedResourceCollection.ContinuationToken, SeekOperation.Next);
        }
    }
}

Para obter um exemplo semelhante, consulte:For a similar example, see:

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

Solicitação RESTREST request

Sintaxe da solicitaçãoRequest syntax

Você pode usar as sintaxes a seguir para sua solicitação REST, dependendo de seu caso de uso.You can use the following syntaxes for your REST request, depending on your use case. Para obter mais informações, consulte as descrições de cada sintaxe.For more information, see the descriptions for each syntax.

MétodoMethod URI da solicitaçãoRequest URI Descrição do caso de uso da sintaxeDescription of syntax use case
GETGET {baseURL}/v1/invoices/unbilled/LineItems? Provider = OneTime&invoicelineitemtype = usagelineitems&CurrencyCode = {currencycode} &period = {period} http/1.1{baseURL}/v1/invoices/unbilled/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode={currencycode}&period={period} HTTP/1.1 Use essa sintaxe para retornar uma lista completa de todos os itens de linha da fatura determinada.Use this syntax to return a full list of every line item for the given invoice.
GETGET {baseURL}/v1/invoices/unbilled/LineItems? Provider = OneTime&invoicelineitemtype = usagelineitems&CurrencyCode = {currencycode} &period = {period} &tamanho = {size} http/1.1{baseURL}/v1/invoices/unbilled/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode={currencycode}&period={period}&size={size} HTTP/1.1 Use essa sintaxe para faturas grandes.Use this syntax for large invoices. Use essa sintaxe com um tamanho especificado e um deslocamento com base em 0 para retornar uma lista paginável de itens de linha.Use this syntax with a specified size and 0-based offset to return a paged list of line items.
GETGET {baseURL}/v1/invoices/unbilled/LineItems? Provider = OneTime&invoicelineitemtype = usagelineitems&CurrencyCode = {currencycode} &period = {period} &tamanho = {size} &SeekOperation = próximo{baseURL}/v1/invoices/unbilled/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode={currencycode}&period={period}&size={size}&seekOperation=Next Use essa sintaxe para obter a próxima página de itens de linha de reconciliação usando seekOperation = "Next" .Use this syntax to get the next page of reconciliation line items using 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
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", "UsageLineItems".The type of invoice detail: "UsageLineItems", "UsageLineItems".
currencyCodecurrencyCode stringstring SimYes O código de moeda para os itens de linha não cobrados.The currency code for the unbilled line items.
periodperiod stringstring SimYes O período para reconhecimento não faturadas (por exemplo: atual, anterior).The period for unbilled recon (for example: current, previous).

Anterior – se o ciclo de cobrança for 01/01/2020 – 01/31/2020, é provável que sua fatura seja gerada entre 02/06/2020 e 02/08/2020 hora UTC.Previous – if the billing cycle is 01/01/2020 – 01/31/2020 then, most likely that your invoice is generated between 02/06/2020 and 02/08/2020 UTC time. Se você precisar consultar os dados de uso não faturados do ciclo de cobrança (01/01/2020 – 01/31/2020) em qualquer momento entre 02/01/2020 e a data gerada pela nota fiscal (que está entre 02/06/2020 e 02/08/2020 hora UTC), então, você precisará escolher período como "anterior".If you need to query your unbilled usage data of the billing cycle (01/01/2020 – 01/31/2020) on any time between 02/01/2020 and the invoice-generated date (which is between 02/06/2020 and 02/08/2020 UTC time), then, you need to choose Period as "Previous".

Atual – se o ciclo de cobrança for 01/01/2020 – 01/31/2020, é provável que sua fatura seja gerada entre 02/06/2020 e 02/08/2020 hora UTC.Current – if the billing cycle is 01/01/2020 – 01/31/2020 then, most likely that your invoice is generated between 02/06/2020 and 02/08/2020 UTC time. Se você precisar consultar os dados de uso não faturados do ciclo de cobrança (01/01/2020 – 01/31/2020) em qualquer momento entre 01/01/2020 e 01/31/2020 que esteja dentro de seu ciclo de cobrança, então, você precisará escolher período como "atual".If you need to query your unbilled usage data of the billing cycle (01/01/2020 – 01/31/2020) on any time between 01/01/2020 and 01/31/2020 which is within your billing cycle, then, you need to choose Period as "Current".
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 é 2000.The default size is 2000.
seekOperationseekOperation Cadeia de caracteresstring NoNo Defina seekOperation=Next para obter a próxima página de itens de linha de reconciliação.Set seekOperation=Next to get the next page of reconciliation 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 e o valor reembolso é mapeado para Cancel.For the line item ChargeType, the value Purchase is mapped to New and 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 solicitação-respostaRequest-response examples

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

Os detalhes a seguir se aplicam a este exemplo:The following details apply to this example:

  • 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/unbilled/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": "00083575-bbd0-54de-b2ad-0f5b0e927d71",
            "partnerName": "MTBC",
            "customerId": "",
            "customerName": "",
            "customerDomainName": "",
            "invoiceNumber": "",
            "productId": "",
            "skuId": "",
            "availabilityId": "",
            "skuName": "VM-Series Next-Generation Firewall (Bundle 2 PAYG)",
            "productName": "VM-Series Next Generation Firewall",
            "publisherName": "Test Alto Networks, Inc.",
            "publisherId": "",
            "subscriptionId": "12345678-04d9-421c-baf8-e3b8dd62ddba",
            "subscriptionDescription": "Pay-As-You-Go",
            "chargeStartDate": "2019-01-01T00:00:00Z",
            "chargeEndDate": "2019-02-01T00:00:00Z",
            "usageDate": "2019-01-01T00:00:00Z",
            "meterType": "1 Compute Hour - 4core",
            "meterCategory": "Virtual Machine Licenses",
            "meterId": "4core",
            "meterSubCategory": "VM-Series Next Generation Firewall",
            "meterName": "VM-Series Next Generation Firewall - VM-Series Next-Generation Firewall (Bundle 2 PAYG) - 4 Core Hours",
            "meterRegion": "",
            "unitOfMeasure": "1 Hour",
            "resourceLocation": "EASTUS",
            "consumedService": "Microsoft.Compute",
            "resourceGroup": "ECH-PAN-RG",
            "resourceUri": "/subscriptions/12345678-04d9-421c-baf8-e3b8dd62ddba/resourceGroups/ECH-PAN-RG/providers/Microsoft.Compute/virtualMachines/echpanfw",
            "tags": "",
            "additionalInfo": "{  \"ImageType\": null,  \"ServiceType\": \"Standard_D3_v2\",  \"VMName\": null,  \"VMProperties\": null,  \"UsageType\": \"ComputeHR_SW\"}",
            "serviceInfo1": "",
            "serviceInfo2": "",
            "customerCountry": "",
            "mpnId": "1234567",
            "resellerMpnId": "",
            "chargeType": "",
            "unitPrice": 1.2799888920023,
            "quantity": 24.0,
            "unitType": "",
            "billingPreTaxTotal": 30.7197334080551,
            "billingCurrency": "USD",
            "pricingPreTaxTotal": 30.7197334080551,
            "pricingCurrency": "USD",
            "entitlementId": "1234547f-b249-4edd-9319-637862d8c0b4",
            "entitlementDescription": "Partner Subscription",
            "pcToBCExchangeRate": 1,
            "pcToBCExchangeRateDate": "2019-08-01T00:00:00Z",
            "effectiveUnitPrice": 0,
            "rateOfPartnerEarnedCredit": 0,
            "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
            "attributes": {
                "objectType": "DailyRatedUsageLineItem"
            }
         },
         {
            "partnerId": "00083575-bbd0-54de-b2ad-0f5b0e927d71",
            "partnerName": "MTBC",
            "customerId": "",
            "customerName": "",
            "customerDomainName": "",
            "invoiceNumber": "",
            "productId": "",
            "skuId": "",
            "availabilityId": "",
            "skuName": "VM-Series Next-Generation Firewall (Bundle 2 PAYG)",
            "productName": "VM-Series Next Generation Firewall",
            "publisherName": "Test Alto Networks, Inc.",
            "publisherId": "",
            "subscriptionId": "12345678-04d9-421c-baf8-e3b8dd62ddba",
            "subscriptionDescription": "Pay-As-You-Go",
            "chargeStartDate": "2019-01-01T00:00:00Z",
            "chargeEndDate": "2019-02-01T00:00:00Z",
            "usageDate": "2019-01-02T00:00:00Z",
            "meterType": "1 Compute Hour - 4core",
            "meterCategory": "Virtual Machine Licenses",
            "meterId": "4core",
            "meterSubCategory": "VM-Series Next Generation Firewall",
            "meterName": "VM-Series Next Generation Firewall - VM-Series Next-Generation Firewall (Bundle 2 PAYG) - 4 Core Hours",
            "meterRegion": "",
            "unitOfMeasure": "1 Hour",
            "resourceLocation": "EASTUS",
            "consumedService": "Microsoft.Compute",
            "resourceGroup": "ECH-PAN-RG",
            "resourceUri": "/subscriptions/12345678-04d9-421c-baf8-e3b8dd62ddba/resourceGroups/ECH-PAN-RG/providers/Microsoft.Compute/virtualMachines/echpanfw",
            "tags": "",
            "additionalInfo": "{  \"ImageType\": null,  \"ServiceType\": \"Standard_D3_v2\",  \"VMName\": null,  \"VMProperties\": null,  \"UsageType\": \"ComputeHR_SW\"}",
            "serviceInfo1": "",
            "serviceInfo2": "",
            "customerCountry": "",
            "mpnId": "1234567",
            "resellerMpnId": "",
            "chargeType": "",
            "unitPrice": 1.2799888920023,
            "quantity": 24.0,
            "unitType": "",
            "billingPreTaxTotal": 30.7197334080551,
            "billingCurrency": "USD",
            "pricingPreTaxTotal": 30.7197334080551,
            "pricingCurrency": "USD",
            "entitlementId": "31cdf47f-b249-4edd-9319-637862d12345",
            "entitlementDescription": "Partner Subscription",
            "pcToBCExchangeRate": 1,
            "pcToBCExchangeRateDate": "2019-08-01T00:00:00Z",
            "effectiveUnitPrice": 0,
            "rateOfPartnerEarnedCredit": 0,
            "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
            "attributes": {
                "objectType": "DailyRatedUsageLineItem"
            }
        }
    ],
    "links": {
        "self": {
            "uri": "/invoices/unbilled/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode=usd&period=previous&size=2000",
            "method": "GET",
            "headers": []
        },
        "next": {
            "uri": "/invoices/unbilled/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 a seguir se aplicam a este exemplo:The following details apply to this example:

  • 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/unbilled/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": "00083575-bbd0-54de-b2ad-0f5b0e927d71",
            "partnerName": "MTBC",
            "customerId": "",
            "customerName": "",
            "customerDomainName": "",
            "invoiceNumber": "",
            "productId": "",
            "skuId": "",
            "availabilityId": "",
            "skuName": "VM-Series Next-Generation Firewall (Bundle 2 PAYG)",
            "productName": "VM-Series Next Generation Firewall",
            "publisherName": "Test Alto Networks, Inc.",
            "publisherId": "",
            "subscriptionId": "12345678-04d9-421c-baf8-e3b8dd62ddba",
            "subscriptionDescription": "Pay-As-You-Go",
            "chargeStartDate": "2019-01-01T00:00:00Z",
            "chargeEndDate": "2019-02-01T00:00:00Z",
            "usageDate": "2019-01-02T00:00:00Z",
            "meterType": "1 Compute Hour - 4core",
            "meterCategory": "Virtual Machine Licenses",
            "meterId": "4core",
            "meterSubCategory": "VM-Series Next Generation Firewall",
            "meterName": "VM-Series Next Generation Firewall - VM-Series Next-Generation Firewall (Bundle 2 PAYG) - 4 Core Hours",
            "meterRegion": "",
            "unitOfMeasure": "1 Hour",
            "resourceLocation": "EASTUS",
            "consumedService": "Microsoft.Compute",
            "resourceGroup": "ECH-PAN-RG",
            "resourceUri": "/subscriptions/12345678-04d9-421c-baf8-e3b8dd62ddba/resourceGroups/ECH-PAN-RG/providers/Microsoft.Compute/virtualMachines/echpanfw",
            "tags": "",
            "additionalInfo": "{  \"ImageType\": null,  \"ServiceType\": \"Standard_D3_v2\",  \"VMName\": null,  \"VMProperties\": null,  \"UsageType\": \"ComputeHR_SW\"}",
            "serviceInfo1": "",
            "serviceInfo2": "",
            "customerCountry": "",
            "mpnId": "1234567",
            "resellerMpnId": "",
            "chargeType": "",
            "unitPrice": 1.2799888920023,
            "quantity": 24.0,
            "unitType": "",
            "billingPreTaxTotal": 30.7197334080551,
            "billingCurrency": "USD",
            "pricingPreTaxTotal": 30.7197334080551,
            "pricingCurrency": "USD",
            "entitlementId": "31cdf47f-b249-4edd-9319-637862d8c0b4",
            "entitlementDescription": "Partner Subscription",
            "pcToBCExchangeRate": 1,
            "pcToBCExchangeRateDate": "2019-08-01T00:00:00Z",
            "effectiveUnitPrice": 0,
            "rateOfPartnerEarnedCredit": 0,
            "invoiceLineItemType": "usage_line_items",
            "billingProvider": "marketplace",
            "attributes": {
                "objectType": "DailyRatedUsageLineItem"
            }
        }
    ],
    "links": {
        "self": {
             "uri": "/invoices/unbilled/lineitems?provider=onetime&invoicelineitemtype=usagelineitems&currencycode=usd&period=previous&size=2000",
            "method": "GET",
            "headers": []
        }
    },
    "attributes": {
        "objectType": "Collection"
    }
}