Beispiel #1
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecreatKey"];
            var basket = await _basketRepository.GetBasketAsync(basketId);

            var shippingPrice = 0m; // 259 "m" for money

            if (basket == null)
            {
                return(null);                // 270
            }
            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }

                var           service = new PaymentIntentService();
                PaymentIntent intent;

                if (string.IsNullOrEmpty(basket.PaymentIntentId))
                {
                    var options = new PaymentIntentCreateOptions
                    {
                        Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) +
                                 (long)shippingPrice * 100,
                        Currency           = "usd",
                        PaymentMethodTypes = new List <string> {
                            "card"
                        }
                    };

                    intent = await service.CreateAsync(options); //  what we get back from stripe

                    basket.PaymentIntentId = intent.Id;
                    basket.ClientSecret    = intent.ClientSecret;
                }
                else
                { // posibility client get changers after going thrugh the check out after already created payment intent
                    var options = new PaymentIntentUpdateOptions
                    {
                        Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) +
                                 (long)shippingPrice * 100
                    };
                    await service.UpdateAsync(basket.PaymentIntentId, options);
                }

                await _basketRepository.UpdateBasketAsync(basket); // 259 update if there any changed
            }
            return(basket);
        }
Beispiel #2
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            if (basket == null)
            {
                return(null);
            }

            var shippingPrice = 0m;

            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync(basket.DeliveryMethodId.Value);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }
            var service = new PaymentIntentService();

            PaymentIntent intent;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions
                {
                    Amount             = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    Currency           = "inr",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    },
                    Shipping = new ChargeShippingOptions
                    {
                        Name    = "Mohit Acharya",
                        Address = new AddressOptions
                        {
                            Line1      = "510 Townsend St",
                            PostalCode = "464441",
                            City       = "Baroda",
                            State      = "MP",
                            Country    = "US",
                        },
                    },
                    Description = "Software development services"
                };
                intent = await service.CreateAsync(options);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100
                };
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
Beispiel #3
0
        public async Task <CustomerCart> CreateOrUpdatePaymentIntent(string cartId)
        {
            StripeConfiguration.ApiKey = _configuration["StripeSettings:SecretKey"];

            var cart = await _cartRepository.GetCartAsync(cartId);

            if (cart == null)
            {
                return(null);
            }

            // m for money
            var shippingPrice = 0m;

            if (cart.DeliveryMethodId.HasValue)
            {
                var deliveryMethode = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync((int)cart.DeliveryMethodId);

                shippingPrice = deliveryMethode.Price;
            }

            foreach (var item in cart.CartItems)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.CartItemId);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }

            // PaymentIntentService coming from stripe
            var service = new PaymentIntentService();

            PaymentIntent intent;

            if (string.IsNullOrEmpty(cart.PaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions()
                {
                    Amount             = (long)cart.CartItems.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    Currency           = "usd",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };

                intent = await service.CreateAsync(options);

                cart.PaymentIntentId = intent.Id;
                cart.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions()
                {
                    Amount = (long)cart.CartItems.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100
                };

                await service.UpdateAsync(cart.PaymentIntentId, options);
            }

            await _cartRepository.UpdateCartAsync(cart);

            return(cart);
        }
        /// <inheritdoc />
        /// <exception cref="UserNotFoundException">Thrown when the user is not found</exception>
        /// <exception cref="Exception">Thrown if error</exception>
        /// <exception cref="EventNotFoundException">Thrown if the event is not found</exception>
        public async Task <TransactionViewModel> CreateIntent(CreateIntentBody createIntentBody)
        {
            var user = await ApplicationContext.Users
                       .Include(x => x.PaymentMethods)
                       .FirstOrDefaultAsync(x => x.Id == createIntentBody.UserId);

            var e = await ApplicationContext.Events.AsSplitQuery()
                    .Include(x => x.Promos)
                    .Include(x => x.Host)
                    .Include(x => x.Tickets)
                    .Include(x => x.Transactions)
                    .FirstOrDefaultAsync(x => x.Id == createIntentBody.EventId);

            if (user == null)
            {
                Logger.LogInformation("User was not found");
                throw new UserNotFoundException();
            }

            // if the user doesn't have a customer id or payment method throw exception
            if (user.StripeCustomerId == null || !user.PaymentMethods.Any())
            {
                throw new Exception("Not enough stripe info");
            }

            if (e == null)
            {
                Logger.LogInformation("Event was not found");
                throw new EventNotFoundException();
            }

            // if the host of the event hasn't setup a bank account throw exception
            if (e.Host.StripeAccountId == null)
            {
                throw new Exception("The host doesn't have enough stripe info");
            }

            // gets a promo that's currently active
            var promo = e.Promos.FirstOrDefault(x => x.Active && x.Start < DateTime.Now && DateTime.Now < x.End);

            if (promo != null)
            {
                // applies discount to price
                createIntentBody.Amount -= (createIntentBody.Amount * promo.Discount / 100);
                Logger.LogInformation("Found promo for event");
            }

            // Stipee api create intent options
            var options = new PaymentIntentCreateOptions()
            {
                Amount               = createIntentBody.Amount,
                Currency             = "gbp",
                OnBehalfOf           = e.Host.StripeAccountId,
                Customer             = user.StripeCustomerId,
                ConfirmationMethod   = "manual",
                ApplicationFeeAmount = 10,
                TransferData         = new PaymentIntentTransferDataOptions()
                {
                    Destination = e.Host.StripeAccountId
                },
                PaymentMethodTypes = new List <string>
                {
                    "card"
                },
                Metadata = new Dictionary <string, string>
                {
                    { "EventId", e.Id.ToString() },
                    { "PromoId", promo?.Id.ToString() }
                },
            };

            var service = new PaymentIntentService();

            try
            {
                var ticket = e.Tickets.FirstOrDefault(x => x.Available);

                // if there's no tickets left then throw exception
                if (ticket == null)
                {
                    throw new Exception("Out of tickets");
                }

                // Sends request to Strip api to create intent
                var intent = service.Create(options);

                e.TicketsLeft = e.Tickets.Count(x => x.Available) - 1;

                ticket.User      = user;
                ticket.Available = false;

                // records transaction using Stripe response
                Transaction transaction = new Transaction()
                {
                    Amount         = intent.Amount,
                    User           = user,
                    Paid           = intent.Status == "succeeded",
                    StripeIntentId = intent.Id,
                    Start          = DateTime.Now,
                    Updated        = DateTime.Now,
                    Status         = Enum.Parse <PaymentStatus>(intent.Status, true),
                    Ticket         = ticket,
                    Event          = e,
                    ClientSecret   = intent.ClientSecret,
                    PromoId        = promo?.Id
                };

                await ApplicationContext.Transactions.AddAsync(transaction);

                await ApplicationContext.SaveChangesAsync();

                // start the intent timout method
                CheckOnIntent(transaction.StripeIntentId, ticket.Id, e.Id);

                return(Mapper.Map <TransactionViewModel>(transaction));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            var shippingPrice = 0m;

            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>()
                                     .GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }


            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Core.Entities.Product>()
                                  .GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }

            var service = new PaymentIntentService();

            PaymentIntent intent;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions
                {
                    Amount             = CalculateTotalItemsCost(basket, shippingPrice),
                    Currency           = "usd",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };

                intent = await service.CreateAsync(options);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = CalculateTotalItemsCost(basket, shippingPrice)
                };
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
Beispiel #6
0
        public async Task <IActionResult> OnPostChargeAsync(string stripeEmail, string stripeToken)
        {
            HttpClient          client = _api.Initial();
            HttpResponseMessage res    = await client.GetAsync("api/CartDetails/" + CartDetailDTO.MemberID + "/GetCartDetailById");

            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                CartDetailDTO = JsonConvert.DeserializeObject <UserCartDetailDTO>(result);
            }

            if (!res.IsSuccessStatusCode || !ModelState.IsValid)
            {
                ViewData["Error"] = ERROR_MSG;
                return(Page());
            }

            try
            {
                decimal totalPrice = CartDetailDTO.TotalPrice;

                var customerOptions = new CustomerCreateOptions
                {
                    Email  = stripeEmail,
                    Source = stripeToken,
                };
                var customer = new CustomerService().Create(customerOptions);

                //var paymentMethodOptions = new PaymentMethodCreateOptions
                //{
                //    Type = "card",
                //    Card = new PaymentMethodCardOptions
                //    {
                //        Number = "4242424242424242",
                //        ExpMonth = 4,
                //        ExpYear = 2022,
                //        Cvc = "314",
                //    },
                //};
                //var paymentMethod = new PaymentMethodService().Create(paymentMethodOptions);

                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount       = (long)(totalPrice * 100),
                    Currency     = "usd",
                    Description  = "Test Payment",
                    Customer     = customer.Id,
                    ReceiptEmail = stripeEmail,
                    Metadata     = new Dictionary <string, string>()
                    {
                        { "Country", CartInputModel.Country },
                        { "State", CartInputModel.State },
                        { "Postcode", CartInputModel.Postcode },
                    },
                    PaymentMethod = "pm_card_visa",
                };

                var           service       = new PaymentIntentService();
                PaymentIntent paymentIntent = service.Create(paymentIntentOptions);

                var order = new EcommerceWebApi.Models.Order();

                order.MemberID   = CartDetailDTO.MemberID;
                order.PaymentID  = paymentIntent.Id;
                order.OrderDate  = DateTime.Now;
                order.Country    = CartInputModel.Country;
                order.State      = CartInputModel.State;
                order.PostCode   = CartInputModel.Postcode;
                order.Status     = "To Ship";
                order.StatusDesc = "Waiting to be shipped out.";
                order.TotalPrice = totalPrice;

                bool stockSufficient            = true;
                List <OrderDetail> orderDetails = new List <OrderDetail>();
                foreach (var item in CartDetailDTO.CartDetails)
                {
                    orderDetails.Add(new OrderDetail
                    {
                        Quantity         = item.Quantity,
                        VariantID        = item.VariantID,
                        ProductName      = item.Variant.Product.ProductName,
                        ProductPrice     = item.Variant.Product.Price,
                        ProductImagePath = item.Variant.Product.ProductImages.FirstOrDefault().Path,
                        VariantType      = item.Variant.Type
                    });

                    HttpResponseMessage variant_res = await client.PutAsync("api/Action/UpdateVariantQuantity/" + item.VariantID + "/" + item.Quantity, new StringContent(
                                                                                JsonConvert.SerializeObject(order, new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }), Encoding.UTF8, MediaTypeNames.Application.Json));

                    if (variant_res.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        var result = variant_res.Content.ReadAsStringAsync().Result;
                        if (result.Equals("Out of stock"))
                        {
                            item.Variant.Stock = 0;
                            stockSufficient    = false;
                            //CartDetailDTO.CartDetails.Remove(item);
                            //CartDetailDTO.TotalPrice = CartDetailDTO.CartDetails.Sum(cd => cd.Quantity * cd.Variant.Product.Price);
                            //ViewData["Error"] = OUT_OF_STOCK_MSG;
                        }
                    }
                }

                if (!stockSufficient)
                {
                    service.Cancel(paymentIntent.Id);
                    return(Page());
                }

                order.OrderDetails = orderDetails;

                HttpResponseMessage insert_res = await client.PostAsync("api/Orders", new StringContent(
                                                                            JsonConvert.SerializeObject(order, new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                }), Encoding.UTF8, MediaTypeNames.Application.Json));

                HttpResponseMessage delete_res = await client.DeleteAsync("api/Action/DeleteCart/" + CartDetailDTO.MemberID);

                if (insert_res.IsSuccessStatusCode && delete_res.IsSuccessStatusCode)
                {
                    paymentIntent = service.Confirm(paymentIntent.Id);
                }

                if (paymentIntent.Status == "succeeded")
                {
                    _logger.LogInformation("Order is successfully made by {user_email} with PaymentID >> {payment_id}", stripeEmail, paymentIntent.Id);
                    return(RedirectToPage("My-purchase"));
                }
                else
                {
                    service.Cancel(paymentIntent.Id);
                }
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex.ToString());
            }

            ViewData["Error"] = ERROR_MSG;
            return(Page());
        }
Beispiel #7
0
        public ActionResult CompleteCheckout(Cart cart, OrderDetails orderDetails)
        {
            StripeConfiguration.ApiKey = StripeKey.SecretKey;

            var customer = new Stripe.Customer
            {
                Name    = orderDetails.CustomerName,
                Email   = orderDetails.Email,
                Address = new Address
                {
                    Line1      = orderDetails.BillingAddressLine1,
                    Line2      = orderDetails.BillingAddressLine2,
                    City       = orderDetails.BillingCity,
                    State      = orderDetails.BillingState,
                    PostalCode = orderDetails.BillingPostalCode,
                    Country    = orderDetails.BillingCountry
                },
                Phone = orderDetails.CustomerPhone
            };

            if (orderDetails.ShippingAddressLine1 == null)
            {
                orderDetails.ShippingAddressLine1 = orderDetails.BillingAddressLine1;
            }
            if (orderDetails.ShippingAddressLine2 == null)
            {
                orderDetails.ShippingAddressLine2 = orderDetails.BillingAddressLine2;
            }
            if (orderDetails.ShippingCity == null)
            {
                orderDetails.ShippingCity = orderDetails.BillingCity;
            }
            if (orderDetails.ShippingState == null)
            {
                orderDetails.ShippingState = orderDetails.BillingState;
            }
            if (orderDetails.ShippingPostalCode == null)
            {
                orderDetails.ShippingPostalCode = orderDetails.BillingPostalCode;
            }
            if (orderDetails.ShippingCountry == null)
            {
                orderDetails.ShippingCountry = orderDetails.BillingCountry;
            }
            if (orderDetails.ShippingName == null)
            {
                orderDetails.ShippingName = orderDetails.CustomerName;
            }
            if (orderDetails.ShippingPhone == null)
            {
                orderDetails.ShippingPhone = orderDetails.CustomerPhone;
            }
            customer.Shipping = new Shipping
            {
                Address = new Address
                {
                    Line1      = orderDetails.BillingAddressLine1,
                    Line2      = orderDetails.BillingAddressLine2,
                    City       = orderDetails.BillingCity,
                    State      = orderDetails.BillingState,
                    PostalCode = orderDetails.BillingPostalCode,
                    Country    = orderDetails.BillingCountry
                },
                Name  = orderDetails.ShippingName,
                Phone = orderDetails.ShippingPhone
            };
            decimal taxRate = 0.0M;

            try
            {
                taxRate = _transactionManager.RetrieveTaxRateBySalesTaxDateAndZipCode(
                    orderDetails.ShippingPostalCode.Substring(0, 5), _transactionManager.RetrieveLatestSalesTaxDateByZipCode(
                        orderDetails.ShippingPostalCode.Substring(0, 5)));
            }
            catch (Exception)
            {
                taxRate = 0.0M;
            }
            orderDetails.TaxRate = taxRate;

            decimal subTotal = 0.0M;
            decimal total    = 0.0M;

            foreach (var line in cart.Lines)
            {
                if (line.Product.Taxable)
                {
                    subTotal += line.Product.Price * line.Amount;
                }
                else
                {
                    total += line.Product.Price * line.Amount;
                }
            }
            decimal tax = subTotal * taxRate;

            total += subTotal + tax;
            var options = new PaymentIntentCreateOptions
            {
                Customer           = customer.Id,
                Amount             = (int)(total * 100), // stripe totals are in pennies
                Currency           = "usd",
                PaymentMethodTypes = new List <string>
                {
                    "card"
                }
            };
            var           service = new PaymentIntentService();
            PaymentIntent intent  = null;

            try
            {
                intent = service.Create(options);
            }
            catch (Exception)
            {
                return(RedirectToAction("Checkout"));
            }
            var ccvm = new CompleteCheckoutViewModel
            {
                Cart         = cart,
                OrderDetails = orderDetails,
                Subtotal     = subTotal,
                TaxAmount    = tax,
                Total        = total
            };

            ViewData["ClientSecret"] = intent.ClientSecret;

            return(View(ccvm));
        }
        public override int ThreeDSecurePayment(Payment payment, Uri postBackURL, string languageCode = "", string languageDialectCode = "")
        {
            int    ret = 10;
            string url = "";

            err = "";

            try
            {
                StripeConfiguration.ApiKey = payment.ProviderPassword;                 // Secret key

                if (postBackURL == null)
                {
                    url = Tools.ConfigValue("SystemURL");
                }
                else
                {
                    url = postBackURL.GetLeftPart(UriPartial.Authority);
                }
                if (!url.EndsWith("/"))
                {
                    url = url + "/";
                }
                d3Form = "";
                ret    = 20;
                url    = url + "RegisterThreeD.aspx?ProviderCode=" + bureauCode
                         + "&TransRef=" + Tools.XMLSafe(payment.MerchantReference);

                ret = 50;
                var paymentMethodOptions = new PaymentMethodCreateOptions
                {
                    Type = "card",
                    Card = new PaymentMethodCardOptions
                    {
                        Number   = payment.CardNumber,
                        ExpMonth = payment.CardExpiryMonth,
                        ExpYear  = payment.CardExpiryYear,
                        Cvc      = payment.CardCVV
                    }
                };
                ret = 60;
                var paymentMethodService = new PaymentMethodService();
                var paymentMethod        = paymentMethodService.Create(paymentMethodOptions);
                err = err + ", paymentMethodId=" + Tools.NullToString(paymentMethod.Id);

                ret = 70;
                var customerOptions = new CustomerCreateOptions
                {
                    Name          = payment.CardName,                     // (payment.FirstName + " " + payment.LastName).Trim(),
                    Email         = payment.EMail,
                    Phone         = payment.PhoneCell,
                    PaymentMethod = paymentMethod.Id
                };
                ret = 80;
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerOptions);
                err = err + ", customerId=" + Tools.NullToString(customer.Id);

//				if ( payment.PaymentDescription.Length < 1 )
//					payment.PaymentDescription = "CareAssist";
//				else if ( payment.PaymentDescription.Length > 22 )
//					payment.PaymentDescription = payment.PaymentDescription.Substring(0,22);

//	Stripe needs a minimum payment of 50 US cents
                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount              = 050,                         // payment.PaymentAmount,
                    Currency            = "usd",                       // payment.CurrencyCode.ToLower(), // Must be "usd" not "USD"
                    StatementDescriptor = payment.PaymentDescriptionLeft(22),
                    Customer            = customer.Id,
                    PaymentMethod       = paymentMethod.Id,
                    Description         = payment.MerchantReference,
                    ConfirmationMethod  = "manual"
                };
                ret = 40;
                var paymentIntentService = new PaymentIntentService();
                var paymentIntent        = paymentIntentService.Create(paymentIntentOptions);
                err = err + ", paymentIntentId=" + Tools.NullToString(paymentIntent.Id);

                ret = 50;
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    PaymentMethod = paymentMethod.Id,
                    ReturnUrl     = url
                };
                ret = 60;
                var paymentConfirm = paymentIntentService.Confirm(paymentIntent.Id, confirmOptions);
                payRef = paymentConfirm.Id;
                err    = err + ", paymentConfirmId=" + Tools.NullToString(payRef);

                ret        = 70;
                strResult  = paymentConfirm.StripeResponse.Content;
                d3Form     = Tools.JSONValue(strResult, "url", "next_action");
                d3Form     = Tools.JSONRaw(d3Form);
                resultMsg  = Tools.JSONValue(strResult, "status");
                ret        = 80;
                resultCode = paymentConfirm.StripeResponse.ToString();
                int k = resultCode.ToUpper().IndexOf(" STATUS=");
                err = err + ", StripeResponse=" + Tools.NullToString(resultCode);
                ret = 90;

                Tools.LogInfo("ThreeDSecurePayment/60", "strResult=" + strResult, 221, this);

                string sql = "exec sp_WP_PaymentRegister3DSecA @ContractCode=" + Tools.DBString(payment.MerchantReference)
                             + ",@ReferenceNumber=" + Tools.DBString(payRef)
                             + ",@Status='77'";                                               // Means payment pending
                if (languageCode.Length > 0)
                {
                    sql = sql + ",@LanguageCode=" + Tools.DBString(languageCode);
                }
                if (languageDialectCode.Length > 0)
                {
                    sql = sql + ",@LanguageDialectCode=" + Tools.DBString(languageDialectCode);
                }
                using (MiscList mList = new MiscList())
                    mList.ExecQuery(sql, 0, "", false, true);

                Tools.LogInfo("ThreeDSecurePayment/80", "PayRef=" + payRef + "; SQL=" + sql + "; " + d3Form, 10, this);
                return(0);
            }
            catch (Exception ex)
            {
                Tools.LogException("ThreeDSecurePayment/99", "Ret=" + ret.ToString(), ex, this);
            }
            return(ret);
        }
Beispiel #9
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            // Needed for Payment intent
            StripeConfiguration.ApiKey = _configuration["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            if (basket == null)
            {
                return(null);
            }

            //Set shipping price to 0
            var shippingPrice = 0m;

            // Dont trust the value in the basket and always get the price from the database
            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>()
                                     .GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

                // When there is a mismatch in the price in the basket vs price in the DB
                // Set it to the price in the DB
                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }

                // Stripe class for payment intent
                var           service = new PaymentIntentService();
                PaymentIntent intent;

                // Check if no payment has been set already. If it is an update to the basket
                // then intent may already be available and the client makes a change after checkout
                if (string.IsNullOrEmpty(basket.PaymentIntentId))
                {
                    _logger.LogDebug("SERVICE ENTRY: Creating new Payment intent Id");
                    var options = new PaymentIntentCreateOptions
                    {
                        // Converting from decimal to long needs multiplication by 100
                        Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100))
                                 + (long)shippingPrice * 100,
                        Currency           = "inr",
                        PaymentMethodTypes = new List <string> {
                            "card"
                        }
                    };
                    // Create the intent on Stripe
                    intent = await service.CreateAsync(options);

                    // Update basket with the payment intent Id and client secret
                    basket.PaymentIntentId = intent.Id;
                    basket.ClientSecret    = intent.ClientSecret;
                }
                // Update the payment intent
                else
                {
                    _logger.LogDebug("SERVICE ENTRY: Updating existing Payment intent Id {PaymentIntentId}", basket.PaymentIntentId);
                    var options = new PaymentIntentUpdateOptions
                    {
                        Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100))
                                 + (long)shippingPrice * 100
                    };

                    await service.UpdateAsync(basket.PaymentIntentId, options);
                }
            }

            //Update the basket with the information from Stripe
            await _basketRepository.CreateOrUpdateBasketAsync(basket);

            return(basket);
        }
Beispiel #10
0
        protected void PlaceOrder_Click(object sender, EventArgs e)
        {
            var totalPrice = int.Parse(hdnTotalPrice.Value) * 100;

            #region Create a Payment Method
            var paymentMethodCreateOptions = new PaymentMethodCreateOptions
            {
                Type = "card",
                Card = new PaymentMethodCardOptions
                {
                    Number   = cardnumber.Value,
                    ExpMonth = long.Parse(expiryMonth.Value),
                    ExpYear  = long.Parse(expiryYear.Value),
                    Cvc      = cvvCode.Value,
                },
            };
            var           paymentMethodService = new PaymentMethodService();
            PaymentMethod paymentMethodResult  = null;
            try
            {
                paymentMethodResult = paymentMethodService.Create(paymentMethodCreateOptions);
            }
            catch (StripeException ex)
            {
                switch (ex.StripeError.Type)
                {
                case "card_error":
                    // Log Error details to your application Database
                    // ex.StripeError.Code, ex.StripeError.Message, ex.StripeError.DocUrl, ex.StripeError.DeclineCode

                    // Show a friendly message to the end user
                    errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " +
                                        "your credit card details are right and you have enough funds in it and try again.";
                    break;

                case "api_connection_error":
                    errorMessage.Text = "We are sorry but we couldn't charge your card. Please try again.";
                    break;

                case "validation_error":
                    errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " +
                                        "your credit card details are right and you have enough funds in it and try again.";
                    break;

                case "api_error":     // 500 errors, very rare
                case "authentication_error":
                case "invalid_request_error":
                case "rate_limit_error":
                default:
                    // Unknown Error Type
                    errorMessage.Text = "We are sorry but we couldn't charge your card due to an issue on our end." +
                                        "Our engineers have been notified. Please wait for 24 hours and retry again. If the issue " +
                                        "isn't resovled still, then please call us on our customer care center at 1 800 123 1234.";
                    break;
                }
                errorMessage.Visible = true;
                return;
            }
            #endregion

            #region Create & Confirm PaymentIntent OR Charge the card
            var paymentIntentCreateOptions = new PaymentIntentCreateOptions
            {
                Amount             = totalPrice,
                Currency           = "sgd",
                PaymentMethodTypes = new List <string> {
                    "card"
                },
                Confirm       = true,
                PaymentMethod = paymentMethodResult.Id
            };
            var           paymentIntentService = new PaymentIntentService();
            PaymentIntent paymentIntentResult;
            try
            {
                paymentIntentResult = paymentIntentService.Create(paymentIntentCreateOptions);
            }
            catch (StripeException ex)
            {
                switch (ex.StripeError.Type)
                {
                case "card_error":
                    // Log Error details to your application Database
                    // ex.StripeError.Code, ex.StripeError.Message, ex.StripeError.DocUrl, ex.StripeError.DeclineCode

                    // Show a friendly message to the end user
                    errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " +
                                        "your credit card details are right and you have enough funds in it and try again.";
                    break;

                case "api_connection_error":
                    errorMessage.Text = "We are sorry but we couldn't charge your card. Please try again.";
                    break;

                case "validation_error":
                    errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " +
                                        "your credit card details are right and you have enough funds in it and try again.";
                    break;

                case "api_error":     // 500 errors, very rare
                case "authentication_error":
                case "invalid_request_error":
                case "rate_limit_error":
                default:
                    // Unknown Error Type
                    errorMessage.Text = "We are sorry but we couldn't charge your card due to an issue on our end." +
                                        "Our engineers have been notified. Please wait for 24 hours and retry again. If the issue " +
                                        "isn't resovled still, then please call us on our customer care center at 1 800 123 1234.";
                    break;
                }
                errorMessage.Visible = true;
                return;
            }
            #endregion

            #region Show success Message
            successMessage.Text = string.Format("<h4>Congratulations! We have successfully received your order.</h4>" +
                                                "<br/>Please save the Payment Intent ID {1} and the Charge ID {2} safely in case of a dispute.",
                                                int.Parse(hdnTotalPrice.Value), paymentIntentResult.Id, paymentIntentResult.Charges.FirstOrDefault().Id);
            successMessage.Visible = true;
            #endregion
        }
Beispiel #11
0
        public PaymentIntentCreateOptions StripePaymentIntentCreateOptions(IStripeCharge stripeChargeParameters, string apiKey, ref List <TransferCreateOptions> transferOptions)
        {
            IEnumerable <StripeConnectMaster> stripeConnectMaster = GetMasterData(stripeChargeParameters.TransactionId);
            var chargeOptions = new PaymentIntentCreateOptions();

            if (stripeChargeParameters.ChannelId != Channels.Feel)
            {
                long applicationFeeAmount = 0;
                if (stripeConnectMaster != null && stripeConnectMaster.Any())
                {
                    applicationFeeAmount = (long)((stripeConnectMaster.FirstOrDefault().ServiceCharge + stripeConnectMaster.FirstOrDefault().DeliveryCharges + stripeConnectMaster.FirstOrDefault().ConvenienceCharges) * 100);
                }
                if (stripeConnectMaster != null && stripeConnectMaster.Any() && stripeConnectMaster.FirstOrDefault().IsEnabled&& applicationFeeAmount != 0)
                {
                    chargeOptions = new PaymentIntentCreateOptions
                    {
                        PaymentMethodId     = stripeChargeParameters.Token,
                        Amount              = Convert.ToInt32(Convert.ToDouble(stripeChargeParameters.Amount) * 100),
                        Currency            = stripeChargeParameters.Currency.ToString().ToLower(),
                        Description         = "Transaction charge for " + stripeChargeParameters.TransactionId.ToString(),
                        Confirm             = true,
                        ConfirmationMethod  = "manual",
                        StatementDescriptor = stripeChargeParameters.ChannelId == Channels.Feel ? "FEELAPLACE.COM" : "ZOONGA.COM"
                    };
                    if (applicationFeeAmount > 0)
                    {
                        var transferOption = new TransferCreateOptions
                        {
                            Amount      = (long)(applicationFeeAmount),
                            Currency    = stripeChargeParameters.Currency,
                            Destination = stripeConnectMaster.FirstOrDefault().StripeConnectAccountID,
                            ExtraParams = new Dictionary <string, object>()
                            {
                                { "EndDateTime", stripeConnectMaster.FirstOrDefault().EndDateTime.AddDays(stripeConnectMaster.FirstOrDefault().PayoutDaysOffset) }, { "CreatedBy", stripeConnectMaster.FirstOrDefault().CreatedBy }
                            }
                        };
                        transferOptions.Add(transferOption);
                    }
                    return(chargeOptions);
                }
            }

            if (stripeChargeParameters.ChannelId == Channels.Feel)
            {
                int chargeCount = 0;
                if (stripeConnectMaster.Count() > 0 && stripeConnectMaster.Where(x => x.IsEnabled == true).Any())
                {
                    chargeOptions = new PaymentIntentCreateOptions
                    {
                        PaymentMethodId     = stripeChargeParameters.Token,
                        Amount              = Convert.ToInt32(Convert.ToDouble(stripeChargeParameters.Amount) * 100),
                        Currency            = stripeChargeParameters.Currency.ToString().ToLower(),
                        Description         = "Transaction charge for " + stripeChargeParameters.TransactionId.ToString(),
                        Confirm             = true,
                        ConfirmationMethod  = "manual",
                        StatementDescriptor = stripeChargeParameters.ChannelId == Channels.Feel ? "FEELAPLACE.COM" : "ZOONGA.COM"
                    };

                    foreach (StripeConnectMaster stripeConnectMasterRow in stripeConnectMaster)
                    {
                        if (stripeConnectMasterRow.IsEnabled)
                        {
                            // Create a Transfer to the connected account for releasing ticket amount (minus our commission):
                            decimal amount = stripeConnectMasterRow.TotalTickets * stripeConnectMasterRow.PricePerTicket * 100;
                            if (stripeConnectMasterRow.ExtraCommisionFlat > 0)
                            {
                                amount = amount - (stripeConnectMasterRow.ExtraCommisionFlat * stripeConnectMasterRow.TotalTickets * 100);
                            }
                            else if (stripeConnectMasterRow.ExtraCommisionPercentage > 0)
                            {
                                amount = amount - ((amount * stripeConnectMasterRow.ExtraCommisionPercentage) / 100);
                            }
                            chargeCount++;
                            if (amount > 0)
                            {
                                var transferOption = new TransferCreateOptions
                                {
                                    Amount      = (long)(amount),
                                    Currency    = stripeChargeParameters.Currency,
                                    Destination = stripeConnectMasterRow.StripeConnectAccountID,
                                    ExtraParams = new Dictionary <string, object>()
                                    {
                                        { "EndDateTime", stripeConnectMasterRow.EndDateTime.AddDays(stripeConnectMasterRow.PayoutDaysOffset) }, { "CreatedBy", stripeConnectMasterRow.CreatedBy }
                                    }
                                };
                                transferOptions.Add(transferOption);
                            }

                            // Create a Transfer to the connected account for chargeBack amount
                            amount = 0;
                            if (stripeConnectMasterRow.ChargebackHoldFlat > 0)
                            {
                                amount = stripeConnectMasterRow.ChargebackHoldFlat;
                            }
                            else if (stripeConnectMasterRow.ChargebackHoldPercentage > 0)
                            {
                                amount = stripeConnectMasterRow.TotalTickets * stripeConnectMasterRow.PricePerTicket * 100;
                                amount = (amount * stripeConnectMasterRow.ExtraCommisionPercentage) / 100;
                            }

                            if (amount > 0)
                            {
                                var transferOption = new TransferCreateOptions
                                {
                                    Amount      = (long)(amount),
                                    Currency    = stripeChargeParameters.Currency,
                                    Destination = stripeConnectMasterRow.StripeConnectAccountID,
                                    ExtraParams = new Dictionary <string, object>()
                                    {
                                        { "EndDateTime", stripeConnectMasterRow.EndDateTime.AddDays(stripeConnectMasterRow.ChargebackDaysOffset) }, { "CreatedBy", stripeConnectMasterRow.CreatedBy }
                                    }
                                };
                                transferOptions.Add(transferOption);
                            }
                        }
                    }
                    if (chargeCount > 0)
                    {
                        return(chargeOptions);
                    }
                }
            }

            chargeOptions = new PaymentIntentCreateOptions
            {
                PaymentMethodId     = stripeChargeParameters.Token,
                Amount              = Convert.ToInt32(Convert.ToDouble(stripeChargeParameters.Amount) * 100),
                Currency            = stripeChargeParameters.Currency.ToString().ToLower(),
                Description         = "Transaction charge for " + stripeChargeParameters.TransactionId.ToString(),
                Confirm             = true,
                ConfirmationMethod  = "manual",
                StatementDescriptor = stripeChargeParameters.ChannelId == Channels.Feel ? "FEELAPLACE.COM" : "ZOONGA.COM"
            };

            return(chargeOptions);
        }
Beispiel #12
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            var shippingPrice = 0m;

            if (basket == null)
            {
                return(null);                                                   // we then handle this inside the PaymentsController and inform user of bad request
            }
            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }

            var service = new PaymentIntentService();                              // new class comes from STRIPE

            PaymentIntent intent;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions
                {
                    Amount             = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    Currency           = "usd",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };

                intent = await service.CreateAsync(options);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100
                };

                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            // get stripe secret key
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            if (basket == null)
            {
                return(null);
            }

            var shippingPrice = 0m;

            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeleveryMethod>()
                                     .GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }

            var service = new PaymentIntentService();

            PaymentIntent intent;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions
                {
                    Amount             = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    Currency           = "usd",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };
                intent = await service.CreateAsync(options);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                // this else block will be used and takes care of the possibility that the client's away the change the basket after going
                // through the checkout and then backing out after we have already created a payment intent.
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100
                };
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
Beispiel #14
0
        //3-methods:
        //a-CreateOrUpdatePaymentIntent:

        /*
         * this method receives the basket Id stored in the browser localstorage,
         * then create the PaymentIntent with the third party payment processor stripe,
         * then returns the basket again. why to return the basket ?
         * after creating the payment intent, this method will assign values to the below properties in CustomerBasket model:
         *
         * public int? DeliveryMethodId {get; set;}
         * public string ClientSecret {get; set;}
         * public string PaymentIntentId {get; set;}
         *
         * so that we need to return the basket with its new valuse so we can read them anywhere else.
         */
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            //1)
            //frommy account in stripe.com, I brought the Publishibale key and the secret key,
            //then stored them in appSettings.json (since it is a file which is not uploaded publicily to github),
            //then let use read that key and store it in StripeConfiguration.ApiKey (which comes from the Stripe library above).
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];



            //2)
            //now bring the basket which has the Id passed to thid method above.
            //remember that basket is stored in redis, and there is no relation between the logged in user's email/Id and the basket,
            //since the basket can be added anonymously without the user being logged in !
            //and the basket is the same per browser for any user ! and is loaded once the website is launched since the basketId is stored in the browser localstorage.
            var basket = await _basketRepository.GetBasketAsync(basketId);

            //2-a)
            //if basket is null for any reason or mistake (if the basket is null, the user will not have the ability to go to checkout and checkout-payment.component.ts, but it is better to check that)
            if (basket == null)
            {
                return(null);
            }



            //3)
            //let us determine the shippingPrice we want to take from the customer for a payment:
            //Initialize it as zero at first:
            var shippingPrice = 0m; //m means decimal

            //check if the basket has the DeliveryMethodId with a value,
            //(which means that the user proceeded to checkout, and in the delivery tab, the user has chosen a DeliveryMethod which its Id got stored in the basket DeliveryMethodId property)
            //(if it is null, that means the user did not proceed to checkout yet, and we will keep shippingprice to 0 as above)
            //indeed, we will not reach this method CreateOrUpdatePaymentIntent unless the user is in the checkout page, in Payment tab,
            //which means he was forced to choose to a delivery method. but it is good to validate that here again.
            if (basket.DeliveryMethodId.HasValue)
            {
                //bring the delivery method from the DeliveryMethods table acording to the delivery method Id we have:
                var dm = await _dmRepo.GetByIdAsync((int)basket.DeliveryMethodId); //DeliveryMethodId is identified as int? in Customerbasket model, and GetByIdAsync receives an int, so cast the DeliveryMethodId as int using (int)

                //now read the delivery price from dm, and assign it to the shippingprice:
                shippingPrice = dm.Price;

                //we could have stored the delivery price in the basket (CustomerBasket model) directly, but it is better not to trust what is really stored in a basket
                //so store the DeliveryMethodId only, and bring its data from the table.
            }



            //4)
            //now, let us say we do not trust the product price as it is stored in redis, becuase it is easy for some fraudesters to update it from the frontend,
            //so let us check the product price as in item in the basket if equals the price in the Products DB table,
            //and if not, let us re-update the price in the basket:
            foreach (var item in basket.Items) //Items is where we store the products in CustomerBasket model
            {
                //bring the product info from the Products table on the DB according to its Id stored in the basket:
                var productItem = await _productRepo.GetByIdAsync(item.Id);

                //now compare the product's price in the basket with the one in the DB:
                if (item.Price != productItem.Price)
                {
                    //if we reached this level here, that means the user tried to make a fraud to update the product price somehow,
                    //so reset it in the basket to be as the price in the DB:
                    item.Price = productItem.Price;
                }
            }



            //5)
            //now create the Payment Intent which will be sent to the "Stripe" payment processor, which will process the intent and
            //returns a clientSecret to be used when submitting an order.
            //please remember the picture 257-3 in course section 21

            /*
             * first validate if the PaymentId in the basket (remembers the BasketMoel) is null,
             * which means that the user did not try to pay before this moment, so we are creating a new Intent.
             *
             * if it is null, so that for the PaymentId stored in the basket, the user is trying to update his basket, after the Intent has been created
             * then go to payment back again.
             */
            //a-instantiate an instance of PaymentIntentService (from the stripe library) which is ussed to send the Intent:
            var service = new PaymentIntentService();
            //b-create a property of type PaymentIntent to store the customer in it:
            PaymentIntent intent;

            //c-to what account in stripe we should consider the intent belongs to ?
            //to our account, and remember that above we set the StripeConfiguration.ApiKey to our key.
            //d-check if PymentId is empty or not as we said above:
            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                //if empty, that means we are creating an Intent for the first time,
                //so create the options we want to fill in the Intent to be sent:
                //Intent options are identified in the class PaymentIntentCreateOptions which comes from the stripe library:
                var options = new PaymentIntentCreateOptions
                {
                    //The amount of the application (order) fee (if any) that will be applied to the payment,
                    //and transferred to the application owner’s Stripe account.
                    //which is here the sum of the basket products price*Quantity for each. plus the shippingPrice we had above.
                    //stripe does not accept decimal numbers, so cast the result in (long) format.
                    //to convert from decimal to long, we must get rid of the 2 decimal digits after the comma, so multiply with *100
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    //Three-letter ISO currency code, in lowercase. Must be a supported currency in stripe:
                    Currency = "usd",
                    //Payment-method-specific configuration for this PaymentIntent.
                    //we may have multiple methods as identified in stripe, so store all the methods in a list.
                    PaymentMethodTypes = new List <string> {
                        "card",
                    },
                };
                //the PaymentIntentService has a method called CreateAsync which communicates with stripe over the internet,
                //and create the Intent:
                intent = await service.CreateAsync(options);

                //CreateAsync method returns 2 values after the intent is created,
                //an Id and ClientSecret to be used when the user will submit the order after the intent is created.
                //please remember the picture 257-3 in course section 21
                //so store these 2 parameters in the PamentIntentId and ClientSecret in the basket (remember the Customerbasket model) so we can send read them from the basket from anywhere else.
                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            //now discuss the case the paymentId in the basket is not empty as we explained above:
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    //the user is just updating his basket, so just update the amount again:
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100
                };
                //and use the UpdateAsync method from the PaymentIntentService:
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            //now in the basket we have the DeliveryMethodId and PaymentId and the ClientSecret,
            //so store them officially in redis:
            await _basketRepository.UpdateBasketAsync(basket);

            //and return the updated basket so we can use read it somehwere else:
            return(basket);
        }
Beispiel #15
0
        protected override void BuildBody(StringBuilder page, PaymentRequest paymentRequest)
        {
            // create client
            string apiKey    = paymentRequest.PaymentMethod.DynamicProperty <string>().PublicKey;
            string apiSecret = paymentRequest.PaymentMethod.DynamicProperty <string>().SecretKey;
            string acceptUrl = paymentRequest.PaymentMethod.DynamicProperty <string>().AcceptUrl;

            var client = new StripeClient(apiSecret);
            var paymentIntentService = new PaymentIntentService(client);

            var createIntent = new PaymentIntentCreateOptions()
            {
                Currency = paymentRequest.Amount.CurrencyIsoCode,
                Amount   = Convert.ToInt64(paymentRequest.Amount.Value * 100)
            };

            var    paymentIntent       = paymentIntentService.Create(createIntent);
            string paymentFormTemplate = paymentRequest.PaymentMethod.DynamicProperty <string>().PaymentFormTemplate;
            var    allLines            = File.ReadAllLines(HttpContext.Current.Server.MapPath(paymentFormTemplate));

            foreach (var line in allLines)
            {
                page.AppendLine(line);
            }

            var billingDetails = new ChargeBillingDetails()
            {
                Name    = $"{paymentRequest.PurchaseOrder.BillingAddress.FirstName} {paymentRequest.PurchaseOrder.BillingAddress.LastName}",
                Address = new s.Address()
                {
                    Line1      = paymentRequest.PurchaseOrder.BillingAddress.Line1,
                    Line2      = paymentRequest.PurchaseOrder.BillingAddress.Line2,
                    City       = paymentRequest.PurchaseOrder.BillingAddress.City,
                    State      = paymentRequest.PurchaseOrder.BillingAddress.State,
                    PostalCode = paymentRequest.PurchaseOrder.BillingAddress.PostalCode,
                    Country    = paymentRequest.PurchaseOrder.BillingAddress.Country.TwoLetterISORegionName
                }
            };

            page.Replace("##STRIPE:PUBLICKEY##", apiKey);
            page.Replace("##STRIPE:PAYMENTINTENT##", JsonConvert.SerializeObject(paymentIntent));
            page.Replace("##STRIPE:BILLINGDETAILS##", JsonConvert.SerializeObject(billingDetails));
            page.Replace("##PROCESSURL##", $"/{paymentRequest.PaymentMethod.PaymentMethodId}/{paymentRequest.Payment["paymentGuid"]}/PaymentProcessor.axd");
            page.Replace("##ACCEPTURL##", acceptUrl);

            PaymentProperty paymentIntentProp;

            if (paymentRequest.Payment.PaymentProperties.Any(p => p.Key == PaymentIntentKey))
            {
                var allProps = paymentRequest.Payment.PaymentProperties.Where(p => p.Key == PaymentIntentKey).ToList();
                foreach (var prop in allProps)
                {
                    paymentRequest.Payment.PaymentProperties.Remove(prop);
                }
                paymentRequest.Payment.Save();
            }

            paymentIntentProp = new PaymentProperty()
            {
                Guid  = Guid.NewGuid(),
                Key   = PaymentIntentKey,
                Value = paymentIntent.Id
            };
            paymentRequest.Payment.AddPaymentProperty(paymentIntentProp);
            paymentRequest.Payment.Save();
        }
        public override int TokenPayment(Payment payment)
        {
            if (!EnabledFor3d(payment.TransactionType))
            {
                return(590);
            }

            int ret = 610;

            payRef     = "";
            strResult  = "";
            err        = "";
            resultMsg  = "Fail";
            resultCode = "981";

            Tools.LogInfo("TokenPayment/10", "Merchant Ref=" + payment.MerchantReference, 10, this);

            try
            {
                ret = 620;
                StripeConfiguration.ApiKey = payment.ProviderPassword;                 // Secret key

                ret = 624;
                err = err + ", customerId=" + Tools.NullToString(payment.CustomerID)
                      + ", paymentMethodId=" + Tools.NullToString(payment.PaymentMethodID)
                      + ", tokenId=" + Tools.NullToString(payment.CardToken);
                ret = 630;
                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount              = payment.PaymentAmount,
                    Currency            = payment.CurrencyCode.ToLower(),                     // Must be "usd" not "USD"
                    StatementDescriptor = payment.PaymentDescriptionLeft(22),
                    Customer            = payment.CustomerID,
                    PaymentMethod       = payment.PaymentMethodID,
                    Description         = payment.MerchantReference,
                    ConfirmationMethod  = "manual"
//					SetupFutureUsage    = "off_session",
//					Confirm             = true,
//					PaymentMethodData   = new PaymentIntentPaymentMethodDataOptions
//					{
//						Type = "card"
//					},
                };

//	Create a separate mandate
//				string mandateId = "";
//				if ( payment.MandateDateTime > Constants.DateNull && payment.MandateIPAddress.Length > 2 )
//				{
//					ret         = 640;
//					var mandate = new Mandate
//					{
//						CustomerAcceptance = new MandateCustomerAcceptance
//						{
//							AcceptedAt = payment.MandateDateTime,
//							Online     = new MandateCustomerAcceptanceOnline
//							{
//								IpAddress = payment.MandateIPAddress,
//								UserAgent = payment.MandateBrowser
//							}
//						}
//					};
//					mandateId = mandate.Id;
//					err       = err + ", mandateId="+Tools.NullToString(mandateId);
//				}
//				else
//					err       = err + ", No mandate";

                ret = 690;
                var paymentIntentService = new PaymentIntentService();
                var paymentIntent        = paymentIntentService.Create(paymentIntentOptions);
                err = err + ", paymentIntentId=" + Tools.NullToString(paymentIntent.Id);

                ret = 700;
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    PaymentMethod = payment.PaymentMethodID,
                    OffSession    = true
//					Mandate       = mandateId
//					MandateData   = new PaymentIntentMandateDataOptions
//					{
//						CustomerAcceptance = new PaymentIntentMandateDataCustomerAcceptanceOptions
//						{
//							AcceptedAt = payment.MandateDateTime,
//							Online     = new PaymentIntentMandateDataCustomerAcceptanceOnlineOptions
//							{
//								IpAddress = payment.MandateIPAddress,
//								UserAgent = payment.MandateBrowser
//							}
//						}
//					}
                };

                if (payment.MandateDateTime > Constants.DateNull && payment.MandateIPAddress.Length > 2)
                {
                    ret = 710;
                    confirmOptions.MandateData = new PaymentIntentMandateDataOptions
                    {
                        CustomerAcceptance = new PaymentIntentMandateDataCustomerAcceptanceOptions
                        {
                            AcceptedAt = payment.MandateDateTime,
                            Type       = "online",
                            Online     = new PaymentIntentMandateDataCustomerAcceptanceOnlineOptions
                            {
                                IpAddress = payment.MandateIPAddress,
                                UserAgent = payment.MandateBrowser
                            }
                        }
                    };
                }

                ret = 720;
                var paymentConfirm = paymentIntentService.Confirm(paymentIntent.Id, confirmOptions);
                payRef = paymentConfirm.Id;
                err    = err + ", paymentConfirmId=" + Tools.NullToString(payRef);

                ret        = 730;
                strResult  = paymentConfirm.StripeResponse.Content;
                resultMsg  = Tools.JSONValue(strResult, "status");
                resultCode = paymentConfirm.StripeResponse.ToString();
                int k = resultCode.ToUpper().IndexOf(" STATUS=");
                ret = 740;
                err = err + ", StripeResponse=" + Tools.NullToString(resultCode);

                if (k > 0)
                {
                    ret        = 750;
                    resultCode = resultCode.Substring(k + 8).Trim();
                    k          = resultCode.IndexOf(" ");
                    if (k > 0)
                    {
                        resultCode = resultCode.Substring(0, k);
                    }
                }
                else
                {
                    resultCode = "989";
                }

                ret = 760;
                err = err + ", strResult=" + Tools.NullToString(strResult)
                      + ", resultCode=" + Tools.NullToString(resultCode);
//				mandate              = null;
                paymentIntentService = null;
                paymentIntent        = null;
                confirmOptions       = null;
                paymentConfirm       = null;

                if (!resultCode.StartsWith("2") || payRef.Length < 1)
                {
                    resultCode = (resultMsg.Length > 0 ? resultMsg : "Fail");
                    //	resultCode = "Fail/" + resultCode + ( resultMsg.Length > 0 ? " : " + resultMsg : "" );
                    Tools.LogInfo("TokenPayment/197", "Ret=" + ret.ToString() + err, 231, this);
                }
                else if (resultMsg.ToUpper().StartsWith("SUCCE") || resultMsg.Length == 0)
                {
                    ret        = 0;
                    resultCode = "Success";
                    //	resultCode = "Success/" + resultCode;
                    //	Tools.LogInfo ("TokenPayment/189","Ret=0" + err,255,this);
                }
                else
                {
                    resultCode = resultMsg;
                }
            }
            catch (Exception ex)
            {
                resultCode = ex.Message;
                //	resultCode = "Fail/" + ret.ToString() + " : " + ex.Message + ( resultMsg.Length > 0 ? " (" + resultMsg + ")" : "" );
                err = "Ret=" + ret.ToString() + err;
                Tools.LogInfo("TokenPayment/198", err, 231, this);
                Tools.LogException("TokenPayment/199", err, ex, this);
            }
            return(ret);
        }
Beispiel #17
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _configuration["StripeSettings:Secretkey"];

            var basket = await _basketRepo.GetBasketAsync(basketId);

            var shippingPrice = 0m;

            if (basket == null)
            {
                return(null);
            }

            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Core.Entities.Product>().GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }

            var service = new PaymentIntentService();

            PaymentIntent intent;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                var intentOptions = new PaymentIntentCreateOptions
                {
                    //stripe does not accept decimal so converting into long and also mutiplying by 100
                    Amount             = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    Currency           = "inr",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    },
                    Shipping = new ChargeShippingOptions
                    {
                        Name    = "Jenny Rosen",
                        Address = new AddressOptions
                        {
                            Line1      = "510 Townsend St",
                            PostalCode = "98140",
                            City       = "San Francisco",
                            State      = "CA",
                            Country    = "US",
                        },
                    },
                    Description = "Software development services"
                };
                intent = await service.CreateAsync(intentOptions);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    //stripe does not accept decimal so converting into long and also mutiplying by 100
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                };
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            await _basketRepo.UpdateBasketAsync(basket);

            return(basket);
        }
Beispiel #18
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            if (basket == null)
            {
                return(null);
            }

            var shippingPrice = 0m;

            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>()
                                     .GetByIdAsync((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>()
                                  .GetByIdAsync(item.Id);

                if (item.Price != productItem.Price)
                {
                    item.Price = productItem.Price;
                }
            }

            var           service = new PaymentIntentService();
            PaymentIntent intent;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions
                {
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) +
                             (long)shippingPrice * 100,
                    Currency           = "usd",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };
                intent = await service.CreateAsync(options);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            // cas ou le client modifie le panier aprés avoir lancé le payment
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) +
                             (long)shippingPrice * 100,
                };
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
Beispiel #19
0
        public async Task <IActionResult> Charge([FromBody] PaymentRequest paymentRequest)
        {
            try
            {
                var customers = new CustomerService();
                var Charges   = new ChargeService();

                var Checkcustomer = await _paymentService.GetCustomerPaymentId(paymentRequest.UserId);

                var customer   = new Customer();
                var CustomerId = "";

                if (Checkcustomer == null)
                {
                    customer = customers.Create(new CustomerCreateOptions
                    {
                        Email = paymentRequest.CustomerEmail,
                        Name  = paymentRequest.CustomerName,
                        Phone = paymentRequest.CustomerPhone,
                    });

                    CustomerId = customer.Id;
                }
                else
                {
                    CustomerId = Checkcustomer.CustomerPaymentId;
                }

                var options1 = new PaymentMethodCreateOptions
                {
                    Type = "card",
                    Card = new PaymentMethodCardCreateOptions
                    {
                        Number   = paymentRequest.CardNumber,
                        ExpMonth = paymentRequest.ExpMonth,
                        ExpYear  = paymentRequest.ExpYear,
                        Cvc      = paymentRequest.Cvc
                    },
                };

                var service1 = new PaymentMethodService();
                service1.Create(options1);


                var options = new PaymentIntentCreateOptions
                {
                    Amount             = paymentRequest.Amount,
                    Currency           = "USD",
                    Customer           = CustomerId,
                    PaymentMethod      = paymentRequest.PaymentMethod,
                    Confirm            = true,
                    PaymentMethodTypes = new List <string> {
                        "card"
                    },
                };

                var service = new PaymentIntentService();
                var intent  = service.Create(options);

                if (intent.Status == "succeeded")
                {
                    var PaymentTrans = new PaymentTransaction
                    {
                        UserId            = paymentRequest.UserId,
                        CustomerPaymentId = CustomerId
                    };

                    await Create(PaymentTrans);

                    return(Ok(new
                    {
                        status = Ok().StatusCode,
                        message = "Payment Successfully"
                    }));
                }
                return(BadRequest(new
                {
                    status = BadRequest().StatusCode,
                    message = "Internal server error"
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new
                {
                    status = BadRequest().StatusCode,
                    message = ex.Message
                }));
            }
        }