Exemple #1
0
        public coupons_fixture()
        {
            CouponCreateOptions = new StripeCouponCreateOptions()
            {
                // Add a space at the end to ensure the ID is properly URL encoded
                // when passed in the URL for other methods
                Id               = "test-coupon-" + Guid.NewGuid().ToString() + " ",
                PercentOff       = 25,
                Duration         = "repeating",
                DurationInMonths = 3,
            };

            CouponUpdateOptions = new StripeCouponUpdateOptions {
                Metadata = new Dictionary <string, string> {
                    { "key_1", "value_1" }
                }
            };

            var service = new StripeCouponService(Cache.ApiKey);

            Coupon          = service.Create(CouponCreateOptions);
            CouponRetrieved = service.Get(Coupon.Id);
            CouponUpdated   = service.Update(Coupon.Id, CouponUpdateOptions);
            CouponsList     = service.List();
            CouponDeleted   = service.Delete(Coupon.Id);
        }
        public void Serialize()
        {
            var options = new StripeCouponCreateOptions()
            {
                PercentOff = 25,
                Duration   = "forever",
            };

            var url = this.service.ApplyAllParameters(options, string.Empty, false);

            Assert.Equal("?percent_off=25&duration=forever", url);
        }
        public static StripeCouponCreateOptions Valid(int? _redeemBy = null)
        {
            var stripeCouponCreateOptions = new StripeCouponCreateOptions()
            {
                Id = "test-coupon-" + Guid.NewGuid().ToString(),
                PercentOff = 5,
                Duration = "repeating",
                DurationInMonths = 3,
                MaxRedemptions = 5,
                RedeemBy = DateTime.UtcNow.AddDays(1)                
            };

            return stripeCouponCreateOptions;
        }
        public static StripeCouponCreateOptions Valid()
        {
            var stripeCouponCreateOptions = new StripeCouponCreateOptions()
            {
                Id               = "test-coupon-" + Guid.NewGuid().ToString(),
                PercentOff       = 5,
                Duration         = "repeating",
                DurationInMonths = 3,
                MaxRedemptions   = 5,
                RedeemBy         = DateTime.UtcNow.AddDays(1)
            };

            return(stripeCouponCreateOptions);
        }
        public JsonResult AddUpdateCode(AffiliationData cdata)
        {
            String res = "";

            if (ModelState.IsValid)
            {
                if ((cdata.Redeemby >= DateTime.Now && cdata.Redeemby != null) || cdata.Redeemby == null)
                {
                    try
                    {
                        String Code          = cdata.Code.Trim();
                        var    couponOptions = new StripeCouponCreateOptions();
                        couponOptions.Id             = Code;
                        couponOptions.Duration       = cdata.Duration == 0 ? "once" : "forever";
                        couponOptions.MaxRedemptions = cdata.Maxredeem;
                        if (cdata.Redeemby != null)
                        {
                            couponOptions.RedeemBy = Convert.ToDateTime(cdata.Redeemby).AddMinutes(-1).AddDays(1);
                        }
                        if (cdata.Amount == null || cdata.Amount == 0)
                        {
                            couponOptions.PercentOff = cdata.Percent;
                        }
                        else
                        {
                            couponOptions.AmountOff = (int)cdata.Amount * 100;
                            couponOptions.Currency  = "usd";
                        }
                        StripeHelper.CreateCoupon(couponOptions);
                        var userid = Convert.ToInt32(Session["AdminUserID"]);
                        res = adata.AddUpdateCouponData(Code, cdata.Duration, cdata.Amount, cdata.Percent, cdata.Maxredeem, cdata.Redeemby, userid);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
                else
                {
                    res = "Redeemby must be greater than current date.";
                }
            }
            else
            {
                res = "Failed!";
            }
            return(new JsonResult {
                Data = res, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
		public static StripeCouponCreateOptions ValidAmountOff()
		{
			var stripeCouponCreateOptions = new StripeCouponCreateOptions()
			{
				Id = "test-coupon-" + Guid.NewGuid().ToString(),
				AmountOff = 10,
				Currency = "usd",
				Duration = "repeating",
				DurationInMonths = 3,
				MaxRedemptions = 5,
				RedeemBy = DateTime.UtcNow.AddDays(1)
			};

			return stripeCouponCreateOptions;
		}
        public StripeCouponServiceTest()
        {
            this.service = new StripeCouponService();

            this.createOptions = new StripeCouponCreateOptions()
            {
                PercentOff = 25,
                Duration   = "forever",
            };

            this.updateOptions = new StripeCouponUpdateOptions()
            {
                Metadata = new Dictionary <string, string>()
                {
                    { "key", "value" },
                },
            };

            this.listOptions = new StripeCouponListOptions()
            {
                Limit = 1,
            };
        }
Exemple #8
0
        public ActionResult Create(CouponCreateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var options = new StripeCouponCreateOptions
            {
                Id               = model.Id,
                AmountOff        = model.AmountOff,
                Currency         = model.Currency,
                Duration         = model.Duration,
                DurationInMonths = model.DurationInMonths,
                MaxRedemptions   = model.MaxRedemptions,
                PercentOff       = model.PercentOff,
                RedeemBy         = model.RedeemBy
            };

            var couponService = new StripeCouponService();
            var coupon        = couponService.Create(options);

            return(RedirectToAction("Index"));
        }
        public static void CreateCoupon(StripeCouponCreateOptions couponOptions)
        {
            var couponService = new StripeCouponService();

            couponService.Create(couponOptions);
        }
        private int PurchaseSubscription(out bool success)
        {
            // Check customer change their email
            success = true;
            bool isPayByCredit;

            var bookingExists = _subscriptionBookingRepository.GetBookingInLast3Minutes(PublicSubscription.Id,
                                                                                        PublicCustomerInfos != null ? PublicCustomerInfos.EmailAddress : email.Text.Replace(" ", ""));

            if (bookingExists != null)
            {
                success = false;
                newBookingModal.Visible = true;
                return(bookingExists.Id);
            }

            if (PublicCustomerInfos == null)
            {
                PublicCustomerInfos = new CustomerInfos
                {
                    EmailAddress = email.Text.Replace(" ", ""),
                    FirstName    = FirstName.Text.Trim(),
                    LastName     = LastName.Text.Trim(),
                    ZipCode      = txtzipcode.Text.Trim()
                };

                // Create new account with email
                var response = _customerInfoRepository.GetVipAccess(email.Text.Replace(" ", ""), Constant.SearchPageDefault, FirstName.Text.Trim(), LastName.Text.Trim());
                PublicCustomerInfos.CustomerId       = response.CustomerId;
                PublicCustomerInfos.StripeCustomerId = response.StripeCustomerId;

                CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);

                Session["ReferralCode"] = response.ReferralCode;

                string searchPage = !string.IsNullOrEmpty((string)Session["SearchPage"])
                    ? Session["SearchPage"].ToString()
                    : Constant.SearchPageDefault;

                // Send email new account
                var responseEmail = EmailHelper.EmailNewAccount(PublicCustomerInfos.EmailAddress,
                                                                PublicCustomerInfos.FirstName,
                                                                response.Password,
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?sp={1}",
                                                                                                                  searchPage,
                                                                                                                  response.PasswordKey)), // Reset Password Url
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?c={1}",
                                                                                                                  searchPage,
                                                                                                                  response.AccessKey))); // Browse Day Pass
                PublicCustomerCredits = _subscriptionBookingRepository.GetCustomerCredits(response.CustomerId);


                Session["UserSession"]  = response.AccessKey;
                Session["IsRegister"]   = true;
                Session["ReferralCode"] = response.ReferralCode;
            }

            Regex regex = new Regex(@"([\d]+)(\s)?/(\s)?([\d]+)");
            int   month;
            int   year;

            int.TryParse(regex.Match(txtexpdat.Value).Groups[1].Value, out month);
            int.TryParse("20" + regex.Match(txtexpdat.Value).Groups[4].Value, out year);
            string fullName = string.Format("{0} {1}", FirstName.Text, LastName.Text);

            // Check customer has exists with email
            int            customerId     = PublicCustomerInfos.CustomerId;
            StripeCustomer stripeCustomer = null;
            Discounts      discounts      = new Discounts();
            double         actualPrice    = PublicSubscription.Price;
            double         totalPrice;
            bool           hasCoupon      = false;
            string         stripeCouponId = string.Empty;

            // update user info with exists
            if (!string.IsNullOrEmpty(PublicCustomerInfos.StripeCustomerId))
            {
                stripeCustomer = GetCustomerById(PublicCustomerInfos.StripeCustomerId);
            }

            // Use New Card
            if (MVCardInfo.ActiveViewIndex == 0)
            {
                StripeToken stripeToken = CreateToken(cctextbox.Text.Replace(" ", ""), year, month, txtzipcode.Text,
                                                      fullName,
                                                      txtseccode.Value);

                // update new card for customer
                PublicCustomerInfos.StripeTokenId    = stripeToken.Id;
                PublicCustomerInfos.StripeCardId     = stripeToken.StripeCard.Id;
                PublicCustomerInfos.BankAccountLast4 = stripeToken.StripeCard.Last4;
                PublicCustomerInfos.CardType         = Helper.GetCreditCardType(cctextbox.Text.Replace(" ", ""));
                PublicCustomerInfos.ZipCode          = txtzipcode.Text;

                if (stripeCustomer == null)
                {
                    stripeCustomer = CreateCustomer(PublicCustomerInfos.EmailAddress, fullName, stripeToken.Id);
                    PublicCustomerInfos.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    // Update Stripe exists customer with New Card
                    var card = CreateCard(stripeToken.Id, PublicCustomerInfos.StripeCustomerId);
                    UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName,
                                   PublicCustomerInfos.StripeCustomerId, card.Id);
                }
                _customerInfoRepository.Update(PublicCustomerInfos);

                isPayByCredit = IsPayByCreditCheckBox.Checked;
            }
            else
            {
                isPayByCredit = DCreditCheckBox.Checked;
            }

            if (string.IsNullOrWhiteSpace(PromoText.Text))
            {
                Session.Remove(_discountKey);
            }

            // Not available upgrade so checkout with this hotel
            if (Session[_discountKey] != null)
            {
                discounts = JsonConvert.DeserializeObject <Discounts>(Session[_discountKey].ToString());
            }

            // Have Discount
            if (discounts != null && discounts.Id > 0)
            {
                discounts = _discountRepository.VerifyDiscountsSubscription(discounts, customerId, PublicSubscription.Id);

                // Discount Invalid
                if (discounts != null)
                {
                    actualPrice = Helper.CalculateDiscount(discounts, actualPrice, TotalTickets);
                    hasCoupon   = true;
                }
                else
                {
                    InitDefaultPromo(Message.ExceedLimit, false);
                    Session[_discountKey] = null;
                    success = false;
                    return(0);
                }

                if (discounts.BillingCycleNumber > 1)
                {
                    stripeCouponId = string.Format("{0}C{1}", PublicCustomerInfos.CustomerId,
                                                   Helper.RandomString(Constant.BookingCodeLength));
                    if (discounts.PercentOff > 0)
                    {
                        var couponPrice = PublicSubscription.Price - actualPrice;
                        //Create the Coupon
                        var coupon = new StripeCouponCreateOptions
                        {
                            Duration         = "repeating",
                            Id               = stripeCouponId,
                            MaxRedemptions   = discounts.BillingCycleNumber,
                            DurationInMonths = discounts.BillingCycleNumber
                        };


                        if (discounts.PromoType == (int)Enums.PromoType.Fixed)
                        {
                            coupon.AmountOff = (int)(couponPrice * 100);
                            coupon.Currency  = "usd";
                        }

                        if (discounts.PromoType == (int)Enums.PromoType.Percent)
                        {
                            coupon.PercentOff = (int)(discounts.PercentOff);
                        }

                        //coupon.AmountOff - AmountOff is not a property of StripeCouponCreateOptions
                        var          couponService = new StripeCouponService();
                        StripeCoupon createdCoupon = couponService.Create(coupon);

                        //Apply it to the customer
                        var customerOptions = new StripeCustomerUpdateOptions
                        {
                            Coupon = createdCoupon.Id
                        };

                        var customerService = new StripeCustomerService();
                        customerService.Update(PublicCustomerInfos.StripeCustomerId, customerOptions);
                    }
                }
            }

            if (PublicCustomerInfos.FirstName != FirstName.Text.Trim() || PublicCustomerInfos.LastName != LastName.Text.Trim())
            {
                PublicCustomerInfos.FirstName = FirstName.Text.Trim();
                PublicCustomerInfos.LastName  = LastName.Text.Trim();
                _customerInfoRepository.Update(PublicCustomerInfos);

                // Update Stripe exists customer
                UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName, PublicCustomerInfos.StripeCustomerId, string.Empty);
            }

            // Discount 100% ??
            // Price equal 0, so we should not charge with this
            totalPrice = actualPrice * TotalTickets;
            double chargePrice          = totalPrice;
            string creditLogDescription = string.Empty;

            var subscriptionOptions = new StripeSubscriptionCreateOptions
            {
                PlanId = PublicSubscription.StripePlanId
            };

            // Use DayAxe Credit
            if (isPayByCredit && PublicCustomerCredits != null && PublicCustomerCredits.Amount > 0)
            {
                hasCoupon = true;

                chargePrice = totalPrice - PublicCustomerCredits.Amount;
                if (chargePrice <= 0)
                {
                    chargePrice = 0;
                }
            }

            if (hasCoupon && string.IsNullOrEmpty(stripeCouponId))
            {
                var couponPrice = PublicSubscription.Price - chargePrice;
                if (couponPrice > 0)
                {
                    // Create Coupon Id because we used DayAxe Credit
                    stripeCouponId = string.Format("{0}C{1}", PublicCustomerInfos.CustomerId,
                                                   Helper.RandomString(Constant.BookingCodeLength));
                    var couponOptions = new StripeCouponCreateOptions
                    {
                        Id        = stripeCouponId,
                        AmountOff = Convert.ToInt32(couponPrice * 100), // USD
                        Duration  = "once",
                        Currency  = "USD"
                    };

                    // Create Coupon
                    var couponService = new StripeCouponService();
                    var coupon        = couponService.Create(couponOptions);

                    subscriptionOptions.CouponId = stripeCouponId;

                    creditLogDescription = string.Format("{0} – {1}",
                                                         PublicSubscription.Name, coupon.Id);
                }
            }

            // Create Subscription on Stripe
            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Create(PublicCustomerInfos.StripeCustomerId, subscriptionOptions);

            var booking = new SubscriptionBookings
            {
                SubscriptionId       = PublicSubscription.Id,
                Quantity             = TotalTickets,
                StripeCouponId       = stripeCouponId,
                BookedDate           = DateTime.UtcNow,
                ActivedDate          = subscription.Start,
                StartDate            = subscription.CurrentPeriodStart,
                EndDate              = subscription.CurrentPeriodEnd,
                Status               = (int)Enums.SubscriptionBookingStatus.Active,
                CustomerId           = customerId,
                LastUpdatedDate      = DateTime.UtcNow,
                LastUpdatedBy        = customerId,
                StripeSubscriptionId = subscription.Id
            };

            var param = new AddSubscriptionBookingParams
            {
                SubscriptionBookingsObject = booking,
                CustomerCreditsObject      = PublicCustomerCredits,
                Description                  = creditLogDescription,
                SubscriptionName             = PublicSubscription.Name,
                FirstName                    = PublicCustomerInfos.FirstName,
                LastName                     = PublicCustomerInfos.LastName,
                SubscriptionBookingDiscounts = discounts,
                ActualPrice                  = actualPrice,
                MerchantPrice                = PublicSubscription.Price,
                PayByCredit                  = totalPrice.Equals(chargePrice) ? 0 : totalPrice - chargePrice,
                TotalPrice                   = chargePrice,
                MaxPurchases                 = PublicSubscription.MaxPurchases
            };

            int bookingId = _subscriptionBookingRepository.Add(param);

            //Session.Remove(_discountKey);

            CacheLayer.Clear(CacheKeys.SubscriptionBookingsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);
            CacheLayer.Clear(CacheKeys.DiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionBookingDiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubsciptionDiscountUsedCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionDiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionCyclesCacheKey);

            return(bookingId);
        }