Files
social-media/src/Infrastructure/Stripe/StripeService.cs
2024-06-30 12:35:14 -04:00

78 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Stripe;
using Stripe.Checkout;
using Hutopy.Application.Common.Interfaces;
using Microsoft.AspNetCore.Http;
using Hutopy.Application.Common.Models;
using Hutopy.Application.Stripe.Commands;
using Microsoft.Extensions.Configuration;
namespace Hutopy.Infrastructure.Stripe;
public class StripeService : IStripeService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public StripeService(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
{
_httpContextAccessor = httpContextAccessor;
var stripeKey = configuration["STRIPE-API-KEY"] ?? "";
StripeConfiguration.ApiKey = stripeKey;
}
public async Task<string> CreateCheckoutSession(int amount, string creatorId, string currency = "cad")
{
var options = new SessionCreateOptions
{
LineItems =
[
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
UnitAmount = amount,
Currency = currency,
ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Tip", },
},
Quantity = 1,
}
],
Mode = "payment",
UiMode = "embedded",
ReturnUrl = $"https://hutopy.ca/paymentcompleted?creatorId={creatorId}",
InvoiceCreation = new SessionInvoiceCreationOptions(){ Enabled = true},
ClientReferenceId = creatorId
};
var service = new SessionService();
Session session = await service.CreateAsync(options);
return session.ClientSecret;
}
public Result ValidateTransaction(ConfirmStripeTransactionCommand request)
{
try
{
if (request.Data.Object.Status is "succeeded")
{
return new Result(true, new List<string>());
}
return new Result(false, new List<string>());
}
catch (StripeException e)
{
Console.WriteLine("Error: {0}", e.Message);
return new Result(false, new List<string>{e.Message});
}
catch (Exception e)
{
return new Result(false, new List<string>{e.Message});
}
}
}