啟用消費性應用程式內產品購買Enable consumable in-app product purchases

您可以透過 Microsoft Store 商業平台提供消費性的應用程式內產品 (亦即可購買、使用,然後再次購買的項目),為客戶提供既健全又可靠的購買體驗。Offer consumable in-app products—items that can be purchased, used, and purchased again—through the Store commerce platform to provide your customers with a purchase experience that is both robust and reliable. 這對於像遊戲內貨幣 (金幣、錢幣等) 這種可在買來後用來購買特定火力升級配備的東西,特別有用。This is especially useful for things like in-game currency (gold, coins, etc.) that can be purchased and then used to purchase specific power-ups.

重要

這篇文章示範如何使用 Windows.ApplicationModel.Store 命名空間的成員來啟用消費性 App 內產品購買。This article demonstrates how to use members of the Windows.ApplicationModel.Store namespace to enable consumable in-app product purchases. 此命名空間不再提供新功能更新,建議您改為使用 Windows.Services.Store 命名空間。This namespace is no longer being updated with new features, and we recommend that you use the Windows.Services.Store namespace instead. Windows. Store 命名空間支援最新的附加元件類型(例如儲存管理的可使用附加元件和訂閱),其設計目的是要與合作夥伴中心和存放區所支援的未來產品和功能類型相容。The Windows.Services.Store namespace supports the latest add-on types, such as Store-managed consumable add-ons and subscriptions, and is designed to be compatible with future types of products and features supported by Partner Center and the Store. Windows.Services.Store 命名空間在 Windows 10 (版本 1607) 中引進,只適用於目標為 Visual Studio 中 Windows 10 Anniversary Edition (10.0;組建 14393) 或更新版本的專案。The Windows.Services.Store namespace was introduced in Windows 10, version 1607, and it can only be used in projects that target Windows 10 Anniversary Edition (10.0; Build 14393) or a later release in Visual Studio. 如需有關使用 Windows.Services.Store 命名空間來啟用消費性 App 內產品購買的詳細資訊,請參閱 本文For more information about enabling consumable in-app product purchases using the Windows.Services.Store namespace, see this article.

PrerequisitesPrerequisites

  • 本主題涵蓋消費性應用程式內產品的購買和履行狀況報告。This topic covers the purchase and fulfillment reporting of consumable in-app products. 如果您不熟悉應用程式內產品,請檢閱啟用應用程式內產品購買,以了解授權資訊及如何在 Microsoft Store 中正確列出應用程式內產品。If you are unfamiliar with in-app products, please review Enable in-app product purchases to learn about license information, and how to properly list in-app products in the Store.
  • 初次撰寫並測試新應用程式內產品的程式碼時,您必須使用 CurrentAppSimulator 物件,而不是 CurrentApp 物件。When you code and test new in-app products for the first time, you must use the CurrentAppSimulator object instead of the CurrentApp object. 如此一來,您就可以利用對授權伺服器進行模擬呼叫來驗證授權邏輯,而不是呼叫使用中的伺服器。This way you can verify your license logic using simulated calls to the license server instead of calling the live server. 若要這樣做,您必須自訂% userprofile% \ AppData \ 本機 \ 套件 \ < 套件名稱 > \ LocalState \ Microsoft \ Windows Store \ ApiData 中名為 WindowsStoreProxy.xml 的檔案。To do this, you need to customize the file named WindowsStoreProxy.xml in %userprofile%\AppData\local\packages\<package name>\LocalState\Microsoft\Windows Store\ApiData. Microsoft Visual Studio 模擬器會在您第一次執行您的 App 時建立這個檔案,或者您也可以在執行階段載入自訂的檔案。The Microsoft Visual Studio simulator creates this file when you run your app for the first time—or you can also load a custom one at runtime. 如需詳細資訊,請參閱使用 WindowsStoreProxy.xml 檔案搭配 CurrentAppSimulatorFor more info, see Using the WindowsStoreProxy.xml file with CurrentAppSimulator.
  • 本主題也會參照 Microsoft Store 範例中提供的程式碼範例。This topic also references code examples provided in the Store sample. 這個範例非常適合用來體驗實機操作針對通用 Windows 平台 (UWP) app 提供的不同貨幣選項。This sample is a great way to get hands-on experience with the different monetization options provided for Universal Windows Platform (UWP) apps.

步驟 1:提出購買要求Step 1: Making the purchase request

就像透過 Microsoft Store 進行的任何其他購買一樣,初始購買要求是以 RequestProductPurchaseAsync 提出。The initial purchase request is made with RequestProductPurchaseAsync like any other purchase made through the Store. 消費性應用程式內產品的不同之處在於,客戶在順利購買這類產品之後,除非應用程式已通知 Microsoft Store 先前的購買已順利履行,否則客戶無法再次購買相同的產品。The difference for consumable in-app products is that after a successful purchase, a customer cannot purchase the same product again until the app has notified the Store that the previous purchase was successfully fulfilled. 您的應用程式必須負責履行已購買的消費性產品,並在履行後通知 Microsoft Store。It's your app's responsibility to fulfill purchased consumables and notify the Store of the fulfillment.

下列範例示範消費性應用程式內產品購買要求。The following example shows a consumable in-app product purchase request. 您會注意到程式碼註解指出在下列兩種不同的情況下,App 應該於何時在本機履行消費性應用程式內產品,一是在要求成功的情況,二是在因為購買尚未履行的相同產品而導致要求失敗的情況。You'll notice code comments indicating when your app should conduct its local fulfillment of the consumable in-app product for two different scenarios—when the request is successful, and when the request is not successful because of an unfulfilled purchase of that same product.

PurchaseResults purchaseResults = await CurrentAppSimulator.RequestProductPurchaseAsync("product1");
switch (purchaseResults.Status)
{
    case ProductPurchaseStatus.Succeeded:
        product1TempTransactionId = purchaseResults.TransactionId;

        // Grant the user their purchase here, and then pass the product ID and transaction ID to
        // CurrentAppSimulator.ReportConsumableFulfillment to indicate local fulfillment to the
        // Windows Store.
        break;

    case ProductPurchaseStatus.NotFulfilled:
        product1TempTransactionId = purchaseResults.TransactionId;

        // First check for unfulfilled purchases and grant any unfulfilled purchases from an
        // earlier transaction. Once products are fulfilled pass the product ID and transaction ID
        // to CurrentAppSimulator.ReportConsumableFulfillment to indicate local fulfillment to the
        // Windows Store.
        break;
}

步驟 2:追蹤消費性產品的本機履行Step 2: Tracking local fulfillment of the consumable

將消費性應用程式內產品的存取權授與客戶時,請務必追蹤哪些產品已履行 ( productId ),以及該履行動作與哪個交易關聯 ( transactionId )。When granting your customer access to the consumable in-app product, it's important to keep track of which product is fulfilled ( productId ), and which transaction that fulfillment is associated with ( transactionId ).

重要

您的 App 必須將履行動作準確回報給 Microsoft Store。Your app is responsible for the accurately reporting fulfillment to the Store. 若要為客戶維護公平可靠的購買體驗,這個步驟是不可或缺的。This step is essential to maintaining a fair and reliable purchase experience for your customers.

下列範例示範如何使用上一個步驟之 RequestProductPurchaseAsync 呼叫中的 PurchaseResults 屬性,來識別購買的產品是否已經履行。The following example demonstrates use of the PurchaseResults properties from the RequestProductPurchaseAsync call in the previous step to identify the purchased product for fulfillment. 此範例使用集合將產品資訊儲存在可供參照的位置,以便稍後確認是否已在本機順利履行。A collection is used to store the product information in a location that can later be referenced to confirm that local fulfillment was successful.

private void GrantFeatureLocally(string productId, Guid transactionId)
{
    if (!grantedConsumableTransactionIds.ContainsKey(productId))
    {
        grantedConsumableTransactionIds.Add(productId, new List<Guid>());
    }
    grantedConsumableTransactionIds[productId].Add(transactionId);

    // Grant the user their content. You will likely increase some kind of gold/coins/some other asset count.
}

下個範例說明將履行回報給 Microsoft Store 後,如何使用上個範例的陣列來存取之後要使用的產品識別碼/交易識別碼。This next example shows how to use the array from the previous example to access product ID/transaction ID pairs that are later used when reporting fulfillment to the Store.

重要

無論您的 App 使用哪種方法來追蹤和確認履行,都必須提供審查評鑑,以確保不會針對客戶尚未收到的項目向客戶收費。Whatever methodology your app uses to track and confirm fulfillment, your app must demonstrate due diligence to ensure that your customers are not charged for items they haven't received.

private Boolean IsLocallyFulfilled(string productId, Guid transactionId)
{
    return grantedConsumableTransactionIds.ContainsKey(productId) &&
        grantedConsumableTransactionIds[productId].Contains(transactionId);
}

步驟 3:將產品履行回報給 Microsoft Store Step 3: Reporting product fulfillment to the Store

完成本機履行之後,您的 App 必須進行 ReportConsumableFulfillmentAsync 呼叫,此呼叫包含 productId 及含括該項產品購買的交易。After local fulfillment is completed, your app must make a ReportConsumableFulfillmentAsync call that includes the productId and the transaction the product purchase is included in.

重要

若未將已履行的消費性應用程式內產品報告給 Microsoft Store,將導致使用者無法再次購買該產品,必須等到回報已履行上次的購買後才能再購買。Failure to report fulfilled consumable in-app products to the Store will result in the user being unable to purchase that product again until fulfillment for the previous purchase is reported.

FulfillmentResult result = await CurrentAppSimulator.ReportConsumableFulfillmentAsync(
    "product2", product2TempTransactionId);

步驟 4:識別未履行的購買Step 4: Identifying unfulfilled purchases

您的 App 可以隨時使用 GetUnfulfilledConsumablesAsync 方法,來檢查是否有任何未履行的消費性應用程式內產品。Your app can use the GetUnfulfilledConsumablesAsync method to check for unfulfilled consumable in-app products at any time. 您應該定期呼叫這個方法,以檢查是否有任何因為未預期的應用程式事件 (例如網路連線中斷或應用程式終止) 而未履行的消費性產品存在。This method should be called on a regular basis to check for unfulfilled consumables that exist due to unanticipated app events like an interruption in network connectivity or app termination.

下列範例示範如何使用 GetUnfulfilledConsumablesAsync 列舉未履行的消費性產品,以及您的 App 如何重複此清單來完成本機履行。The following example demonstrates how GetUnfulfilledConsumablesAsync can be used to enumerate unfulfilled consumables, and how your app can iterate through this list to complete local fulfillment.

private async void GetUnfulfilledConsumables()
{
    products = await CurrentApp.GetUnfulfilledConsumablesAsync();

    foreach (UnfulfilledConsumable product in products)
    {
        logMessage += "\nProduct Id: " + product.ProductId + " Transaction Id: " + product.TransactionId;
        // This is where you would pass the product ID and transaction ID to
        // currentAppSimulator.reportConsumableFulfillment to indicate local fulfillment to the Windows Store.
    }
}