Esempio n. 1
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 <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             = (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);
        }
Esempio n. 2
0
        private async Task ProcessExistingPaymentIntent(CustomerBasket basket, decimal shippingPrice)
        {
            var service = new PaymentIntentService();
            var options = new PaymentIntentUpdateOptions
            {
                Amount = GetLongBasketAmount(basket, shippingPrice)
            };

            await service.UpdateAsync(basket.PaymentIntentId, options);
        }
Esempio n. 3
0
        public async Task <CustomerBasket> CreateOrUpdatePayementIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];
            var basket = await _bsktRepo.GetBasketAsync(basketId);

            if (basket == null)
            {
                return(null);
            }
            var shippingCharge = 0m;

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

                if (deliveryMethod != null)
                {
                    shippingCharge = deliveryMethod.Price;
                }
            }
            foreach (var item in basket.Items)
            {
                var product = await _uow.Repository <Core.Entities.Product>().GetByIdAsync(item.Id);

                item.Price = product.Price;
            }
            var paymentIntentService = new PaymentIntentService();

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

                basket.ClientSecret    = payment.ClientSecret;
                basket.PaymentIntentId = payment.Id;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)((basket.Items.Sum(x => x.Price * x.Quantity) + shippingCharge)) * 100
                };
                await paymentIntentService.UpdateAsync(basket.PaymentIntentId, options);
            }
            await _bsktRepo.CreateOrUpdateBasketAsync(basket);

            return(basket);
        }
Esempio n. 4
0
        /// <summary>
        /// Add receipt email to an existing intent
        /// </summary>
        /// <param name="paymentIntentId"></param>
        /// <param name="receiptEmail"></param>
        /// <returns></returns>
        private async Task <bool> AddIntentReceiptEmail(string paymentIntentId, MailAddress receiptEmail)
        {
            var service = new PaymentIntentService();
            var options = new PaymentIntentUpdateOptions()
            {
                ReceiptEmail = receiptEmail.Address
            };
            var res = await service.UpdateAsync(paymentIntentId, options, GetRequestOptions());

            return(true);
        }
Esempio n. 5
0
        public async Task <CustomerCart> CreateOrUpdatePaymentIntent(string customerId)
        {
            StripeConfiguration.ApiKey = SecretKey;// _config["StripeSettings:SecretKey"];

            var basket = await customerService.GetCartDetailsForCustomer(customerId);

            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;
            }

            var service = new PaymentIntentService();

            PaymentIntent intent;

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

                basket.paymentIntentId = intent.Id;
                basket.client_secret   = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)basket.cartItems.Sum(i => i.qty * (i.total_payable * 100)) + (long)shippingPrice * 100,
                };
                await service.UpdateAsync(basket.paymentIntentId, options);
            }

            await customerService.UpdateCart(basket);

            return(basket);
        }
Esempio n. 6
0
        public async Task <CustomerCart> CreateOrUpdatePaymentIntent(string basketId)
        {
            try
            {
                StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];
                CustomerCart basket = await _basketRepository.GetByIdAsync(basketId);

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

                var shippingPrice = 0m;

                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
                {
                    var options = new PaymentIntentUpdateOptions
                    {
                        Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100,
                    };

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

                _basketRepository.Update(basket);
                return(basket);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 7
0
        public PaymentIntentServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new PaymentIntentService(this.StripeClient);

            this.cancelOptions = new PaymentIntentCancelOptions
            {
            };

            this.captureOptions = new PaymentIntentCaptureOptions
            {
                AmountToCapture = 123,
            };

            this.confirmOptions = new PaymentIntentConfirmOptions
            {
                ReceiptEmail = "*****@*****.**",
            };

            this.createOptions = new PaymentIntentCreateOptions
            {
                Amount             = 1000,
                Currency           = "usd",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                TransferData = new PaymentIntentTransferDataOptions
                {
                    Amount      = 100,
                    Destination = "acct_123",
                },
            };

            this.listOptions = new PaymentIntentListOptions
            {
                Limit = 1,
            };

            this.updateOptions = new PaymentIntentUpdateOptions
            {
                Metadata = new Dictionary <string, string>
                {
                    { "key", "value" },
                },
            };
        }
Esempio n. 8
0
        public PaymentIntentServiceTest(MockHttpClientFixture mockHttpClientFixture)
            : base(mockHttpClientFixture)
        {
            this.service = new PaymentIntentService();

            this.cancelOptions = new PaymentIntentCancelOptions
            {
            };

            this.captureOptions = new PaymentIntentCaptureOptions
            {
                AmountToCapture = 123,
            };

            this.confirmOptions = new PaymentIntentConfirmOptions
            {
                SaveSourceToCustomer = true,
            };

            this.createOptions = new PaymentIntentCreateOptions
            {
                AllowedSourceTypes = new List <string>
                {
                    "card",
                },
                Amount       = 1000,
                Currency     = "usd",
                TransferData = new PaymentIntentTransferDataOptions
                {
                    Amount      = 100,
                    Destination = "acct_123",
                }
            };

            this.listOptions = new PaymentIntentListOptions
            {
                Limit = 1,
            };

            this.updateOptions = new PaymentIntentUpdateOptions
            {
                Metadata = new Dictionary <string, string>
                {
                    { "key", "value" },
                },
            };
        }
Esempio n. 9
0
        public async Task <PendingBooking> AddPaymentIntentToPendingBooking(PendingBooking pendingBooking, decimal amtForStripe)
        {
            StripeConfiguration.ApiKey = _config["Stripe:SecretKey"];

            var paymentIntentService = new PaymentIntentService();

            PaymentIntent intent;

            if (string.IsNullOrEmpty(pendingBooking.StripePaymentIntentId))
            {
                var options = new PaymentIntentCreateOptions
                {
                    Amount             = (long)amtForStripe * 100,
                    Currency           = "gbp",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };

                intent = await paymentIntentService.CreateAsync(options);

                pendingBooking.StripePaymentIntentId = intent.Id;
                pendingBooking.StripeClientSecret    = intent.ClientSecret;
                pendingBooking.StripeAmount          = (int)intent.Amount / 100;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = (long)amtForStripe * 100
                };

                intent = await paymentIntentService.UpdateAsync(pendingBooking.StripePaymentIntentId, options);

                pendingBooking.StripeAmount = (int)intent.Amount / 100;
            }

            // commit amended pendingBookings entity
            await _repo.Commit();

            return(pendingBooking);
        }
Esempio n. 10
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId, string email)
        {
            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 _deliveryRepo.GetDeliveryMethod((int)basket.DeliveryMethodId);

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await _productRepo.GetProductByIdAsync(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           = "eur",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    },
                    Customer      = "cus_J63t1pVjvPzKF8",
                    PaymentMethod = "pm_card_nl",
                    Confirm       = true,
                    ReceiptEmail  = email,
                };

                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);
        }
Esempio n. 11
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(basketId);

            #region 21.271.4 Checking to see if there is a basket to avoid the exeption -> PaymentController
            if (basket == null)
            {
                return(null);
            }

            #endregion

            #region 21.260.2 Rest of the method -> PaymentsController
            //getting the shipping option
            var shippingPrice = 0m;

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

                shippingPrice = deliveryMethod.Price;
            }

            // checking if the prices in basket are accurate
            foreach (var item in basket.Items)
            {
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

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

            // hoking into stripe
            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
            {
                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);

            #endregion
        }
Esempio n. 12
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string id)
        {
            StripeConfiguration.ApiKey = _configuration["StripeSettings:SecretKey"];

            var basket = await _basketRepository.GetBasketAsync(id);

            if (basket == default(CustomerBasket))
            {
                return(default(CustomerBasket));
            }

            var shippingPrice = 0.0m;

            if (basket.DeliveryMethodId.HasValue)
            {
                var deliveryMethodRepository = _unitOfWork.Repository <DeliveryMethod>();

                var deliveryMethod = await deliveryMethodRepository.GetByIdAsync(basket.DeliveryMethodId.Value);

                shippingPrice = deliveryMethod.Price;
            }

            // accurate the 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 = null;

            var calculatedAmount = (long)basket.Items.Sum(x => x.Quantity * (x.Price * 100)) + (long)shippingPrice * 100;

            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                //create option
                var createOptions = new PaymentIntentCreateOptions()
                {
                    Amount             = calculatedAmount,
                    Currency           = "usd",
                    PaymentMethodTypes = new List <string> {
                        "card"
                    }
                };

                intent = await service.CreateAsync(createOptions);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                // update option
                var updateOptions = new PaymentIntentUpdateOptions()
                {
                    Amount = calculatedAmount
                };

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

            await _basketRepository.UpdateAsync(basket);

            return(basket);
        }
Esempio n. 13
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);
        }
Esempio n. 14
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);
        }
Esempio n. 15
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 = (decimal)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"
                    },
                    Description = "Software development services",
                    Shipping    = new ChargeShippingOptions
                    {
                        Name    = "Jenny Rosen",
                        Address = new AddressOptions
                        {
                            Line1      = "510 Townsend St",
                            Line2      = "unr",
                            PostalCode = "98140",
                            City       = "San Francisco",
                            State      = "CA",
                            Country    = "IN",
                        },
                    },
                };
                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 InvoiceInfo GeneratePayNowLink(
            string customerEmail,
            decimal amountToPay,
            string currency,
            string description = "")
        {
            try
            {
                CustomerCreateOptions customerInfo = new CustomerCreateOptions
                {
                    Email = customerEmail,
                    //PaymentMethod = "card",
                };
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerInfo);

                var invoiceItemOption = new InvoiceItemCreateOptions
                {
                    Customer = customer.Id,
                    Amount   = Convert.ToInt32(amountToPay * 100),
                    Currency = currency,
                };
                var invoiceItemService = new InvoiceItemService();
                var invoiceItem        = invoiceItemService.Create(invoiceItemOption);

                var invoiceOptions = new InvoiceCreateOptions
                {
                    Customer         = customer.Id,
                    CollectionMethod = "send_invoice",
                    DaysUntilDue     = 30,
                    Description      = description
                };

                var service = new InvoiceService();
                var invoice = service.Create(invoiceOptions);

                invoice = service.FinalizeInvoice(invoice.Id);

                try
                {
                    var paymentIntentService = new PaymentIntentService();

                    var paymentIntent = paymentIntentService.Get(invoice.PaymentIntentId);
                    var paymentIntentUpdateOptions = new PaymentIntentUpdateOptions
                    {
                        Description = description
                    };
                    paymentIntentService.Update(paymentIntent.Id, paymentIntentUpdateOptions);
                }
                catch (Exception)
                {
                    //continue
                }

                var result = new InvoiceInfo
                {
                    Url = invoice.HostedInvoiceUrl,
                    Id  = invoice.Id
                };
                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
Esempio n. 17
0
        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);
        }
Esempio n. 18
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            //get the stripe secret key from appsettings
            StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"];

            //return the content of the basket from db
            var basket = await _basketRepository.GetBasketAsync(basketId);

            //check to see that we have a basket
            if (basket == null)
            {
                return(null);
            }

            //initialize the shipping cost with 0
            var shippingPrice = 0m;

            //check to see if the current basket structure has set a delivery id
            if (basket.DeliveryMethodId.HasValue)
            {
                //if the delivery method has been set, retrieve the full delivery information
                var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync((int)basket.DeliveryMethodId);

                //set the current shipping price with the price of selected delivery method
                shippingPrice = deliveryMethod.Price;
            }

            //check de items from basket and confirm that the prices stored there are accurate
            foreach (var item in basket.Items)
            {
                //get the product from db
                var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id);

                //check the price from db with what the client had in the basket
                if (item.Price != productItem.Price)
                {
                    //set the basket item price in case for some reason the client does not have the same price for the item
                    item.Price = productItem.Price;
                }
            }

            //initialize the PaymentIntent Service
            var service = new PaymentIntentService();

            //initialize the PaymentIntent Class
            PaymentIntent intent;

            //check to see if the client already made a payment intent
            if (string.IsNullOrEmpty(basket.PaymentIntentId))
            {
                //if not, create a new payment intent
                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);

                //return and set the PaymentIntentId and ClientSecret
                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                //if yes, just update the payment amount
                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 content in db with the new content
            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
Esempio n. 19
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);
        }
Esempio n. 20
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);
        }
        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           = "inr",
                    PaymentMethodTypes = new List <string>()
                    {
                        "card"
                    }
                };
                options.Shipping = new ChargeShippingOptions {
                    Name    = "mrinal jha",
                    Address = new AddressOptions
                    {
                        Line1      = "hindon vihar noida",
                        PostalCode = "201305",
                        City       = "Noida",
                        State      = "UP",
                        Country    = "INDIA",
                    }
                };

                options.Description = "Mrinal soft 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);
        }
Esempio n. 22
0
        public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId)
        {
            StripeConfiguration.ApiKey = config["StripeSettings:SecretKey"];

            var basket = await this.basketRepository.GetBasketAsync(basketId);

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

            var shippingPrice = 0m;

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

                shippingPrice = deliveryMethod.Price;
            }

            foreach (var item in basket.Items)
            {
                var productItem = await this.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)Decimal.Round(shippingPrice * 100, 2),
                    Currency           = "bgn",
                    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)Decimal.Round(shippingPrice * 100, 2)
                };
                await service.UpdateAsync(basket.PaymentIntentId, options);
            }

            // TEST shitty Stripe Long casting !!!
            var     items = new List <dynamic>();
            dynamic thing = new System.Dynamic.ExpandoObject();

            thing.Price    = 345.30;
            thing.Quantity = 1;
            dynamic thing2 = new System.Dynamic.ExpandoObject();

            thing2.Price    = 16.20;
            thing2.Quantity = 1;
            items.Add(thing);
            items.Add(thing2);

            var  exampleShip = 4.69m;
            long sum         = 0;

            foreach (var i in items)
            {
                sum += i.Quantity * (i.Price * 100);
            }
            long shipConverted = (long)Decimal.Round(exampleShip * 100, 2);

            sum += shipConverted;

            await basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
Esempio n. 23
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 _storeRepo.Repository <DeliveryMethod>().GetByIdAsync(basket.DeliveryMethodId.Value);

                shippingPrice = deliveryMethod.Price;
            }

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

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

            var paymentIntentService = new PaymentIntentService();

            long amountAsLong = (long)basket.Items.Sum(x => (x.Price * 100) * x.Quantity) + (long)(shippingPrice * 100);

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

                PaymentIntent intent = await paymentIntentService.CreateAsync(options);

                basket.PaymentIntentId = intent.Id;
                basket.ClientSecret    = intent.ClientSecret;
            }
            else
            {
                var options = new PaymentIntentUpdateOptions
                {
                    Amount = amountAsLong
                };

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

            await _basketRepository.UpdateBasketAsync(basket);

            return(basket);
        }
        public string SendInvoice(
            string customerEmail,
            decimal amountToPay,
            string currency,
            string description = "",
            bool sendInvoice   = true)
        {
            try
            {
                CustomerCreateOptions customerInfo = new CustomerCreateOptions
                {
                    Email = customerEmail,
                    //PaymentMethod = "card",
                };
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerInfo);

                var invoiceItemOption = new InvoiceItemCreateOptions
                {
                    Customer = customer.Id,
                    Amount   = Convert.ToInt32(amountToPay * 100),
                    Currency = currency,
                };
                var invoiceItemService = new InvoiceItemService();
                var invoiceItem        = invoiceItemService.Create(invoiceItemOption);

                var invoiceOptions = new InvoiceCreateOptions
                {
                    Customer         = customer.Id,
                    CollectionMethod = "send_invoice",
                    DaysUntilDue     = 30,
                    Description      = description,
                    AutoAdvance      = true
                };

                var service = new InvoiceService();
                var invoice = service.Create(invoiceOptions);
                invoice = service.FinalizeInvoice(invoice.Id);

                try
                {
                    var paymentIntentService = new PaymentIntentService();

                    var paymentIntent = paymentIntentService.Get(invoice.PaymentIntentId);
                    var paymentIntentUpdateOptions = new PaymentIntentUpdateOptions
                    {
                        Description = description
                    };
                    paymentIntentService.Update(paymentIntent.Id, paymentIntentUpdateOptions);
                }
                catch (Exception)
                {
                    //continue
                }

                if (sendInvoice)
                {
                    invoice = service.SendInvoice(invoice.Id);
                }

                return(invoice.Id);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }