> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# XStoreQueryAssociatedProductsAsync

> XStoreQueryAssociatedProductsAsync

# XStoreQueryAssociatedProductsAsync

Obtém informações da listagem da loja para produtos que os usuários podem comprar dentro do jogo atual.

## Sintaxe

```cpp theme={null}
HRESULT XStoreQueryAssociatedProductsAsync(  
         const XStoreContextHandle storeContextHandle,  
         XStoreProductKind productKinds,  
         uint32_t maxItemsToRetrievePerPage,  
         XAsyncBlock* async  
)  
```

### Parâmetros

*storeContextHandle*   \_In\_\
Tipo: XStoreContextHandle

O identificador de contexto da loja para o usuário retornado por [XStoreCreateContext](/pt-BR/reference/system/xstore/functions/xstorecreatecontext).

*productKinds*   \_In\_\
Tipo: [XStoreProductKind](/pt-BR/reference/system/xstore/enums/xstoreproductkind)

O tipo de produtos a serem retornados.

*maxItemsToRetrievePerPage*   \_In\_\
Tipo: uint32\_t

O número máximo de itens a serem recuperados por página.
O número de itens retornados por página pode variar de 0 a `maxItemsToRetrievePerPage`.
Para obter mais informações, consulte [Paginação](#paging).

*async*   \_Inout\_\
Tipo: [XAsyncBlock\*](/pt-BR/reference/system/xasync/structs/xasyncblock)

Um [XAsyncBlock](/pt-BR/reference/system/xasync/structs/xasyncblock) que define o trabalho assíncrono que está sendo realizado.
Use o [XAsyncBlock](/pt-BR/reference/system/xasync/structs/xasyncblock) para sondar o status da chamada e recuperar os resultados da chamada.
Para obter mais informações, consulte [XAsyncBlock](/pt-BR/reference/system/xasync/structs/xasyncblock).

### Valor retornado

Tipo: HRESULT

Código de sucesso ou erro HRESULT.

## Comentários

Para obter as informações da listagem da loja e o resultado da execução desta função, chame [XStoreQueryAssociatedProductsResult](/pt-BR/reference/system/xstore/functions/xstorequeryassociatedproductsresult) depois de chamar esta função.
[XStoreQueryAssociatedProductsResult](/pt-BR/reference/system/xstore/functions/xstorequeryassociatedproductsresult) contém um `XStoreProductQueryHandle` que você enumera chamando [XStoreEnumerateProductsQuery](/pt-BR/reference/system/xstore/functions/xstoreenumerateproductsquery).

Não é possível saber antecipadamente o número de produtos que esta consulta retorna.

Esta API retorna apenas produtos que os usuários podem procurar na Microsoft Store ou comprar dentro do jogo.
Os resultados não incluem nenhum produto oculto, expirado ou removido da loja.
Se você precisar de detalhes de um produto desse tipo, use [XStoreQueryProductsAsync](/pt-BR/reference/system/xstore/functions/xstorequeryproductsasync) e passe a Store ID do produto.

## Paginação

Esta função retorna produtos em várias páginas (até `maxItemsToRetrievePerPage` itens em uma única página).
Use [XStoreProductsQueryHasMorePages](/pt-BR/reference/system/xstore/functions/xstoreproductsqueryhasmorepages) e [XStoreProductsQueryNextPageAsync](/pt-BR/reference/system/xstore/functions/xstoreproductsquerynextpageasync)/[XStoreProductsQueryNextPageResult](/pt-BR/reference/system/xstore/functions/xstoreproductsquerynextpageresult) para processar todos os resultados paginados.
A paginação não está concluída até que `XStoreProductsQueryHasMorePages` retorne false.

<Note>
  A paginação pode se comportar de forma diferente entre áreas restritas e RETAIL.
  Em uma área restrita, os itens se acumulam até `maxItemsToRetrievePerPage` antes que uma página seja retornada.
  Em RETAIL, é comum que de 0 a 1 item seja retornado por página.

  É importante que todos os jogos que usam esta API implementem e testem a paginação antes do lançamento.

  Para testar o comportamento da paginação em uma área restrita, defina temporariamente `maxItemsToRetrievePerPage` como um valor menor que o número de produtos publicados na sua área restrita.
  Para testar em RETAIL antes do lançamento do seu jogo, publique produtos usando a opção **Enable Private Audience** na página 'Pricing and availability' do Partner Center.
  Para testar em RETAIL após o lançamento do seu jogo, use um package flight.
</Note>

O código a seguir mostra como recuperar os resultados da consulta de produtos em várias páginas.

Certifique-se de que o identificador da consulta seja passado adiante pela recursão de paginação para evitar vazamentos.

```cpp theme={null}
struct QueryContext
{
    uint32_t count = 0;  // used to accumulate count of products returned across pages
    XStoreProductQueryHandle handle = nullptr;  // handle to reuse for paged operations
};

void CleanupProductQuery(XAsyncBlock* async)
{
    if (!async) return;

    auto* ctx = static_cast<QueryContext*>(async->context);
    if (ctx)
    {
        if (ctx->handle)
        {
            XStoreCloseProductsQueryHandle(ctx->handle);
            ctx->handle = nullptr;
        }

        delete ctx;
        async->context = nullptr;
    }

    delete async;
}

bool CALLBACK ProductEnumerationCallback(const XStoreProduct* product, void* context)
{
    // Use result of query
    auto* ctx = static_cast<QueryContext*>(context);

    // Empty results are possible and should be skipped
    if (product)
    {
        printf("%s %s %u\n", product->title, product->storeId, product->productKind);
        ctx->count++;
    }

    return true;
}

void CALLBACK QueryAssociatedProductsCallback(XAsyncBlock* async)
{
    auto* ctx = static_cast<QueryContext*>(async->context);

    HRESULT hr = XStoreQueryAssociatedProductsResult(async, &ctx->handle);
    if (FAILED(hr)) { CleanupProductQuery(async); return; }

    hr = XStoreEnumerateProductsQuery(ctx->handle, ctx, ProductEnumerationCallback);
    if (FAILED(hr)) { CleanupProductQuery(async); return; }

    // Check if there are more pages to process
    if (XStoreProductsQueryHasMorePages(ctx->handle))
    {
        QueryNextPage(async);
        return;
    }

    printf("Enumeration complete, %u products found\n", ctx->count);
    CleanupProductQuery(async);
}

void QueryAssociatedProducts(XStoreContextHandle storeContextHandle, XTaskQueueHandle taskQueueHandle)
{
    auto async = new XAsyncBlock{};
    async->context = new QueryContext{ 0, nullptr };
    async->queue = taskQueueHandle;
    async->callback = QueryAssociatedProductsCallback;

    XStoreProductKind typeFilter =
        XStoreProductKind::Consumable |
        XStoreProductKind::Durable |
        XStoreProductKind::Game |
        XStoreProductKind::Pass |
        XStoreProductKind::UnmanagedConsumable;

    HRESULT hr = XStoreQueryAssociatedProductsAsync(
        storeContextHandle,
        typeFilter,
        25,          // Products per page (25 is a good default, can set lower to verify paging in sandbox)
        async);

    if (FAILED(hr))
    {
        CleanupProductQuery(async);
    }
}

// In RETAIL, content will be returned across multiple pages.
// Paging is not complete until XStoreProductsQueryHasMorePages returns false.
void QueryNextPage(XAsyncBlock *async)
{
    async->callback = [](XAsyncBlock* async)
    {
        auto* ctx = static_cast<QueryContext*>(async->context);

        XStoreProductQueryHandle next = nullptr;
        HRESULT hr = XStoreProductsQueryNextPageResult(async, &next);
        if (FAILED(hr)) { CleanupProductQuery(async); return; }

        // Safe swap: avoids leaks if 'next' is a new handle, avoids double-close if identical
        if (next && next != ctx->handle)
        {
            if (ctx->handle) XStoreCloseProductsQueryHandle(ctx->handle);
            ctx->handle = next;
        }
        else
        {
            ctx->handle = next; // covers null or same-handle cases
        }

        hr = XStoreEnumerateProductsQuery(ctx->handle, ctx, ProductEnumerationCallback);
        if (FAILED(hr)) { CleanupProductQuery(async); return; }

        // Check if there are more pages to process
        if (XStoreProductsQueryHasMorePages(ctx->handle))
        {
            QueryNextPage(async);
            return;
        }

        printf("Enumeration complete, %u products found\n", ctx->count);
        CleanupProductQuery(async);
    };

    auto* ctx = static_cast<QueryContext*>(async->context);
    HRESULT hr = XStoreProductsQueryNextPageAsync(ctx->handle, async);
    if (FAILED(hr))
    {
        CleanupProductQuery(async);
    }
}

```

## Requisitos

**Cabeçalho:** XStore.h (incluído em XGameRuntime.h)

**Biblioteca:** xgameruntime.lib

**Plataformas com suporte:** Windows, consoles da família XBOX One e consoles XBOX Series

## Documentação conceitual

* [Implementar compras no jogo](https://learn.microsoft.com/gaming/gdk/docs/gdk-dev/pc-dev/tutorials/pc-e2e-guide/e2e-services/e2e-in-game-purchases)
* [Operações básicas da loja](/pt-BR/publishing/xstore-commerce/xstore-basic-operations)
* [Conceder aos jogadores acesso ao conteúdo de complementos](/pt-BR/publishing/xstore-commerce/xstore-granting-access)
* [Visão geral dos sistemas de comércio do GDK](/pt-BR/publishing/xstore-commerce/xstore-overview)
* [Limitação de taxa refinada para APIs da Microsoft Store](/pt-BR/publishing/xstore-commerce/xstore-fgrl)
* [Ferramenta de direitos de desenvolvimento da loja (DevEntitlementTool.exe)](/pt-BR/tools/tools-services/live-dev-entitlements-tool)

## Confira também

[XStore](/pt-BR/reference/system/xstore/xstore_members)\
[XStoreQueryAssociatedProductsResult](/pt-BR/reference/system/xstore/functions/xstorequeryassociatedproductsresult)\
[XStoreEnumerateProductsQuery](/pt-BR/reference/system/xstore/functions/xstoreenumerateproductsquery)\
[XStoreProductsQueryHasMorePages](/pt-BR/reference/system/xstore/functions/xstoreproductsqueryhasmorepages)\
[XStoreProductsQueryNextPageAsync](/pt-BR/reference/system/xstore/functions/xstoreproductsquerynextpageasync)\
[Operações básicas da loja](/pt-BR/publishing/xstore-commerce/xstore-basic-operations)\
[Conceder aos jogadores acesso ao conteúdo de complementos](/pt-BR/publishing/xstore-commerce/xstore-granting-access)


## Related topics

- [XStoreQueryAssociatedProductsAsync](/reference/system/xstore/functions/xstorequeryassociatedproductsasync.md)
- [XStoreQueryAssociatedProductsResult](/reference/system/xstore/functions/xstorequeryassociatedproductsresult.md)
- [XStoreQueryAssociatedProductsForStoreIdAsync](/reference/system/xstore/functions/xstorequeryassociatedproductsforstoreidasync.md)
- [XStoreQueryProductsAsync](/reference/system/xstore/functions/xstorequeryproductsasync.md)
- [XStoreQueryProductForPackageAsync](/reference/system/xstore/functions/xstorequeryproductforpackageasync.md)
