Make payments dependency injected based on the .env settings

This commit is contained in:
2025-06-20 18:31:18 -07:00
parent c4ad0f2c10
commit fb2a2c6ae9
8 changed files with 111 additions and 83 deletions
@@ -4,8 +4,16 @@ namespace MistoxWebsite.Server.Controllers.Payment {
public interface IPayment {
public Task<(bool, string)> Purchase(string OrderNumber, Account user, List<Cart> cart);
public static PaymentType _PaymentType;
public static string _EndpointSecret = "";
public Task<(bool, string)> TryGetCheckoutToken(string OrderNumber, Account user, List<Cart> cart);
public Task ValidatePurchase(string WebHookData, string Headers);
}
public enum PaymentType {
StripeIntent
}
}
@@ -8,11 +8,11 @@ namespace MistoxWebsite.Server.Controllers {
DatabaseService _databaseService;
public StripeIntent( DatabaseService databaseService ) {
public StripeIntent(DatabaseService databaseService) {
_databaseService = databaseService;
}
public async Task<(bool, string)> Purchase(string OrderNumber, Account user, List<Cart> cart) {
public async Task<(bool, string)> TryGetCheckoutToken(string OrderNumber, Account user, List<Cart> cart) {
try {
// build Recipt and calculate Tax
var options = new Stripe.Tax.CalculationCreateOptions {
@@ -72,12 +72,71 @@ namespace MistoxWebsite.Server.Controllers {
Stripe.PaymentIntent x = await intentService.CreateAsync(paymentIntent);
return (true, x.ClientSecret);
} catch(Exception e) {
} catch (Exception e) {
return (false, e.ToString());
}
}
public async Task ValidatePurchase(string WebHookData, string Headers) {
Stripe.Event e = Stripe.EventUtility.ConstructEvent( WebHookData, Headers, IPayment._EndpointSecret );
if (e.Type == "payment_intent.succeeded") {
// Extract Data from payment confirm
Stripe.PaymentIntent intent = (Stripe.PaymentIntent)e.Data.Object;
string orderNumber = "";
int userID = 0;
List<int> productIDs = new List<int>();
int subtotal = 0;
int total = 0;
KeyValuePair<string, string>[] y = intent.Metadata.ToArray();
foreach (KeyValuePair<string, string> 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
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);
}
}
}
}