using Microsoft.AspNetCore.Mvc; using MistoxWebsite.Server.Controllers.Payment; using MistoxWebsite.Server.Services.DatabaseService; using MistoxWebsite.Shared.Database; using Stripe; namespace MistoxWebsite.Server.Controllers { [ApiController] public class PaymentController : ControllerBase { DatabaseService _databaseService; public PaymentController( DatabaseService databaseService ) { _databaseService = databaseService; } // Charges [Route( "api/getCheckoutToken" )] [HttpPost] public async Task GetPaymentKey( [FromQuery] string userID ) { string OrderNumber = Guid.NewGuid().ToString().Substring(0,10); Shared.Database.Account? acc = await _databaseService.GetAccount(userID); if (acc != null) { List cart = await _databaseService.GetCart(acc); IPayment PaymentPlugin = new StripeIntent(_databaseService); (bool, string) PaymentResponse = await PaymentPlugin.Purchase(OrderNumber, acc, cart); if (PaymentResponse.Item1) { return PaymentResponse.Item2; } else { Console.WriteLine("An error has occured in the payment plugin\n\n"); Console.WriteLine(PaymentResponse.Item2); Console.WriteLine("\n"); return "0"; } } return "0"; } [Route( "/api/payment/response" )] [HttpPost] public async Task paymentWebhook() { try { const string endpointSecret = "whsec_HCO7uv2BPIPmUPOiSg9tfwLZul8usCGG"; string body = await new StreamReader(Request.Body).ReadToEndAsync(); Event e = EventUtility.ConstructEvent( body, Request.Headers["Stripe-Signature"], endpointSecret ); if( e.Type == "payment_intent.succeeded" ) { // Extract Data from payment confirm PaymentIntent intent = (PaymentIntent)e.Data.Object; string orderNumber = ""; int userID = 0; List productIDs = new List(); int subtotal = 0; int total = 0; KeyValuePair[] y = intent.Metadata.ToArray(); foreach( KeyValuePair cur in y ) { string val = cur.Key; if( val == "ordernumber" ) { orderNumber = cur.Value; } else if( val == "user" ) { userID = int.Parse( cur.Value ); } else if( val == "products" ) { string[] products = cur.Value.Split(','); foreach( string product in products ) { if ( !string.IsNullOrEmpty(product) ) { productIDs.Add( Convert.ToInt32( product ) ); } } } else if( val == "subtotal" ) { subtotal = int.Parse( cur.Value ); } else if( val == "total" ) { total = int.Parse( cur.Value ); } } // Clear the cart Shared.Database.Account account = new() { ID = userID }; await _databaseService.ClearCart( account ); // Add data to misox receipt for( int i = 0; i < productIDs.Count; i++ ) { int product = productIDs[i]; await _databaseService.NewReceipt( new Receipt { AccountID = userID, ProductID = product, ReceiptID = orderNumber, Time = DateTime.Now, TaxAmount = total - subtotal, TotalCost = total, LineItem = i } ); } } else { Console.WriteLine( "Unhandled event type: {0}", e.Type ); } return Ok(); } catch( Exception ex ) { return Content(ex.ToString()); } } } }