public async Task <PurchaseResponseModel> Purchase(PurchaseModel purchaseModel, User user) { var purchaseResponse = new PurchaseResponseModel { Success = false, Nanrs = 0 }; try { if (purchaseModel.SaveBilling) { CustomersApi customerApi = new CustomersApi(configuration); if (string.IsNullOrWhiteSpace(user.BillingId)) { CreateCustomerRequest createCustomer = new CreateCustomerRequest(Guid.NewGuid().ToString(), Nickname: user.Username, EmailAddress: user.Email, ReferenceId: user.Id.ToString()); var customerResponse = await customerApi.CreateCustomerAsync(createCustomer); if (customerResponse.Errors != null && customerResponse.Errors.Any()) { return(purchaseResponse); } user.BillingId = customerResponse.Customer.Id; } CreateCustomerCardRequest cardRequest = new CreateCustomerCardRequest(purchaseModel.Token); var cardResponse = await customerApi.CreateCustomerCardAsync(user.BillingId, cardRequest); if (cardResponse.Errors != null && cardResponse.Errors.Any()) { return(purchaseResponse); } user.CardId = cardResponse.Card.Id; } (int price, int amount) = GetPricing(purchaseModel.Amount !); string idempotencyKey = Guid.NewGuid().ToString(); Money money = new Money(price, "USD"); CreatePaymentRequest body; if (purchaseModel.UseSaved || purchaseModel.SaveBilling) { body = new CreatePaymentRequest(SourceId: user.CardId, CustomerId: user.BillingId, IdempotencyKey: idempotencyKey, AmountMoney: money, Note: $"{user.Id} {purchaseModel.Amount}"); } else { body = new CreatePaymentRequest(SourceId: purchaseModel.Token, IdempotencyKey: idempotencyKey, AmountMoney: money, Note: $"{user.Id} {purchaseModel.Amount}"); } PaymentsApi paymentsApi = new PaymentsApi(configuration); var response = await paymentsApi.CreatePaymentAsync(body); if (response.Payment.Status == "COMPLETED") { user.Balance += amount; user.Repurchase = purchaseModel.Refill; if (user.Repurchase) { user.RepurchaseAmount = purchaseModel.Amount; } else { user.RepurchaseAmount = null; } var purchase = new Purchase { Id = Guid.NewGuid(), NanrAmount = amount, UsdAmount = price, Timestamp = DateTime.UtcNow }; context.Purchases.Add(purchase); await emailManager.SendPurchase(user, purchase); } else { return(purchaseResponse); } await context.SaveChangesAsync(); purchaseResponse.Success = true; purchaseResponse.Nanrs = amount; return(purchaseResponse); } catch (Exception ex) { Console.WriteLine(ex); return(purchaseResponse); } }