Back

Step by Step Guide to Building a PayPal API Integration in C#

Aug 2, 20247 minute read

Hey there, fellow developer! Ready to dive into the world of PayPal integration? You're in the right place. Let's walk through building a robust PayPal API integration using C# and the PayPalCheckoutSdk package. Buckle up, and let's get coding!

Prerequisites

Before we jump in, make sure you've got these essentials:

  • .NET Core SDK (the newer, the better)
  • A PayPal Developer account (if you don't have one, it's quick to set up)
  • PayPalCheckoutSdk NuGet package (we'll grab this in a bit)

Setting Up Your Project

First things first, let's create a new .NET Core project. Fire up your terminal and run:

dotnet new webapi -n PayPalIntegration cd PayPalIntegration

Now, let's add the PayPalCheckoutSdk package:

dotnet add package PayPalCheckoutSdk

Configuring PayPal Credentials

Head over to the PayPal Developer Dashboard and grab your API credentials. You'll need the Client ID and Secret.

Pro tip: Never hardcode these! Instead, use environment variables or a configuration file. Here's a quick way to set them up in your appsettings.json:

{ "PayPal": { "ClientId": "YOUR_CLIENT_ID", "Secret": "YOUR_SECRET" } }

Initializing the PayPal Client

Time to get our hands dirty with some C# code. Create a new file called PayPalClient.cs:

using PayPalCheckoutSdk.Core; using Microsoft.Extensions.Configuration; public class PayPalClient { private readonly IConfiguration _configuration; public PayPalClient(IConfiguration configuration) { _configuration = configuration; } public PayPalHttpClient Client() { var environment = new SandboxEnvironment( _configuration["PayPal:ClientId"], _configuration["PayPal:Secret"]); return new PayPalHttpClient(environment); } }

Creating an Order

Let's implement the order creation. Add a new OrdersController.cs:

using PayPalCheckoutSdk.Orders; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("[controller]")] public class OrdersController : ControllerBase { private readonly PayPalHttpClient _client; public OrdersController(PayPalClient payPalClient) { _client = payPalClient.Client(); } [HttpPost("create")] public async Task<IActionResult> CreateOrder() { var order = new OrderRequest() { CheckoutPaymentIntent = "CAPTURE", PurchaseUnits = new List<PurchaseUnitRequest> { new PurchaseUnitRequest { AmountWithBreakdown = new AmountWithBreakdown { CurrencyCode = "USD", Value = "100.00" } } } }; var request = new OrdersCreateRequest(); request.Prefer("return=representation"); request.RequestBody(order); var response = await _client.Execute(request); var result = response.Result<Order>(); return Ok(new { id = result.Id }); } }

Capturing Payment

Now, let's add a method to capture the payment:

[HttpPost("capture/{orderId}")] public async Task<IActionResult> CaptureOrder(string orderId) { var request = new OrdersCaptureRequest(orderId); var response = await _client.Execute(request); var result = response.Result<Order>(); return Ok(new { id = result.Id, status = result.Status }); }

Integrating with Your Application

You've got your endpoints set up. Now, you'll need to integrate this with your front-end. Here's a quick JavaScript snippet to get you started:

// Create order fetch('/orders/create', { method: 'POST' }) .then(res => res.json()) .then(data => { // Use data.id to complete the payment }); // Capture payment fetch(`/orders/capture/${orderId}`, { method: 'POST' }) .then(res => res.json()) .then(data => { if (data.status === 'COMPLETED') { // Payment successful! } });

Error Handling and Logging

Don't forget to wrap your API calls in try-catch blocks and log any errors. It'll save you headaches later, trust me!

try { // Your API call here } catch (HttpException ex) { // Log the error return StatusCode((int)ex.StatusCode, ex.Message); }

Testing the Integration

Time to put on your tester hat! Use PayPal Sandbox accounts to simulate various scenarios. Try successful payments, declined payments, and anything else you can think of. Better to catch issues now than in production!

Going Live

Once you're confident everything's working smoothly, it's time to go live. Update your PayPalClient.cs to use the live environment:

var environment = new LiveEnvironment( _configuration["PayPal:ClientId"], _configuration["PayPal:Secret"]);

And don't forget to update your credentials for production!

Wrapping Up

And there you have it! You've successfully integrated PayPal into your C# application. Remember, this is just the beginning. PayPal's API offers a ton of features, so don't be afraid to explore and expand your integration.

For more in-depth info, check out the PayPal API docs. Happy coding, and may your transactions always be successful!