using Core.Entities; using Core.Entities.OrderAggregate; using Core.Interfaces; using Microsoft.Extensions.Configuration; using Stripe; using Product = Core.Entities.Product; namespace Infrastructure.Services { public class PaymentService : IPaymentService { private readonly IBasketRepository _basketRepository; private readonly IUnitOfWork _unitOfWork; private readonly IConfiguration _config; public PaymentService(IBasketRepository basketRepository, IUnitOfWork unitOfWork, IConfiguration config) { _config = config; _unitOfWork = unitOfWork; _basketRepository = basketRepository; } public async Task 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().GetByIdAsync((int)basket.DeliveryMethodId); shippingPrice = deliveryMethod.Price; } foreach (var item in basket.Items) { var productItem = await _unitOfWork.Repository().GetByIdAsync(item.Id); if(item.Price != productItem.Price){ item.Price = productItem.Price; } } var service = new PaymentIntentService(); PaymentIntent intent; if(string.IsNullOrEmpty(basket.PaymentItentId)) { var options = new PaymentIntentCreateOptions { Amount = (long) basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long) shippingPrice * 100, Currency = "usd", PaymentMethodTypes = new List{"card"} }; intent = await service.CreateAsync(options); basket.PaymentItentId = 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.PaymentItentId, options); } await _basketRepository.UpdateBasketAsync(basket); return basket; } } }