/// <summary>
        /// Searches thought the inventories for the first possible purchase to execute, attempting to sell more of the resource of minimum utility
        ///     bit by bit until a purchase is possible
        ///
        /// There is a fundamental problem with this in terms of optimization: This only looks for the -first- purchase that can happen: not the -best-
        ///     purchase. finding the best purchase option would require evaluating all possible selling amounts, or
        ///     using a completely different search strategy
        /// To make this work well enough for resource sets with just a couple possible options, this function will never
        ///     return an exchange in which it purchases the same items as it has sold
        /// </summary>
        /// <param name="minUtility"></param>
        /// <returns></returns>
        private (ExchangeResult <Resource>, PurchaseResult)? GetFirstPossiblePurchase(Resource minUtility)
        {
            PurchaseResult purchaseOption = null;
            ActionOption <ExchangeResult <Resource> > sellOption = null;
            float purchaseAmount = 0;
            int   iterations     = 0;

            while (purchaseOption == null || purchaseOption.ledger.exchages.Count() <= 0)
            {
                var simSelfInventory  = CloneSelfInventory();
                var simOtherInventory = CloneOtherInventory();
                purchaseAmount += increment;

                // Execute all operations on a simulated inventory to make sure all prices, utilities,
                //  and any constraints on size are respected
                sellOption = exchange.Sell(minUtility, purchaseAmount, simSelfInventory, simOtherInventory);
                // If the sold amount is less than the requested amount by more than increment
                //  this means that we aren't going to gain anything at all
                if (sellOption.info.amount <= (purchaseAmount - increment))
                {
                    return(null);
                }
                sellOption.Execute();

                purchaseOption = PurchaseResult.Purchase(this, simSelfInventory, simOtherInventory, new[] { minUtility });

                iterations++;
                if (iterations > 1000)
                {
                    throw new Exception("Attempted to find purchase option over too many iterations, broke to safegaurd against infinite loop");
                }
            }
            return(sellOption.info, purchaseOption);
        }
        public StorePurchase GetPurchase(string productId, PurchaseResult purchaseResult)
        {
            StorePurchase p = new StorePurchase();

            string purchaseToken = purchaseResult.PurchaseId;

            if (string.IsNullOrEmpty(purchaseToken))
            {
                throw new StoreInvalidPurchaseException("PurchaseToken not found in Purchase Transaction Data");
            }

            if (string.IsNullOrEmpty(_iTunesStorePassword))
            {
                throw new StoreConfigurationException("iTunes Store Password cannot be empty");
            }

            try
            {
                p = ValidatePurchase(purchaseToken, purchaseResult, PurchaseEnvironment.Production);
            }
            catch (StoreResponseEnvironmentException)
            {
                p = ValidatePurchase(purchaseToken, purchaseResult, PurchaseEnvironment.Sandbox);
            }
            return(p);
        }
Ejemplo n.º 3
0
 private void onPurchaseComplete(ShopEntry entry, PurchaseResult result)
 {
     if (result == PurchaseResult.Success)
     {
         PlayerView.Binder.MenuSystem.closeAllMenusAndTransitionToNewMenu(MenuType.NONE, MenuContentType.NONE, null);
     }
 }
Ejemplo n.º 4
0
    public async Task <PurchaseResult> PurchaseUpgrade(string userId, ProcessType process)
    {
        await Task.Delay(MockLag);

        UserData       user;
        PurchaseResult result = new PurchaseResult();

        if ((int)process < (int)ProcessType.COUNT && (int)process >= 0)
        {
            result.processType = process;
            if (userData.TryGetValue(userId, out user))
            {
                int level = user.processData[(int)process].level;
                if (level < configData.configData[(int)process].levels.Length - 1)
                {
                    long cost = configData.configData[(int)process].levels[level + 1].cost;
                    if (user.cookieCount >= cost)
                    {
                        user.cookieCount -= cost;
                        ++user.processData[(int)process].level;
                    }
                }
                result.buildingCount = user.processData[(int)process].count;
                result.cookieCount   = user.cookieCount;
            }
        }
        return(result);
    }
        /// <summary>
        /// Optimize transactions on the provided exchange. This will execute purchases via the exchange methods provided, after
        ///     finding an available trade which can increase utility.
        /// </summary>
        /// <returns>a summary of all exchanges made during the optimization</returns>
        public IList <(ExchangeResult <Resource>?, PurchaseOperationResult <Resource>)> Optimize()
        {
            var transactionLedger = new List <(ExchangeResult <Resource>?, PurchaseOperationResult <Resource>)>();
            var purchase          = PurchaseResult.Purchase(this, selfInventory, otherInventory);

            if (purchase?.ledger.exchages.Count > 0)
            {
                transactionLedger.Add((null, purchase.ledger));
            }

            var iterations       = 0;
            var executesPurchase = true;

            for (var minUtility = GetHighestSellableValuePerUtility(increment, selfInventory, otherInventory);
                 !EqualityComparer <Resource> .Default.Equals(minUtility, default) && executesPurchase;
                 minUtility = GetHighestSellableValuePerUtility(increment, selfInventory, otherInventory))
            {
                var nextTransaction = SellUntilPurchaseCanHappen(minUtility);

                if (!nextTransaction.HasValue)
                {
                    break;
                }
                transactionLedger.Add(nextTransaction.Value);
                iterations++;
                if (iterations > 1000)
                {
                    throw new Exception("Attempted to optimize over too many iterations, broke to safegaurd against infinite loop");
                }
            }

            return(transactionLedger);
        }
Ejemplo n.º 6
0
        private IEnumerator IEBuy()
        {
            purchaseResultText.text = "خرید با موفقیت انجام شد".ToFarsi();
            purchaseStartPage.SetActive(false);
            purchaseResultPage.SetActive(true);
            Instacne.checkObject.SetActive(true);
            yield return(new WaitForSecondsRealtime(0.6f));

            Instacne.Animator.SetTrigger("Hide");
            yield return(new WaitForSecondsRealtime(0.3f));

            if (OnResult != null)
            {
                Purchase product = new Purchase();
                product.ProductId        = SKU;
                product.PurchaseTime     = DateTime.UtcNow;
                product.PurchaseToken    = Guid.NewGuid().ToString();
                product.State            = PurchaseState.Purchased;
                product.OrderId          = product.PurchaseToken;
                product.Signature        = "";
                product.DeveloperPayload = DeveloperPayload;

                PurchaseResult result = new PurchaseResult();
                result.Status   = PurchaseStatus.Success;
                result.TestMode = true;
                result.Purchase = product;
                OnResult(result);

                OnResult = null;
            }
        }
Ejemplo n.º 7
0
        public bool AcknowledgePurchase(GxUserType gxStoreConfig, string productId, GxUserType gxPurchaseResult)
        {
            IStoreManager          storeMgr = null;
            int                    errCode  = GetManager(gxStoreConfig, 2, out storeMgr);
            GooglePlayStoreManager mgr      = (GooglePlayStoreManager)storeMgr;
            PurchaseResult         purchase = JSONHelper.Deserialize <PurchaseResult>(gxPurchaseResult.ToJSonString());

            try
            {
                return(mgr.AcknowledgePurchase(productId, purchase));
            }
            catch (StoreConfigurationException e)
            {
                errCode        = 3;
                ErrDescription = e.Message;
            }
            catch (StoreInvalidPurchaseException e)
            {
                errCode        = 2;
                ErrDescription = e.Message;
            }
            catch (StoreServerException e)
            {
                errCode        = 4;
                ErrDescription = e.Message;
            }
            catch (StoreException e)
            {
                errCode        = 10;
                ErrDescription = e.Message;
            }
            return(false);
        }
    //--------------------------------------
    // Event Handlers
    //--------------------------------------


    private void IOS_OnTransactionComplete(PurchaseResult responce)
    {
        UM_InAppProduct p = UltimateMobileSettings.Instance.GetProductByIOSId(responce.ProductIdentifier);

        if (p != null)
        {
            UM_PurchaseResult r = new UM_PurchaseResult();
            r.product          = p;
            r.IOS_PurchaseInfo = responce;


            switch (r.IOS_PurchaseInfo.State)
            {
            case PurchaseState.Purchased:
            case PurchaseState.Restored:
                r.isSuccess = true;
                break;

            case PurchaseState.Deferred:
            case PurchaseState.Failed:
                r.isSuccess = false;
                break;
            }

            SendPurchaseFinishedEvent(r);
        }
        else
        {
            SendNoTemplateEvent();
        }
    }
Ejemplo n.º 9
0
        /// <summary>
        /// returns all purchases
        /// </summary>
        /// <param name="itemType">not used for Amazon</param>
        /// <param name="verifyPurchase">Not Used for Amazon</param>
        /// <param name="verifyOnlyProductId">Not Used for Amazon</param>
        /// <returns></returns>
        public async Task <List <PurchaseResult> > GetPurchasesAsync(ItemType itemType = ItemType.InAppPurchase, IInAppBillingVerifyPurchase verifyPurchase = null, string verifyOnlyProductId = null)
        {
            var PurchaseHistoryResult = new List <PurchaseResult>();
            var purchaseReceipts      = await GetPurchaseReceipts();

            if (purchaseReceipts?.Count > 0)
            {
                foreach (var purchase in purchaseReceipts)
                {
                    var purchaseHistory = new PurchaseResult();
                    purchaseHistory.Sku           = purchase.Sku;
                    purchaseHistory.PurchaseToken = purchase.ReceiptId;

                    if (purchase.PurchaseDate > 0)
                    {
                        purchaseHistory.PurchaseDate = DateTimeOffset.FromUnixTimeSeconds(purchase.PurchaseDate).DateTime;
                    }

                    purchaseHistory.DeveloperPayload = null;
                    if (purchase.CancelDate > 0)
                    {
                        purchaseHistory.ExpirationDate = DateTimeOffset.FromUnixTimeSeconds(purchase.CancelDate).DateTime;
                        purchaseHistory.PurchaseState  = PurchaseState.Cancelled;
                    }
                    else
                    {
                        purchaseHistory.PurchaseState = PurchaseState.Purchased;
                    }

                    PurchaseHistoryResult.Add(purchaseHistory);
                }
            }

            return(PurchaseHistoryResult);
        }
Ejemplo n.º 10
0
 // Update is called once per frame
 void Update()
 {
     if (countTask != null)
     {
         if (countTask.IsCompleted)
         {
             confirmedCookies = countTask.Result;
             CookieGameManager.Instance.UserData.cookieCount = confirmedCookies;
             cookieCountText.text = (confirmedCookies + bufferedClicks).ToString();
             countTask            = null;
             UpdateShop();
             predictedClicks = 0;
         }
     }
     else if (purchaseTask != null)
     {
         if (purchaseTask.IsCompleted)
         {
             PurchaseResult result = purchaseTask.Result;
             CookieGameManager.Instance.UserData.cookieCount = result.cookieCount;
             CookieGameManager.Instance.UserData.processData[(int)result.processType].count = result.buildingCount;
             UpdateShop();
             UpdateUpgrades();
             purchaseTask = null;
         }
     }
     else if (Time.time - lastSendTime > 1.0f)
     {
         countTask    = CookieServer.Instance.RequestProcessUser(CookieGameManager.Instance.UserId);
         lastSendTime = Time.time;
     }
 }
Ejemplo n.º 11
0
 private void onShopPurchaseCompleted(ShopEntry shopEntry, PurchaseResult purchaseResult)
 {
     if (ConfigShops.IsIapShopEntry(shopEntry))
     {
         PlayerView.Binder.MenuSystem.waitAndTransitionToNewMenu(MenuType.StackedPopupMenu, MenuContentType.VendorPopupContent, null);
     }
 }
Ejemplo n.º 12
0
        public void RecoverHP_PickAItem_ReturnTrue()
        {
            var item = new ItemInfo
            {
                Id = "cs"
            };

            _solution.Setup(s => s.PickAPotion(It.IsAny <List <ItemInfo> >(),
                                               It.IsAny <int>()))
            .Returns(item);

            var purchaseResult = new PurchaseResult
            {
                ShoppingSuccess = true
            };

            _shopService.Setup(s => s.Purchase(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.FromResult(purchaseResult));

            var result = _store.RecoverHP();

            _solution.Verify(s => s.PickAPotion(It.IsAny <List <ItemInfo> >(),
                                                It.IsAny <int>()));
            Assert.That(result, Is.EqualTo(true));
        }
 private void onPurchaseComplete(ShopEntry entry, PurchaseResult result)
 {
     if (result == PurchaseResult.Success)
     {
         Service.Binder.PromotionManager.ConsumePromotion(this.m_inputParameters.Promotion, true);
         Service.Binder.EventBus.PromotionAction(this.m_inputParameters.Promotion.promotionid, "purchase");
     }
 }
Ejemplo n.º 14
0
        private void onShopPurchaseCompleted(ShopEntry shopEntry, PurchaseResult purchaseResult)
        {
            InputParameters parameters2 = new InputParameters();

            parameters2.ItemInstance = this.ItemInstance;
            InputParameters parameter = parameters2;

            PlayerView.Binder.MenuSystem.waitAndTransitionToNewMenu(MenuType.ThinPopupMenu, MenuContentType.ItemInfoContent, parameter);
        }
 private void onShopPurchaseCompleted(ShopEntry shopEntry, PurchaseResult purchaseResult)
 {
     if (ConfigShops.IsIapShopEntry(shopEntry))
     {
         MiniPopupMenu.InputParameters parameters2 = new MiniPopupMenu.InputParameters();
         parameters2.MenuContentParams = this.m_param;
         MiniPopupMenu.InputParameters parameter = parameters2;
         PlayerView.Binder.MenuSystem.waitAndTransitionToNewMenu(MenuType.MiniPopupMenu, MenuContentType.VendorMiniPopupContent, parameter);
     }
 }
Ejemplo n.º 16
0
        public void LauraBuyAndThePurchaseIsValid()
        {
            List <Item>       items             = NewItems("pull rouge", "pantalon noir");
            CreditCardDetails creditCardDetails = new CreditCardDetails("6546597543445912");
            Address           address           = new Address("55 Rue du Faubourg Saint-Honoré");

            PurchaseResult purchaseResult = NewPurchase.Confirm(items, address, creditCardDetails);

            Assert.True(purchaseResult.IsValid);
        }
Ejemplo n.º 17
0
        private void OnPurchaseInternalResultHandler(IAPProduct product, PurchaseResult purchaseResult)
        {
            SetActionState(false);

            _purchaseHandler?.Invoke(product, purchaseResult);

            OnPurchasedEvent?.Invoke(product, purchaseResult);

            Debug.Log($"AppCore IAP -> purchase result for product with id '{product.Id}' and name '{product.Name}' is '{purchaseResult.ToString()}'");
        }
Ejemplo n.º 18
0
        private void BuyButtonClicked()
        {
            this.result = PurchaseResult.Buy;

            if (this.automaticallyPerformPurchase)
            {
                PF.Purchasing.PurchaseStoreItem(this.storeId, this.storeItem);
            }

            this.Dialog.Hide();
        }
Ejemplo n.º 19
0
        public void AnnaBuyButBankRejectPayment()
        {
            List <Item>       items             = NewItems("chemise verte", "pantalon noir");
            CreditCardDetails creditCardDetails = new CreditCardDetails("9745965412543654");
            Address           address           = new Address("55 Rue du Faubourg Saint-Honoré");

            PurchaseResult purchaseResult = NewPurchase.Confirm(items, address, creditCardDetails);

            Assert.False(purchaseResult.IsValid);
            Assert.NotEmpty(purchaseResult.Errors);
            Assert.Equal("solde insuffisant", purchaseResult.Errors.First());
        }
Ejemplo n.º 20
0
        static bool PurchaseSelector <TPurchaseReport>(ICommandResult cmdResult)
            where TPurchaseReport : IPurchaseReport
        {
            PurchaseResult purchaseResult = cmdResult as PurchaseResult;

            if (purchaseResult == null)
            {
                return(false);
            }

            return(purchaseResult.Report.GetType() == typeof(TPurchaseReport));
        }
Ejemplo n.º 21
0
        public void KevinBuyButOneArticleIsNoLongerAvailable()
        {
            List <Item>       items             = NewItems("tee-shirt rouge", "short blanc", "pull violet");
            CreditCardDetails creditCardDetails = new CreditCardDetails("7895265452543153");
            Address           address           = new Address("1 Avenue du Colonel Henri Rol-Tanguy");

            PurchaseResult purchaseResult = NewPurchase.Confirm(items, address, creditCardDetails);

            Assert.False(purchaseResult.IsValid);
            Assert.NotEmpty(purchaseResult.Errors);
            Assert.Equal("tee-shirt rouge indisponible", purchaseResult.Errors.First());
        }
Ejemplo n.º 22
0
        public void JohnBuyButAddressIsInexistant()
        {
            List <Item>       items             = NewItems("pull rouge", "pull violet");
            CreditCardDetails creditCardDetails = new CreditCardDetails("7526215354358945");
            Address           address           = new Address("77 Avenue du Jambon");

            PurchaseResult purchaseResult = NewPurchase.Confirm(items, address, creditCardDetails);

            Assert.False(purchaseResult.IsValid);
            Assert.NotEmpty(purchaseResult.Errors);
            Assert.Equal("adresse inexistante", purchaseResult.Errors.First());
        }
Ejemplo n.º 23
0
        public int GetPurchase(GxUserType gxStoreConfig, string productId, GxUserType gxPurchaseResult, GxUserType gxStorePurchase)
        {
            PurchaseResult purchase = JSONHelper.Deserialize <PurchaseResult>(gxPurchaseResult.ToJSonString());
            StorePurchase  sp       = null;
            int            errCode  = GetPurchaseImpl(gxStoreConfig, productId, purchase, out sp);

            if (errCode == 0)
            {
                gxStorePurchase.FromJSonString(sp.ToJson());
            }
            return(errCode);
        }
Ejemplo n.º 24
0
 private void OnResumePurchaseResult(PurchaseResult result)
 {
     base.m_contentMenu.setCloseButtonVisibility(true);
     if (result == PurchaseResult.Fail)
     {
         this.LoadingIndicator.SetActive(false);
         this.Text.text = _.L(ConfigLoca.IAP_SOMETHING_WENT_WRONG, null, false);
     }
     else
     {
         (base.m_contentMenu as TechPopupMenu).onCloseButtonClicked();
     }
 }
Ejemplo n.º 25
0
        static TPurchaseReport Cast <TPurchaseReport>(ICommandResult cmdResult)
            where TPurchaseReport : IPurchaseReport
        {
            PurchaseResult purchaseResult = cmdResult as PurchaseResult;

            if (purchaseResult == null)
            {
                return(default(TPurchaseReport));
            }

            IPurchaseReport report = purchaseResult.Report;

            return((TPurchaseReport)report);
        }
Ejemplo n.º 26
0
            public override void OnSuccess(Java.Lang.Object jObject)
            {
                PurchaseResult purchaseResult = jObject.JavaCast <PurchaseResult>();

                if (null == purchaseResult)
                {
                    m_debugText = string.Format("PurchaseResult is null!");
                }
                else
                {
                    m_debugText = string.Format("Request Purchase: OnSuccess");
                    Log.Info(TAG, "OnSuccess identiifer" + purchaseResult.ProductIdentifier);
                }
            }
Ejemplo n.º 27
0
        public void MarieBuyButAddressIsInexistantAndOneArticleIsNoLongerAvailableAndBankRejectPayment()
        {
            List <Item>       items             = NewItems("tee-shirt rouge", "pull rose");
            CreditCardDetails creditCardDetails = new CreditCardDetails("1265599754346544");
            Address           address           = new Address("98 Avenue du saucisson");

            PurchaseResult purchaseResult = NewPurchase.Confirm(items, address, creditCardDetails);

            Assert.False(purchaseResult.IsValid);
            Assert.NotEmpty(purchaseResult.Errors);
            Assert.Contains(purchaseResult.Errors, _ => _ == "tee-shirt rouge indisponible");
            Assert.Contains(purchaseResult.Errors, _ => _ == "pull rose indisponible");
            Assert.Contains(purchaseResult.Errors, _ => _ == "adresse inexistante");
            Assert.Contains(purchaseResult.Errors, _ => _ == "solde insuffisant");
        }
Ejemplo n.º 28
0
 private void onResumePurchaseResult(PurchaseResult result)
 {
     if (this.m_inputParams.PurchaseCallback != null)
     {
         this.m_inputParams.PurchaseCallback(this.m_inputParams.ShopEntry, result);
     }
     if (result == PurchaseResult.Fail)
     {
         this.showFailedMessage();
     }
     else
     {
         (base.m_contentMenu as TechPopupMenu).onCloseButtonClicked();
     }
 }
Ejemplo n.º 29
0
        /// <inheritdoc/>
        public Task <PurchaseResult> PurchaseAsync(PurchaseRequest request, CancellationToken cancellationToken)
        {
            // Validate
            _validator.ValidateAndThrow(request);

            // In a production scenrio this would make an external request to our billing provider such as Stripe.
            var stripeChargedAmount = request.AmountInCents;

            // Build Result
            var result = new PurchaseResult(
                purchaseId: Guid.NewGuid(),
                timestamp: DateTimeOffset.UtcNow,
                amountChargedInCents: stripeChargedAmount);

            return(Task.FromResult(result));
        }
Ejemplo n.º 30
0
	private static void HandleOnTransactionComplete (PurchaseResult res) {
		switch(res.State) {
		case PurchaseState.Purchased:
			Product tpl = PaymentManager.Instance.GetProductById(res.ProductIdentifier);
			if(tpl != null) {
				ISN_SoomlaGrow.PurchaseFinished(tpl.Id, tpl.PriceInMicros.ToString(), tpl.CurrencyCode);
			}
			break;
		case PurchaseState.Failed:
			if(res.Error.Code == (int) TransactionErrorCode.SKErrorPaymentCanceled) {
				ISN_SoomlaGrow.PurchaseCanceled(res.ProductIdentifier);
			} else {
				ISN_SoomlaGrow.PurchaseError();
			}
			break;
		}
	}
Ejemplo n.º 31
0
		internal static AsyncHTTPClient DirectPurchase(int packageID, string password, AssetStoreResultBase<PurchaseResult>.Callback callback)
		{
			string url = AssetStoreClient.APIUrl(string.Format("/purchase/direct/{0}", packageID.ToString()));
			PurchaseResult r = new PurchaseResult(callback);
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			dictionary["password"] = password;
			return AssetStoreClient.CreateJSONRequestPost(url, dictionary, delegate(AssetStoreResponse ar)
			{
				r.Parse(ar);
			});
		}