-
Notifications
You must be signed in to change notification settings - Fork 0
/
PayPalExtensions.cs
80 lines (64 loc) · 2.72 KB
/
PayPalExtensions.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
72
73
74
75
76
77
78
79
80
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using PayPalExtensions.Models;
using System.Text.Json;
namespace PayPal.Extensions
{
public enum PayPalEnvironment
{
Sandbox,
Live
}
public static class PayPalExtensions
{
public static Dictionary<PayPalEnvironment, Uri> Urls => new()
{
[PayPalEnvironment.Live] = new Uri("https://ipnpb.paypal.com/"),
[PayPalEnvironment.Sandbox] = new Uri("https://ipnpb.sandbox.paypal.com/")
};
public static async Task<VerificationResult> VerifyPayPalTransactionAsync(this HttpRequest request, PayPalEnvironment environment, IHttpClientFactory httpClientFactory, ILogger? logger = null)
{
VerificationResult result = new();
using var client = httpClientFactory.CreateClient();
try
{
if (client.BaseAddress == null)
{
client.BaseAddress = Urls[environment];
}
client.DefaultRequestHeaders.Accept.Clear();
var formValues = new Dictionary<string, string>();
formValues.Add("cmd", "_notify-validate");
foreach (var field in request.Form) formValues.Add(field.Key, field.Value);
var content = new FormUrlEncodedContent(formValues);
var response = await client.PostAsync("cgi-bin/webscr", content);
if (response.IsSuccessStatusCode)
{
var responseText = await response.Content.ReadAsStringAsync();
result.IsVerified = responseText.Trim().Equals("VERIFIED");
if (result.IsVerified)
{
result.Transaction = request.Form.ParseForm<PayPalTransaction>();
}
return result;
}
throw new Exception($"PayPal API call failed: {response.Content}");
}
catch (Exception exc)
{
result.Exception = exc;
logger?.LogError(exc, "Error in VerifyPayPalTransactionAsync: {message}", exc.Message);
}
return result;
}
public static T? ParseForm<T>(this IFormCollection form) where T : new()
{
var fields = form
.Select(keyPair => new KeyValuePair<string, string>(keyPair.Key, keyPair.Value.First()))
.ToDictionary(keyPair => keyPair.Key, keyPair => keyPair.Value);
string json = JsonSerializer.Serialize(fields);
if (string.IsNullOrEmpty(json)) return default;
return JsonSerializer.Deserialize<T>(json);
}
}
}