Integrating PayPal Payment Gateway with .NET Core

Integrating a payment gateway into your application is crucial for businesses that require online transactions. PayPal is one of the most popular and widely used payment gateways, offering a secure and easy-to-integrate solution for accepting payments. In this article, we'll walk through the process of integrating the PayPal payment gateway into a .NET Core application using the "Codingvila" namespace to help illustrate key concepts with practical code examples.

Prerequisites

Before we begin, ensure you have the following.

  • A PayPal Developer Account.
  • .NET Core SDK installed on your machine.
  • A code editor or IDE (like Visual Studio).

Step 1. Setting Up the PayPal SDK

First, you need to install the PayPal SDK for .NET. Open your terminal and navigate to your project directory. Run the following command to install the PayPal SDK.

dotnet add package PayPalCheckoutSdk

Step 2. Setting Up Your PayPal Client

Create a new class called PayPalClient.cs in your project. This class will be responsible for authenticating requests to the PayPal API.

using PayPalCheckoutSdk.Core;
using PayPalHttp;
namespace Codingvila
{
    public class PayPalClient
    {
        public static PayPalEnvironment Environment()
        {
            return new SandboxEnvironment("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET");
        }

        public static HttpClient Client()
        {
            return new PayPalHttpClient(Environment());
        }
    }
}

Replace "YOUR_CLIENT_ID" and "YOUR_CLIENT_SECRET" with your actual PayPal client ID and secret.

Step 3. Creating a Payment

In the same namespace, create a class called CreatePayment.cs. This class will handle the logic to create a payment.

using PayPalCheckoutSdk.Orders;
using PayPalHttp;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Codingvila
{
    public class CreatePayment
    {
        public async static Task<HttpResponse> CreateOrder()
        {
            var request = new OrdersCreateRequest();
            request.Prefer("return=representation");
            request.RequestBody(BuildRequestBody());
            var response = await PayPalClient.Client().Execute(request);
            return response;
        }

        private static OrderRequest BuildRequestBody()
        {
            return new OrderRequest()
            {
                Intent = "CAPTURE",
                PurchaseUnits = new List<PurchaseUnitRequest>
                {
                    new PurchaseUnitRequest
                    {
                        AmountWithBreakdown = new AmountWithBreakdown
                        {
                            CurrencyCode = "USD",
                            Value = "100.00"
                        }
                    }
                }
            };
        }
    }
}

This code defines a method to create an order with a total amount of $100.00. You can customize the amount and currency as needed.

Step 4. Processing the Payment

Create a controller or a method in your existing controller to handle the payment process. Here's a simple example.

using Microsoft.AspNetCore.Mvc;
using PayPalHttp;
using System.Threading.Tasks;
namespace Codingvila.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PaymentController : ControllerBase
    {
        [HttpPost("create-payment")]
        public async Task<IActionResult> CreatePayment()
        {
            HttpResponse response = await CreatePayment.CreateOrder();
            if (response.StatusCode == 201)
            {
                return Ok(response.Result<Order>());
            }

            return BadRequest();
        }
    }
}

This controller includes an endpoint that triggers the payment creation process.

Summary

Integrating PayPal into your .NET Core application provides a secure and reliable way for users to make payments. By following these steps, you can set up a basic payment flow that can be further customized to fit your specific needs. As with any integration involving sensitive information, ensure you handle all data securely and comply with PayPal's best practices and guidelines.


Similar Articles
Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.