Gestisci offerte mirate utilizzando i servizi dello Store

Se crei un'offertra mirata nella pagina Coinvolgi > in offerte mirate per la tua app nel Partner Center, utilizza l'API delle offerte mirate di Microsoft Store nel codice della tua app per recuperare informazioni che ti aiutano a implementare l'esperienza in-app per l'offerta mirata. Per ulteriori informazioni sulle offerte mirate e su come crearle nel dashboard, vedi Utilizzare offerte mirate per massimizzare il coinvolgimento e le conversioni.

L'API delle offerte mirate è una semplice API REST che puoi utilizzare per ottenere le offerte mirate disponibili per l'utente corrente, a seconda che l'utente faccia o meno parte del segmento di clienti per l'offerta mirata. Per utilizzare questa API nel codice della tua app, procedi nel seguente modo:

  1. Ottieni un token dell'account Microsoft per l'utente attualmente connesso alla tua app..
  2. Ottieni le offerte mirate per l'uso attuale.
  3. Implementa l'esperienza di acquisto in-app per il componente aggiuntivo associato a una delle offerte target. Per ulteriori informazioni sull'implementazione degli acquisti in-app, vedere questo articolo.

Per un esempio di codice completo che illustra tutti questi passaggi, vedere l'esempio di codice nella parte finale di questo articolo. Le sezioni seguenti forniscono ulteriori dettagli su ciascun passaggio.

Ottieni un token dell'account Microsoft per l'utente corrente

Nel codice dell'app ottieni un token dell'account Microsoft (MSA) per l'utente attualmente connesso. Devi passare questo token nell'Authorization intestazione della richiesta per l'API delle offerte mirate di Microsoft Store. Questo token viene utilizzato dallo Store per recuperare le offerte mirate disponibili per l'utente corrente.

Per ottenere il token MSA utilizza la classe WebAuthenticationCoreManager per richiedere un token utilizzando lo scopedevcenter_implicit.basic,wl.basic. Nell'esempio riportato di seguito viene illustrato come procedere. Questo esempio è un estratto dell'esempio completo e richiedel'utilizzodelle istruzioni fornite nell'esempio completo.

private async Task<string> GetMicrosoftAccountTokenAsync()
{
    var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
        "https://login.microsoft.com", "consumers");

    WebTokenRequest request = new WebTokenRequest(msaProvider, "devcenter_implicit.basic,wl.basic");
    WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request);

    if (result.ResponseStatus == WebTokenRequestStatus.Success)
    {
        return result.ResponseData[0].Token;
    }
    else
    {
        return string.Empty;
    }
}

Per ulteriori informazioni su come ottenere i gettoni MSA, vedere Gestore account web.

Ottieni le offerte mirate per l'uso attuale

Dopo aver ottenuto un token MSA per l'utente corrente, chiama il metodo GET dell'https://manage.devcenter.microsoft.com/v2.0/my/storeoffers/userURI per ottenere le offerte mirate disponibili per l'utente corrente. Per ulteriori informazioni su questo metodo REST, vedere Ricevi offerte mirate.

Questo metodo restituisce gli ID prodotto dei componenti aggiuntivi associati alle offerte mirate disponibili per l'utente corrente. Con queste informazioni puoi offrire all'utente una o più offerte mirate come acquisto in-app.

L'esempio seguente mostra come ottenere le offerte mirate per l'utente corrente. Questo esempio è un estratto dall'esempio completo Richiede la libreriaJson.NET di Newtonsoft e classi aggiuntive e dichiarazioni di utilizzofornite nell'esempio completo.

private async Task<List<TargetedOfferData>> GetTargetedOffersForUserAsync(string msaToken)
{
    if (string.IsNullOrEmpty(msaToken))
    {
        System.Diagnostics.Debug.WriteLine("Microsoft Account token is null or empty.");
        return null;
    }

    HttpClient httpClientGetOffers = new HttpClient();
    httpClientGetOffers.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msaToken);
    List<TargetedOfferData> availableOfferData = null;

    try
    {
        string getOffersResponse = await httpClientGetOffers.GetStringAsync(new Uri(storeOffersUri));
        availableOfferData = 
            Newtonsoft.Json.JsonConvert.DeserializeObject<List<TargetedOfferData>>(getOffersResponse);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }

    return availableOfferData;
}

Esempio di codice completo

Nell'esempio di codice seguente vengono illustrate le attività seguenti:

  • Ottieni un token MSA per l'utente corrente.
  • Ottieni tutte le offerte mirate per l'utente corrente utilizzando il metodoRicevi offerte mirate.
  • Acquista il componente aggiuntivo associato a un'offerta mirata.

L'esempio richiede la libreria Json.NETdi Newtonsoft. L'esempio usa questa libreria per serializzare e deserializzare i dati in formato JSON.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Windows.Services.Store;
using Windows.Security.Authentication.Web.Core;

namespace DocumenationExamples
{
    public class TargetedOffersExample
    {
        private const string storeOffersUri = "https://manage.devcenter.microsoft.com/v2.0/my/storeoffers/user";
        private const string jsonMediaType = "application/json";
        private static string[] productKinds = { "Durable", "Consumable", "UnmanagedConsumable" };
        private static StoreContext storeContext = StoreContext.GetDefault();

        public async void DemonstrateTargetedOffers()
        {
            // Get the Microsoft Account token for the current user.
            string msaToken = await GetMicrosoftAccountTokenAsync();

            if (string.IsNullOrEmpty(msaToken))
            {
                System.Diagnostics.Debug.WriteLine("Microsoft Account token could not be retrieved.");
                return;
            }

            // Get the targeted Store offers for the current user.
            List<TargetedOfferData> availableOfferData =
                await GetTargetedOffersForUserAsync(msaToken);

            if (availableOfferData == null || availableOfferData.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine("There was an error retrieving targeted offers," +
                    "or there are no targeted offers available for the current user.");
                return;
            }

            // Get the product ID of the add-on that is associated with the first available offer
            // in the response data.
            TargetedOfferData offerData = availableOfferData[0];
            string productId = offerData.Offers[0];

            // Get the Store ID of the add-on that has the matching product ID, and then purchase the add-on.
            List<String> filterList = new List<string>(productKinds);
            StoreProductQueryResult queryResult = await storeContext.GetAssociatedStoreProductsAsync(filterList);
            foreach (KeyValuePair<string, StoreProduct> result in queryResult.Products)
            {
                if (result.Value.InAppOfferToken == productId)
                {
                    await PurchaseOfferAsync(result.Value.StoreId);
                    return;
                }
            }

            System.Diagnostics.Debug.WriteLine("No add-on with the specified product ID could be found " +
                "for the current app.");
            return;
        }

        private async Task<string> GetMicrosoftAccountTokenAsync()
        {
            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                "https://login.microsoft.com", "consumers");

            WebTokenRequest request = new WebTokenRequest(msaProvider, "devcenter_implicit.basic,wl.basic");
            WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                return result.ResponseData[0].Token;
            }
            else
            {
                return string.Empty;
            }
        }

        private async Task<List<TargetedOfferData>> GetTargetedOffersForUserAsync(string msaToken)
        {
            if (string.IsNullOrEmpty(msaToken))
            {
                System.Diagnostics.Debug.WriteLine("Microsoft Account token is null or empty.");
                return null;
            }

            HttpClient httpClientGetOffers = new HttpClient();
            httpClientGetOffers.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msaToken);
            List<TargetedOfferData> availableOfferData = null;

            try
            {
                string getOffersResponse = await httpClientGetOffers.GetStringAsync(new Uri(storeOffersUri));
                availableOfferData = 
                    Newtonsoft.Json.JsonConvert.DeserializeObject<List<TargetedOfferData>>(getOffersResponse);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return availableOfferData;
        }

        private async Task PurchaseOfferAsync(string storeId)
        {
            if (string.IsNullOrEmpty(storeId))
            {
                System.Diagnostics.Debug.WriteLine("storeId is null or empty.");
                return;
            }

            // Purchase the add-on for the current user. Typically, a game or app would first show
            // a UI that prompts the user to buy the add-on; for simplicity, this example
            // simply purchases the add-on.
            StorePurchaseResult result = await storeContext.RequestPurchaseAsync(storeId);

            // Capture the error message for the purchase operation, if any.
            string extendedError = string.Empty;
            if (result.ExtendedError != null)
            {
                extendedError = result.ExtendedError.Message;
            }

            switch (result.Status)
            {
                case StorePurchaseStatus.AlreadyPurchased:
                    System.Diagnostics.Debug.WriteLine("The user has already purchased the product.");
                    break;

                case StorePurchaseStatus.Succeeded:
                    System.Diagnostics.Debug.WriteLine("The purchase was successful.");
                    break;

                case StorePurchaseStatus.NotPurchased:
                    System.Diagnostics.Debug.WriteLine("The purchase did not complete. " +
                        "The user may have cancelled the purchase. ExtendedError: " + extendedError);
                    break;

                case StorePurchaseStatus.NetworkError:
                    System.Diagnostics.Debug.WriteLine("The purchase was unsuccessful due to a network error. " +
                        "ExtendedError: " + extendedError);
                    break;

                case StorePurchaseStatus.ServerError:
                    System.Diagnostics.Debug.WriteLine("The purchase was unsuccessful due to a server error. " +
                        "ExtendedError: " + extendedError);
                    break;

                default:
                    System.Diagnostics.Debug.WriteLine("The purchase was unsuccessful due to an unknown error. " +
                        "ExtendedError: " + extendedError);
                    break;
            }
        }
    }

    public class TargetedOfferData
    {
        [JsonProperty(PropertyName = "offers")]
        public IList<string> Offers { get; } = new List<string>();

        [JsonProperty(PropertyName = "trackingId")]
        public string TrackingId { get; set; }
    }
}