async Task PlatformUpdateConsumableBalance(string key, uint quantity, string trackingId) { if (context == null) { context = StoreContext.GetDefault(); } var result = await context.ReportConsumableFulfillmentAsync(_addOnsByKey[key].Id, quantity, Guid.Parse(trackingId)); switch (result.Status) { case StoreConsumableStatus.Succeeded: break; case StoreConsumableStatus.InsufficentQuantity: throw new Exception($"The fulfillment was unsuccessful because the remaining " + $"balance is insufficient. Remaining balance: {result.BalanceRemaining}", result.ExtendedError); case StoreConsumableStatus.NetworkError: case StoreConsumableStatus.ServerError: throw new Exception($"The fulfillment was unsuccessful due to a server or network error.", result.ExtendedError); default: throw new Exception($"The fulfillment was unsuccessful due to an unknown error.", result.ExtendedError); } }
internal static async Task <List <PurchaseItem> > GetDonateItems() { List <PurchaseItem> items = new List <PurchaseItem>(); if (context == null) { context = StoreContext.GetDefault(); } StoreProductQueryResult queryResult = await context.GetAssociatedStoreProductsAsync(new string[] { "UnmanagedConsumable" }); if (queryResult.ExtendedError != null) { return(items); } foreach (KeyValuePair <string, StoreProduct> item in queryResult.Products) { if ((item.Value.InAppOfferToken.Length >= (Donate_TokenBegin.Length + 1)) && (item.Value.InAppOfferToken.Substring(0, Donate_TokenBegin.Length) == Donate_TokenBegin)) { items.Add(new PurchaseItem { Price = item.Value.Price, StoreID = item.Value.StoreId, Token = item.Value.InAppOfferToken, }); } } return(items.OrderBy(x => GetPurchaseItemOrder(x)).ToList()); }
private void InitStoreContext() { var storeContext = StoreContext.GetDefault(); var initWindow = (IInitializeWithWindow)(object)storeContext; initWindow.Initialize(MainForm.Handle); }
/// <summary> /// Gets license info for the current app, including licenses for add-ons /// </summary> /// <returns>License info for the current app and its associated add-ons</returns> public static WSAStoreAppLicense GetAppLicense() { #if NETFX_CORE || (ENABLE_IL2CPP && UNITY_WSA_10_0) var result = StoreContext.GetDefault().GetAppLicenseAsync().AsTask().Result; return(new WSAStoreAppLicense() { AddOnLicenses = result.AddOnLicenses.ToDictionary(x => x.Key, y => new WSAStoreLicense() { ExpirationDate = y.Value.ExpirationDate, InAppOfferToken = y.Value.InAppOfferToken, IsActive = y.Value.IsActive, StoreId = y.Value.SkuStoreId }), ExpirationDate = result.ExpirationDate, IsActive = result.IsActive, IsTrial = result.IsTrial, StoreId = result.SkuStoreId, TrialTimeRemaining = result.TrialTimeRemaining, TrialUniqueId = result.TrialUniqueId }); #else return(new WSAStoreAppLicense()); #endif }
public async Task <bool> ShowRatingReviewDialog() { if (ApiInformation.IsMethodPresent(typeof(StoreRequestHelper).FullName, nameof(StoreRequestHelper.SendRequestAsync), 3)) { logger.Log("Review.SendRequest"); StoreSendRequestResult result = await StoreRequestHelper.SendRequestAsync( StoreContext.GetDefault(), 16, string.Empty); if (result.ExtendedError == null) { JObject jsonObject = JObject.Parse(result.Response); if (jsonObject.SelectToken("status").ToString() == "success") { // The customer rated or reviewed the app. return(true); } } // There was an error with the request, or the customer chose not to // rate or review the app. return(false); } else { logger.Log("Review.LaunchUri"); bool reviewResult = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store://review/?ProductId=9PCZBVLLDSX4")); return(reviewResult); } }
internal static async void CheckIfFullVersion() { if (context == null) { context = StoreContext.GetDefault(); } StoreProductQueryResult queryResult = await context.GetAssociatedStoreProductsAsync(new string[] { "Durable" }); if (queryResult.ExtendedError != null) { TrialSettings.IsTrial = false; return; } foreach (KeyValuePair <string, StoreProduct> item in queryResult.Products) { if (item.Value.InAppOfferToken == RemoveAdsAndSizeLimit_Token) { if (item.Value.IsInUserCollection) { TrialSettings.IsTrial = false; } else { TrialSettings.IsTrial = true; } } } }
private async Task <bool> CheckAndInstallUpdate() { try { Cancellation = new CancellationTokenSource(); if (StoreContext.GetDefault() is StoreContext Context) { IReadOnlyList <StorePackageUpdate> Updates = await Context.GetAppAndOptionalStorePackageUpdatesAsync().AsTask(Cancellation.Token); return(Updates.Count > 0); } else { return(false); } } catch { return(false); } finally { Cancellation.Dispose(); Cancellation = null; } }
public bool verify(LicenseVerifierCallback callback) { StoreContext storeContext = StoreContext.GetDefault(); StoreAppLicense license = storeContext.GetAppLicenseAsync().AsTask().Result; return(true || (license?.IsActive ?? true)); // HACK Windows Store Submission Process }
/// <inheritdoc/> public async Task <bool> IsOwnedAsync(string iapId) { if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable) { return(false); } if (_context == null) { _context = StoreContext.GetDefault(); } StoreAppLicense appLicense = await _context.GetAppLicenseAsync(); if (appLicense == null) { return(false); } /// Check if user has an active license for given add-on id. foreach (var addOnLicense in appLicense.AddOnLicenses) { var license = addOnLicense.Value; if (license.InAppOfferToken == iapId && license.IsActive) { return(true); } } return(false); }
// Has the user purchased this collection? private async Task <bool> IsPurchased() { if (_Context == null) { _Context = StoreContext.GetDefault(); } // Specify the kinds of add-ons to retrieve. var filterList = new List <string>(new[] { "Durable" }); var idList = new List <string>(new[] { _StoreId }); StoreProductQueryResult queryResult = await _Context.GetStoreProductsAsync(filterList, idList); if (queryResult.ExtendedError != null) { // The user may be offline or there might be some other server failure. Debug.WriteLine($"ExtendedError: {queryResult.ExtendedError.Message}"); return(false); } foreach (var item in queryResult.Products) { StoreProduct product = item.Value; return(product.IsInUserCollection); } return(false); }
public string getName() { StoreContext storeContext = StoreContext.GetDefault(); StoreAppLicense license = storeContext.GetAppLicenseAsync().AsTask().Result; if (license == null) { return(LocaleFactory.localizedString("Unknown")); } if (license.IsActive) { if (license.IsTrial) { return(LocaleFactory.localizedString("Trial Version", "License")); } else { return((string)storeContext.User?.GetPropertyAsync(KnownUserProperties.DisplayName).AsTask().Result ?? LocaleFactory.localizedString("Unknown")); } } else { return(LocaleFactory.localizedString("Unknown")); } }
private async Task ReportPurchased() { 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. } // This is an example for a Store-managed consumable, where you specify the actual number // of units that you want to report as consumed so the Store can update the remaining // balance. For a developer-managed consumable where you maintain the balance, specify 1 // to just report the add-on as fulfilled to the Store. var trackingId = Guid.NewGuid(); var result = await context.ReportConsumableFulfillmentAsync(Consts.DonationStoreID, 1, trackingId); switch (result.Status) { case StoreConsumableStatus.Succeeded: case StoreConsumableStatus.InsufficentQuantity: break; case StoreConsumableStatus.NetworkError: case StoreConsumableStatus.ServerError: MainPage.Current.PopMessage(result.ExtendedError.Message); break; default: break; } }
private async Task StartAppSelfUpdate() { Debug.WriteLine("Check for updates..."); StoreContext context = StoreContext.GetDefault(); // Check for updates... string lastCheck = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); ReportSelfUpdateStatus(lastCheck, "checkStarting"); IReadOnlyList <StorePackageUpdate> updates = await context.GetAppAndOptionalStorePackageUpdatesAsync(); if (updates.Count == 0) { ReportSelfUpdateStatus(lastCheck, "noUpdates"); return; } // Download and install the updates... IAsyncOperationWithProgress <StorePackageUpdateResult, StorePackageUpdateStatus> downloadOperation = context.RequestDownloadAndInstallStorePackageUpdatesAsync(updates); ReportSelfUpdateStatus(lastCheck, "updatesDownloadingAndInstalling"); // Wait for completion... StorePackageUpdateResult result = await downloadOperation.AsTask(); ReportSelfUpdateStatus(lastCheck, result.OverallState == StorePackageUpdateState.Completed ? "installed" : "failed"); return; }
/// <summary> /// check for update as an asynchronous operation. /// </summary> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public async Task <bool> CheckForUpdateAsync() { var result = false; try { updates = null; if (context is null) { context = StoreContext.GetDefault(); } updates = await context.GetAppAndOptionalStorePackageUpdatesAsync(); if (updates.Count > 0) { result = true; } } catch (Exception) { result = false; } return(result); }
public async void GetUserCollection() { 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. } // Specify the kinds of add-ons to retrieve. string[] productKinds = { "Durable" }; List <String> filterList = new List <string>(productKinds); workingProgressRing.IsActive = true; StoreProductQueryResult queryResult = await context.GetUserCollectionAsync(filterList); workingProgressRing.IsActive = false; if (queryResult.ExtendedError != null) { // The user may be offline or there might be some other server failure. textBlock.Text = $"ExtendedError: {queryResult.ExtendedError.Message}"; return; } foreach (KeyValuePair <string, StoreProduct> item in queryResult.Products) { StoreProduct product = item.Value; // Use members of the product object to access info for the product... } }
private static void InitializeContext() { if (_context == null) { _context = StoreContext.GetDefault(); } }
public static async Task TryUpgrade() { if (context == null) { context = StoreContext.GetDefault(); } try { StorePurchaseResult result = await context.RequestPurchaseAsync(RemoveAdsAndSizeLimit_StoreID); Debug.WriteLine($"In app purchase of {RemoveAdsAndSizeLimit_Token} finished with status: {result.Status}"); CheckIfFullVersion(); #if !DEBUG App.Tracker.Send(HitBuilder.CreateCustomEvent("TryUpgrade", "Upgraded", result.Status.ToString()).Build()); #endif } catch (Exception ex) { Debug.WriteLine($"In app purchase of {RemoveAdsAndSizeLimit_Token} failed: {ex.Message}"); #if !DEBUG App.Tracker.Send(HitBuilder.CreateCustomEvent("TryUpgrade", "Failed", ex.Message).Build()); #endif } }
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. } }
private async Task <bool> CheckUpdateAsync() { try { Cancellation = new CancellationTokenSource(); if (StoreContext.GetDefault() is StoreContext Context) { return((await Context.GetAppAndOptionalStorePackageUpdatesAsync().AsTask(Cancellation.Token)).Any()); } else { return(false); } } catch { return(false); } finally { Cancellation.Dispose(); Cancellation = null; } }
/// <summary> /// Get all current purchase for a specific product type. /// </summary> /// <param name="itemType">Type of product</param> /// <param name="verifyPurchase">Verify purchase implementation</param> /// <returns>The current purchases</returns> public override async Task <IEnumerable <InAppBillingPurchase> > GetPurchasesAsync(ItemType itemType, IInAppBillingVerifyPurchase verifyPurchase = null) { // https://docs.microsoft.com/en-us/windows/uwp/monetize/query-for-products // https://docs.microsoft.com/en-us/windows/uwp/monetize/enable-subscription-add-ons-for-your-app#code-examples var context = StoreContext.GetDefault(); var appLicense = await context.GetAppLicenseAsync(); var purchases = new List <InAppBillingPurchase>() { new InAppBillingPurchase { ProductId = appLicense.SkuStoreId, ExpirationDate = appLicense.ExpirationDate, State = appLicense.IsActive ? PurchaseState.Purchased : PurchaseState.Unknown, } }; purchases.AddRange(appLicense.AddOnLicenses.Select(l => new InAppBillingPurchase { ProductId = l.Value.SkuStoreId, ExpirationDate = appLicense.ExpirationDate, State = l.Value.IsActive ? PurchaseState.Purchased : PurchaseState.Unknown })); return(purchases); }
public async void CheckForUpdatesAsync(bool mandatoryOnly = true) { try { if (context == null) { context = await Task.Run(() => StoreContext.GetDefault()); } var updateList = await context.GetAppAndOptionalStorePackageUpdatesAsync(); if (mandatoryOnly) { updateList = updateList.Where(e => e.Mandatory).ToList(); } if (updateList.Count > 0) { if (await DownloadUpdatesConsent()) { await DownloadUpdates(updateList); } } } #if !DEBUG catch (Exception ex) { App.Logger.Warn(ex, "Could not fetch updates."); } #else catch (Exception) { } #endif }
private static async Task <bool> CheckPurchaseStatusAsync() { try { StoreContext Store = StoreContext.GetDefault(); StoreAppLicense License = await Store.GetAppLicenseAsync(); if (License.AddOnLicenses.Any((Item) => Item.Value.InAppOfferToken == "Donation")) { return(true); } if (License.IsActive) { if (License.IsTrial) { return(false); } else { return(true); } } else { return(false); } } catch { throw new NetworkException("Network Exception"); } }
private static async void GetAppInfoAsync(Action <WSAStoreProductResult> response) { StoreProductResult result = await StoreContext.GetDefault().GetStoreProductForCurrentAppAsync(); WSAStoreProductResult wsaStoreProductResult = new WSAStoreProductResult() { Product = new WSAStoreProduct() { Description = result.Product.Description, FormattedPrice = result.Product.Price.FormattedPrice, Images = result.Product.Images.Select(x => x.Uri).ToList(), InAppOfferToken = result.Product.InAppOfferToken, IsInUserCollection = result.Product.IsInUserCollection, Language = result.Product.Language, LinkUri = result.Product.LinkUri, ProductKind = result.Product.ProductKind, StoreId = result.Product.StoreId, Title = result.Product.Title, Videos = result.Product.Videos.Select(x => x.Uri).ToList() }, Error = result.ExtendedError }; if (response != null) { response(wsaStoreProductResult); } }
private static async Task <bool> PurchaseAsync() { StoreContext Store = StoreContext.GetDefault(); StoreProductResult ProductResult = await Store.GetStoreProductForCurrentAppAsync(); if (ProductResult.ExtendedError == null) { if (ProductResult.Product != null) { if ((await ProductResult.Product.RequestPurchaseAsync()).Status == StorePurchaseStatus.Succeeded) { return(true); } else { return(false); } } else { return(false); } } else { throw new NetworkException("Network error"); } }
// This is the entry point method for the example.检查加载项信息,是否有可试用 public async Task SetupSubscriptionInfoAsync() { 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. } //检查用户是否有订阅的许可证传给userOwnsSubscription值 userOwnsSubscription = await CheckIfUserHasSubscriptionAsync(); if (userOwnsSubscription) { Loading.IsActive = false; var messageDig = new MessageDialog("您已订阅此服务!"); //展示窗口,获取按钮是否退出 var result = await messageDig.ShowAsync(); // 解锁所有加载项订阅的特性功能 return; } //获取订阅信息.传给subscriptionStoreProduct值。 subscriptionStoreProduct = await GetSubscriptionProductAsync(); if (subscriptionStoreProduct == null) { Loading.IsActive = false; var messageDig = new MessageDialog("此订阅暂不提供!"); //展示窗口,获取按钮是否退出 var result = await messageDig.ShowAsync(); return; } //检查第一个SKU是否是试用版,并通知客户试用版可用。 //如果试用可用,Skus数组将始终具有两个可购买的SKU,以及 // first one is the trial. Otherwise,第一个是审判。否则,该数组将只有一个SKU。 StoreSku sku = subscriptionStoreProduct.Skus[0]; if (sku.SubscriptionInfo.HasTrialPeriod) { //如果存在试用 //您可以在这里向客户显示订阅购买信息。你可以使用 // sku.SubscriptionInfo.BillingPeriod and sku.SubscriptionInfo.BillingPeriodUnit //提供续约详情。 } else { //不存在试用 //您可以在这里向客户显示订阅购买信息。你可以使用 // sku.SubscriptionInfo.BillingPeriod and sku.SubscriptionInfo.BillingPeriodUnit //提供续约详情。 } // Prompt the customer to purchase the subscription. await PromptUserToPurchaseAsync(); }
public async void CheckForUpdatesAsync(bool mandantoryOnly = true) { try { if (context == null) { context = StoreContext.GetDefault(); } UpdateList = await context.GetAppAndOptionalStorePackageUpdatesAsync(); if (mandantoryOnly) { UpdateList = (IReadOnlyList <StorePackageUpdate>)UpdateList.Where(e => e.Mandatory); } if (UpdateList.Count > 0) { if (await DownloadUpdatesConsent()) { DownloadUpdates(); } } } catch (Exception) { } }
internal static async Task <StorePurchaseStatus> TryPurchaseConsumable(PurchaseItem item) { if (context == null) { context = StoreContext.GetDefault(); } Guid trackingId = Guid.NewGuid(); try { StorePurchaseResult result = await context.RequestPurchaseAsync(item.StoreID); var fulfillResult = await context.ReportConsumableFulfillmentAsync(item.StoreID, 1, trackingId); Debug.WriteLine($"In app purchase of consumable {item.Token} finished with status: Purchase={result.Status}, Fulfill={fulfillResult.Status}"); #if !DEBUG App.Tracker.Send(HitBuilder.CreateCustomEvent("TryDonate" + item.Token, "Done", $"Purchase={result.Status}, Fulfill={fulfillResult.Status}").Build()); #endif return(result.Status); } catch (Exception ex) { Debug.WriteLine($"In app purchase of consumable {item.Token} failed: {ex.Message}"); #if !DEBUG App.Tracker.Send(HitBuilder.CreateCustomEvent("TryDonate" + item.Token, "Failed", ex.Message).Build()); #endif return(StorePurchaseStatus.NotPurchased); } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { navigationHelper.OnNavigatedTo(e); try { packageCatalog = PackageCatalog.OpenForCurrentPackage(); packageCatalog.PackageInstalling += Catalog_PackageInstalling; packageCatalog.PackageStaging += Catalog_PackageStaging; packageCatalog.PackageStatusChanged += Catalog_PackageStatusChanged; } catch (Exception ex) { await new MessageDialog("Unable to setup deployment event handlers. {" + ex.InnerException + "}").ShowAsync(); } dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; optionalPackagesList = new ObservableCollection <Controls.OptionalPackageControl>(); OptionalPackagesListView.ItemsSource = optionalPackagesList; storeOptionalPackagesList = new ObservableCollection <StoreProductControl>(); StoreOptionalPackagesListView.ItemsSource = storeOptionalPackagesList; deployingOptionalPackagesList = new Dictionary <string, PackageDeploymentControl>(); deployingOptionalPackagesListUI = new ObservableCollection <PackageDeploymentControl>(); DeployingOptionalPackagesListView.ItemsSource = deployingOptionalPackagesListUI; context = StoreContext.GetDefault(); LoadInstalledOptionalPackages(); }
private async void UpdateNow(object sender, RoutedEventArgs e) { ProgressRing.Visibility = Visibility.Visible; // Setup the UI UpdateBar.Visibility = Visibility.Visible; UpdateButton.IsEnabled = false; CloseButton.IsEnabled = false; // Get a list of updates var updates = await StoreContext.GetDefault().GetAppAndOptionalStorePackageUpdatesAsync(); // Download and install the updates. var downloadOperation = StoreContext.GetDefault() .RequestDownloadAndInstallStorePackageUpdatesAsync(updates); // The Progress async method is called one time for each step in the download // and installation process for each package in this request. downloadOperation.Progress = async(asyncInfo, progress) => { await DispatcherHelper.ExecuteOnUIThreadAsync(() => { UpdateBar.Value = progress.PackageDownloadProgress; }); }; await downloadOperation.AsTask(); ProgressRing.Visibility = Visibility.Collapsed; Hide(); }
async Task PlatformPurchaseById(string storeId) { if (context == null) { context = StoreContext.GetDefault(); } var purchaseResult = await context.RequestPurchaseAsync(storeId); switch (purchaseResult.Status) { case StorePurchaseStatus.Succeeded: break; case StorePurchaseStatus.AlreadyPurchased: throw new Exception($"You already own this add-on.", purchaseResult.ExtendedError); case StorePurchaseStatus.NotPurchased: throw new Exception($"The purchase did not complete or may have been cancelled.", purchaseResult.ExtendedError); case StorePurchaseStatus.NetworkError: case StorePurchaseStatus.ServerError: throw new Exception($"The purchase was unsuccessful due to a server or network error.", purchaseResult.ExtendedError); default: throw new Exception("The purchase was unsuccessful due to an unknown error", purchaseResult.ExtendedError); } }