Is there any sample for PayPal IPN

后端 未结 5 1131
半阙折子戏
半阙折子戏 2021-02-05 20:47

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

5条回答
  •  忘了有多久
    2021-02-05 21:41

    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.

提交回复
热议问题