-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStripeWebhook.cs
More file actions
112 lines (98 loc) · 4.28 KB
/
Copy pathStripeWebhook.cs
File metadata and controls
112 lines (98 loc) · 4.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Stripe;
using System.Net;
using System.Text.Json;
using HoTeach.Entities;
using HoTeach.Infrastructure.Interfaces;
using HoTeach.Payments.Services;
namespace HoTeach
{
public class StripeWebhook
{
private readonly ILogger<StripeWebhook> _logger;
private readonly IRepository<Payment> _paymentRepository;
public StripeWebhook(ILogger<StripeWebhook> logger, IRepository<Payment> paymnRepository)
{
_logger = logger;
_paymentRepository = paymnRepository;
}
[Function("StripeWebhook")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "stripe-webhook")] HttpRequestData req)
{
var response = req.CreateResponse();
try
{
if (!req.Headers.TryGetValues("Stripe-Signature", out var signatureValues))
{
response.StatusCode = HttpStatusCode.BadRequest;
await response.WriteAsJsonAsync(new { error = "No signature found" });
return response;
}
var signature = signatureValues.FirstOrDefault();
var stripeSecretKey = Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY");
var webhookSecret = Environment.GetEnvironmentVariable("STRIPE_WEBHOOK_SECRET");
if (string.IsNullOrEmpty(stripeSecretKey) || string.IsNullOrEmpty(webhookSecret))
{
response.StatusCode = HttpStatusCode.BadRequest;
await response.WriteAsJsonAsync(new { error = "Stripe configuration is missing" });
return response;
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var stripeService = new StripeService(stripeSecretKey, webhookSecret);
var stripeEvent = stripeService.VerifyWebhook(requestBody, signature);
switch (stripeEvent.Type)
{
case Events.CheckoutSessionCompleted:
if (stripeEvent.Data.Object is Stripe.Checkout.Session session)
{
await HandleSuccessfulPayment(session);
}
else
{
_logger.LogWarning("Invalid session object in checkout.session.completed event");
}
break;
default:
_logger.LogInformation($"Unhandled event type: {stripeEvent.Type}");
break;
}
response.StatusCode = HttpStatusCode.OK;
return response;
}
catch (StripeException ex)
{
_logger.LogError($"Stripe error: {ex.Message}");
response.StatusCode = HttpStatusCode.BadRequest;
await response.WriteAsJsonAsync(new { error = ex.Message });
return response;
}
catch (Exception ex)
{
_logger.LogError($"Error: {ex.Message}");
response.StatusCode = HttpStatusCode.InternalServerError;
return response;
}
}
private async Task HandleSuccessfulPayment(Stripe.Checkout.Session session)
{
_logger.LogInformation($"Payment successful for customer {session.CustomerId}");
var stripeSecretKey = Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY");
var webhookSecret = Environment.GetEnvironmentVariable("STRIPE_WEBHOOK_SECRET");
var stripeService = new StripeService(stripeSecretKey, webhookSecret);
var customer = await stripeService.GetCustomer(session.CustomerId);
await _paymentRepository.InsertAsync(new Payment()
{
PaymentIntentId = session.PaymentIntentId,
UserId = customer.Metadata["UserId"]
});
await Task.CompletedTask;
}
}
}