使用应用商店服务访问分析数据Access analytics data using Store services

使用 Microsoft Store ANALYTICS API 以编程方式检索注册到你或你的组织的 Windows 合作伙伴中心帐户的应用的分析数据。Use the Microsoft Store analytics API to programmatically retrieve analytics data for apps that are registered to your or your organization's Windows Partner Center account. 此 API 使你可以针对应用和加载项(也称为应用内产品或 IAP)购置、错误、应用评分和评价检索数据。This API enables you to retrieve data for app and add-on (also known as in-app product or IAP) acquisitions, errors, app ratings and reviews. 此 API 使用 Azure Active Directory (Azure AD) 验证来自应用或服务的调用。This API uses Azure Active Directory (Azure AD) to authenticate the calls from your app or service.

以下步骤介绍端到端过程:The following steps describe the end-to-end process:

  1. 确保已完成所有先决条件Make sure that you have completed all the prerequisites.
  2. 在 Microsoft Store 分析 API 中调用某个方法之前,请先获取 Azure AD 访问令牌Before you call a method in the Microsoft Store analytics API, obtain an Azure AD access token. 获取访问令牌后,可以在 60 分钟的令牌有效期内,使用该令牌调用 Microsoft Store 分析 API。After you obtain a token, you have 60 minutes to use this token in calls to the Microsoft Store analytics API before the token expires. 该令牌到期后,可以重新生成一个。After the token expires, you can generate a new token.
  3. 调用 Microsoft Store 分析 APICall the Microsoft Store analytics API.

步骤 1:完成使用 Microsoft Store 分析 API 的先决条件Step 1: Complete prerequisites for using the Microsoft Store analytics API

在开始编写调用 Microsoft Store 分析 API 的代码之前,确保已完成以下先决条件。Before you start writing code to call the Microsoft Store analytics API, make sure that you have completed the following prerequisites.

  • 你(或你的组织)必须有一个 Azure AD 目录,并且必须对该目录拥有全局管理员权限。You (or your organization) must have an Azure AD directory and you must have Global administrator permission for the directory. 如果你已使用 Microsoft 365 或 Microsoft 的其他业务服务,则你已具有 Azure AD 目录。If you already use Microsoft 365 or other business services from Microsoft, you already have Azure AD directory. 否则,你可以免费在合作伙伴中心中创建新的 Azure ADOtherwise, you can create a new Azure AD in Partner Center for no additional charge.

  • 必须将 Azure AD 应用程序与合作伙伴中心帐户相关联,并检索应用程序的租户 ID 和客户端 ID,并生成一个密钥。You must associate an Azure AD application with your Partner Center account, retrieve the tenant ID and client ID for the application and generate a key. Azure AD 应用程序是指你想要从中调用 Microsoft Store 分析 API 的应用或服务。The Azure AD application represents the app or service from which you want to call the Microsoft Store analytics API. 需要使用该租户 ID、客户端 ID 和密钥来获取要传递给 API 的 Azure AD 访问令牌。You need the tenant ID, client ID and key to obtain an Azure AD access token that you pass to the API.

    备注

    你只需执行一次此任务。You only need to perform this task one time. 获取租户 ID、客户端 ID 和密钥后,每当需要创建新的 Azure AD 访问令牌时,都可以重复使用它们。After you have the tenant ID, client ID and key, you can reuse them any time you need to create a new Azure AD access token.

若要将 Azure AD 应用程序与合作伙伴中心帐户关联并检索所需的值:To associate an Azure AD application with your Partner Center account and retrieve the required values:

  1. 在合作伙伴中心,将组织的合作伙伴中心帐户与组织的 Azure AD 目录相关联In Partner Center, associate your organization's Partner Center account with your organization's Azure AD directory.

  2. 接下来,从合作伙伴中心的 "帐户设置" 部分的 "用户" 页中,添加表示将用于访问合作伙伴中心帐户分析数据的应用或服务的Azure AD 应用程序Next, from the Users page in the Account settings section of Partner Center, add the Azure AD application that represents the app or service that you will use to access analytics data for your Partner Center account. 确保为此应用程序分配“管理者”角色。Make sure you assign this application the Manager role. 如果你的 Azure AD 目录中尚不包含该应用程序,可以在合作伙伴中心创建新的 Azure AD 应用程序If the application doesn't exist yet in your Azure AD directory, you can create a new Azure AD application in Partner Center.

  3. 返回到“用户”页,单击 Azure AD 应用程序的名称转到“应用程序设置”,然后复制“租户 ID”和“客户端 ID”值。 Return to the Users page, click the name of your Azure AD application to go to the application settings, and copy down the Tenant ID and Client ID values.

  4. 单击“添加新密钥”。Click Add new key. 在下一个屏幕上,复制“密钥”值。On the following screen, copy down the Key value. 离开此页后,不再可以访问此信息。You won't be able to access this info again after you leave this page. 有关详细信息,请参阅管理 Azure AD 应用程序的密钥For more information, see Manage keys for an Azure AD application.

步骤 2:获取 Azure AD 访问令牌Step 2: Obtain an Azure AD access token

在 Microsoft Store 分析 API 中调用任何方法之前,首先必须获取将传递给该 API 中每个方法的 Authorization 标头的 Azure AD 访问令牌。Before you call any of the methods in the Microsoft Store analytics API, you must first obtain an Azure AD access token that you pass to the Authorization header of each method in the API. 获取访问令牌后,在它到期前,你有 60 分钟的使用时间。After you obtain an access token, you have 60 minutes to use it before it expires. 该令牌到期后,可以对它进行刷新,以便可以在之后调用该 API 时继续使用。After the token expires, you can refresh the token so you can continue to use it in further calls to the API.

若要获取访问令牌,请按照 使用客户端凭据的服务到服务调用 中的说明将 HTTP POST 发送到 https://login.microsoftonline.com/<tenant_id>/oauth2/token 终结点。To obtain the access token, follow the instructions in Service to Service Calls Using Client Credentials to send an HTTP POST to the https://login.microsoftonline.com/<tenant_id>/oauth2/token endpoint. 示例请求如下所示。Here is a sample request.

POST https://login.microsoftonline.com/<tenant_id>/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded; charset=utf-8

grant_type=client_credentials
&client_id=<your_client_id>
&client_secret=<your_client_secret>
&resource=https://manage.devcenter.microsoft.com

对于 POST URI 中的 " 租户 _ id " 和 "客户端 * _ id* " 和 " 客户端 _ 密钥 " 参数,为你在上一节中的合作伙伴中心检索的应用程序指定租户 id、客户端 id 和密钥。For the tenant_id value in the POST URI and the client_id and client_secret parameters, specify the tenant ID, client ID and the key for your application that you retrieved from Partner Center in the previous section. 对于 resource 参数,必须指定 https://manage.devcenter.microsoft.comFor the resource parameter, you must specify https://manage.devcenter.microsoft.com.

在你的访问令牌到期后,你可按照此处的说明刷新令牌。After your access token expires, you can refresh it by following the instructions here.

步骤 3:调用 Microsoft Store 分析 APIStep 3: Call the Microsoft Store analytics API

获取 Azure AD 访问令牌后,可以随时调用 Microsoft Store 分析 API。After you have an Azure AD access token, you are ready to call the Microsoft Store analytics API. 你必须将访问令牌传递到每个方法的 Authorization 标头。You must pass the access token to the Authorization header of each method.

UWP 应用和游戏的方法Methods for UWP apps and games

以下方法可用于应用和游戏收购和附加支持:The following methods are available for apps and games acquisitions and add-on acquisitions:

适用于 UWP 应用的方法Methods for UWP apps

以下分析方法适用于合作伙伴中心的 UWP 应用。The following analytics methods are available for UWP apps in Partner Center.

方案Scenario 方法Methods
购置、转换、安装和使用Acquisitions, conversions, installs, and usage
应用错误App errors
洞察力Insights
评分和评价Ratings and reviews
应用内广告和广告活动In-app ads and ad campaigns

适用于桌面应用程序的方法Methods for desktop applications

属于 Windows 桌面应用程序计划的开发人员帐户可以使用以下分析方法。The following analytics methods are available for use by developer accounts that belong to the Windows Desktop Application program.

方案Scenario 方法Methods
安装次数Installs
Blocks
应用程序错误Application errors
洞察力Insights

适用于 Xbox Live 服务的方法Methods for Xbox Live services

使用 Xbox Live 服务的游戏开发人员帐户可以使用以下其他方法。The following additional methods are available for use by developer accounts with games that use Xbox Live services.

方案Scenario 方法Methods
常规分析General analytics
运行状况分析Health analytics
社区分析Community analytics

适用于硬件和驱动程序的方法Methods for hardware and drivers

属于 Windows 硬件仪表板程序 的开发人员帐户可以访问一组额外的方法来检索硬件和驱动程序的分析数据。Developer accounts that belong to the Windows hardware dashboard program have access to an additional set of methods for retrieving analytics data for hardware and drivers. 有关详细信息,请参阅 硬件仪表板 APIFor more information, see Hardware dashboard API.

代码示例Code example

以下代码示例演示如何获取 Azure AD 访问令牌以及如何从 C# 控制台应用调用 Microsoft Store 分析 API。The following code example demonstrates how to obtain an Azure AD access token and call the Microsoft Store analytics API from a C# console app. 若要使用此代码示例,请将 tenantIdclientIdclientSecretappID 变量分配给你的方案的相应值。To use this code example, assign the tenantId, clientId, clientSecret, and appID variables to the appropriate values for your scenario. 此示例需要 Newtonsoft 中的 Json.NET 程序包,以便反序列化 Microsoft Store 分析 API 返回的 JSON 数据。This example requires the Json.NET package from Newtonsoft to deserialize the JSON data returned by the Microsoft Store analytics API.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace TestAnalyticsAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            string tenantId = "<your tenant ID>";
            string clientId = "<your client ID>";
            string clientSecret = "<your secret>";

            string scope = "https://manage.devcenter.microsoft.com";

            // Retrieve an Azure AD access token
            string accessToken = GetClientCredentialAccessToken(
                    tenantId,
                    clientId,
                    clientSecret,
                    scope).Result;

            // This is your app's Store ID. This ID is available on
            // the App identity page of the Dev Center dashboard.
            string appID = "<your app's Store ID>";

            DateTime startDate = DateTime.Parse("08-01-2015");
            DateTime endDate = DateTime.Parse("11-01-2015");
            int pageSize = 1000;
            int startPageIndex = 0;

            // Call the Windows Store analytics API
            CallAnalyticsAPI(accessToken, appID, startDate, endDate, pageSize, startPageIndex);

            Console.Read();
        }

        private static void CallAnalyticsAPI(string accessToken, string appID, DateTime startDate, DateTime endDate, int top, int skip)
        {
            string requestURI;

            // Get app acquisitions
            requestURI = string.Format(
                "https://manage.devcenter.microsoft.com/v1.0/my/analytics/appacquisitions?applicationId={0}&startDate={1}&endDate={2}&top={3}&skip={4}",
                appID, startDate, endDate, top, skip);

            //// Get add-on acquisitions
            //requestURI = string.Format(
            //    "https://manage.devcenter.microsoft.com/v1.0/my/analytics/inappacquisitions?applicationId={0}&startDate={1}&endDate={2}&top={3}&skip={4}",
            //    appID, startDate, endDate, top, skip);

            //// Get app failures
            //requestURI = string.Format(
            //    "https://manage.devcenter.microsoft.com/v1.0/my/analytics/failurehits?applicationId={0}&startDate={1}&endDate={2}&top={3}&skip={4}",
            //    appID, startDate, endDate, top, skip);

            //// Get app ratings
            //requestURI = string.Format(
            //    "https://manage.devcenter.microsoft.com/v1.0/my/analytics/ratings?applicationId={0}&startDate={1}&endDate={2}top={3}&skip={4}",
            //    appID, startDate, endDate, top, skip);

            //// Get app reviews
            //requestURI = string.Format(
            //    "https://manage.devcenter.microsoft.com/v1.0/my/analytics/reviews?applicationId={0}&startDate={1}&endDate={2}&top={3}&skip={4}",
            //    appID, startDate, endDate, top, skip);

            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, requestURI);
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            WebRequestHandler handler = new WebRequestHandler();
            HttpClient httpClient = new HttpClient(handler);

            HttpResponseMessage response = httpClient.SendAsync(requestMessage).Result;

            Console.WriteLine(response);
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);

            response.Dispose();
        }

        public static async Task<string> GetClientCredentialAccessToken(string tenantId, string clientId, string clientSecret, string scope)
        {
            string tokenEndpointFormat = "https://login.microsoftonline.com/{0}/oauth2/token";
            string tokenEndpoint = string.Format(tokenEndpointFormat, tenantId);

            dynamic result;
            using (HttpClient client = new HttpClient())
            {
                string tokenUrl = tokenEndpoint;
                using (
                    HttpRequestMessage request = new HttpRequestMessage(
                        HttpMethod.Post,
                        tokenUrl))
                {
                    string content =
                        string.Format(
                            "grant_type=client_credentials&client_id={0}&client_secret={1}&resource={2}",
                            clientId,
                            clientSecret,
                            scope);

                    request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

                    using (HttpResponseMessage response = await client.SendAsync(request))
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        result = JsonConvert.DeserializeObject(responseContent);
                    }
                }
            }

            return result.access_token;
        }
    }
}

错误响应Error responses

Microsoft Store 分析 API 在 JSON 对象中返回含有错误代码和消息的错误响应。The Microsoft Store analytics API returns error responses in a JSON object that contains error codes and messages. 以下示例演示了由无效参数引起的错误响应。The following example demonstrates an error response caused by an invalid parameter.

{
    "code":"BadRequest",
    "data":[],
    "details":[],
    "innererror":{
        "code":"InvalidQueryParameters",
        "data":[
            "top parameter cannot be more than 10000"
        ],
        "details":[],
        "message":"One or More Query Parameters has invalid values.",
        "source":"AnalyticsAPI"
    },
    "message":"The calling client sent a bad request to the service.",
    "source":"AnalyticsAPI"
}