Skip to content

adamfoneil/PayPal.Extensions

Repository files navigation

This is a reboot of my PayPalHelper2 as several things about that were outdated. I wanted to modernize this for .NET6, leveraging Minimal APIs for testing, removing the Newtonsoft dependency along with some other minor enhancements.

Note that I don't really have a proper integration test because you need your own Ngrok and PayPal accounts to test this effectively. And my testing was against the PayPal sandbox only using their IPN simulator, not an actual transaction. Still, the heart of this is the VerifyPayPalTransactionAsync method, used in my test handler here.

app.MapPost("/IpnTest", async (HttpContext context) =>
{
    var httpClientFactory = context.RequestServices.GetRequiredService<IHttpClientFactory>();
    var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("IpnTest");

    try
    {
        var result = await context.Request.VerifyPayPalTransactionAsync(PayPalEnvironment.Sandbox, httpClientFactory, logger);

        if (result.IsVerified)
        {
            logger.LogInformation($"Item num: {result.Transaction.ItemNumber}, gross = {result.Transaction.Gross:c2}");
        }
    }
    catch (Exception exc)
    {
        // don't let exceptions escape from IPN handler, or PayPal will keep retrying and potentially disable the callback if it keeps failing
        logger.LogError(exc, "Error in /IpnTest handler: {message}", exc.Message);
    }
});

Note that this SO Q&A was helpful because Minimal APIs don't support application/x-www-form-urlencoded posts directly, which is what PayPal uses when posting to your IPN listener.

About

Extension method for verifying PayPal transactions in .NET6 apps

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages