取得應用程式和附加元件授權資訊
本文示範如何使用 Windows.Services.Store 命名空間中 StoreContext 類別的方法,取得目前應用程式及其附加元件的授權資訊。 例如,您可以使用這項資訊來判斷應用程式的授權或其附加元件是否為使用中,或它們是否為試用版授權。
注意
Windows.Services.Store 命名空間是在 Windows 10 版本 1607 中引進的,而且只能在以 Windows 10 年度版 (10.0) 為目標的專案中使用。組建 14393) 或更新版本中的 Visual Studio。 如果您的 app 以舊版 Windows 10 為目標,您必須使用 Windows.ApplicationModel.Store 命名空間,而不是 Windows.Services.Store 命名空間。 如需詳細資訊,請參閱本文。
先決條件
此範例具有下列必要條件:
- 通用 Windows 平臺 (UWP) app 的 Visual Studio 專案,以 windows 10 年度版本 (10.0) 為目標 :組建14393) 或更新版本。
- 您已 在合作夥伴中心建立應用程式提交內容,且此應用程式已在市集中發佈。 您可以選擇性地設定應用程式的可見性,以便在測試時無法在商店中被發現。 如需詳細資訊,請參閱我們的 測試指引。
- 如果您要取得應用程式附加元件的授權資訊,必須在合作夥伴中心建立附加元件。
此範例中的程式代碼假設:
- 程式碼會在一個 Page 的上下文中執行,該頁中包含名為
workingProgressRing
的 ProgressRing 和名為textBlock
的 TextBlock 。 這些物件用來指出異步作業正在發生,並顯示輸出訊息。 - 範例程式檔案有一個 使用 語句來處理 Windows.Services.Store 命名空間。
- 應用程式是單一使用者應用程式,僅能在啟動它的使用者環境中運行。 如需詳細資訊,請參閱 應用程式內購買和試用版。
注意
如果您的傳統型應用程式使用 Desktop Bridge,您可能需要新增本範例中未顯示的其他程式代碼,以設定 StoreContext 物件。 如需詳細資訊,請參閱在使用桌面橋接器的桌面應用程式中使用 StoreContext 類別 。
程式代碼範例
若要取得目前應用程式的授權資訊,請使用 GetAppLicenseAsync 方法。 這是異步方法,會傳回 StoreAppLicense 物件,該物件會提供應用程式的授權資訊,包括屬性,指出使用者目前是否有有效的授權可以使用應用程式(IsActive),以及授權是否適用於試用版(IsTrial)。
若要存取使用者有權使用之目前應用程式之持久附加元件授權,請使用 StoreAppLicense 物件的 AddOnLicenses 屬性。 這個屬性會傳回代表附加元件授權的 StoreLicense 物件集合。
private StoreContext context = null;
public async void GetLicenseInfo()
{
if (context == null)
{
context = StoreContext.GetDefault();
// If your app is a desktop app that uses the Desktop Bridge, you
// may need additional code to configure the StoreContext object.
// For more info, see https://aka.ms/storecontext-for-desktop.
}
workingProgressRing.IsActive = true;
StoreAppLicense appLicense = await context.GetAppLicenseAsync();
workingProgressRing.IsActive = false;
if (appLicense == null)
{
textBlock.Text = "An error occurred while retrieving the license.";
return;
}
// Use members of the appLicense object to access license info...
// Access the valid licenses for durable add-ons for this app.
foreach (KeyValuePair<string, StoreLicense> item in appLicense.AddOnLicenses)
{
StoreLicense addOnLicense = item.Value;
// Use members of the addOnLicense object to access license info
// for the add-on.
}
}
如需完整的範例應用程式,請參閱 Store 範例。