This repository has been archived by the owner on Sep 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IpnController.cs
71 lines (62 loc) · 2.38 KB
/
IpnController.cs
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
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PayPalHelper.Core.Extensions;
using PayPalHelper.Core.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace PayPalHelper.Core
{
public abstract class IpnController : Controller
{
private readonly ILogger _logger;
protected abstract PayPalEnvironment Environment { get; }
protected abstract bool LogUnverifiedTransactions { get; }
protected abstract Task OnVerifiedAsync(PayPalTransaction transaction);
protected async virtual Task OnVerifiedExceptionAsync(Exception exception) { await Task.CompletedTask; }
public IpnController(ILogger logger)
{
_logger = logger;
}
[HttpPost]
public async Task<IActionResult> Listener()
{
try
{
var result = await Request.VerifyPayPalTransactionAsync(Environment);
if (result.IsVerified)
{
_logger.LogInformation($"Verified transaction at {DateTime.UtcNow}:\r\n{GetFormText(Request.Form)}");
try
{
await OnVerifiedAsync(result.Transaction);
}
catch (Exception exc)
{
_logger.LogError(exc, $"Verified transaction handler failed at {DateTime.UtcNow} because {exc.Message}, form data:\r\n{GetFormText(Request.Form)}");
await OnVerifiedExceptionAsync(exc);
}
}
else
{
if (LogUnverifiedTransactions)
{
_logger.LogInformation($"Unverified transaction at {DateTime.UtcNow}:\r\n{GetFormText(Request.Form)}");
}
}
}
catch (Exception exc)
{
_logger.LogError($"Verification check failed at {DateTime.Now}: {exc.Message}");
}
// we never want exceptions getting back to PayPal.
// if there's a problem, we must handle internally.
return Ok();
}
private string GetFormText(IFormCollection form)
{
return string.Join("\r\n", form.Select(field => $"{field.Key} = {field.Value}"));
}
}
}