I have an Asp.Net WEB API 2 project and I would like to implement an Instant Payment Notification (IPN) listener controller.
I can\'t find any example and nuget package
Based on accepted answer I came up with the following code implementing IPN listener for ASP.NET MVC. The solution has already been deployed and appears to work correctly.
[HttpPost]
public async Task Ipn()
{
var ipn = Request.Form.AllKeys.ToDictionary(k => k, k => Request[k]);
ipn.Add("cmd", "_notify-validate");
var isIpnValid = await ValidateIpnAsync(ipn);
if (isIpnValid)
{
// process the IPN
}
return new EmptyResult();
}
private static async Task ValidateIpnAsync(IEnumerable> ipn)
{
using (var client = new HttpClient())
{
const string PayPalUrl = "https://www.paypal.com/cgi-bin/webscr";
// This is necessary in order for PayPal to not resend the IPN.
await client.PostAsync(PayPalUrl, new StringContent(string.Empty));
var response = await client.PostAsync(PayPalUrl, new FormUrlEncodedContent(ipn));
var responseString = await response.Content.ReadAsStringAsync();
return (responseString == "VERIFIED");
}
}
EDIT:
Let me share my experience - the above code was working just fine up until now, but suddenly it failed for one IPN it was processing, i.e. responseString == "INVALID"
.
The issue turned out to be that my account was set up to use charset == windows-1252
which is PayPal default. However, FormUrlEncodedContent
uses UTF-8 for encoding and therefore the validation failed because of national characters like "ř". The solution was to set charset
to UTF-8, which can be done in Profile > My selling tools > PayPal button language encoding > More Options, see this SO thread.