Back

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

Jul 19, 20247 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of online payments? Stripe is your go-to solution, and we're about to make it dance with C#. We'll be using the Stripe.net package, so buckle up for a smooth ride!

Prerequisites

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

  • A cozy .NET environment set up
  • A Stripe account with those shiny API keys

Installation

Let's kick things off by adding Stripe.net to your project. Fire up your package manager console and run:

Install-Package Stripe.net

Easy peasy, right?

Configuration

Now, let's get Stripe talking to your app. Add this to your startup code:

StripeConfiguration.ApiKey = "your_secret_key_here";

Pro tip: Keep that API key safe and sound in your configuration files!

Basic Operations

Creating a Customer

Time to roll out the red carpet for your users:

var customerService = new CustomerService(); var customer = await customerService.CreateAsync(new CustomerCreateOptions { Email = "[email protected]", Name = "Cool Customer" });

Adding a Payment Method

Let's give your customer a way to pay:

var paymentMethodService = new PaymentMethodService(); var paymentMethod = await paymentMethodService.AttachAsync( "pm_card_visa", // This is a test card token new PaymentMethodAttachOptions { Customer = customer.Id, } );

Creating a Charge

Ka-ching! Time to make it rain:

var chargeService = new ChargeService(); var charge = await chargeService.CreateAsync(new ChargeCreateOptions { Amount = 2000, // That's $20.00 Currency = "usd", Customer = customer.Id, PaymentMethod = paymentMethod.Id, });

Handling Subscriptions

Creating a Subscription

Recurring revenue, here we come:

var subscriptionService = new SubscriptionService(); var subscription = await subscriptionService.CreateAsync(new SubscriptionCreateOptions { Customer = customer.Id, Items = new List<SubscriptionItemOptions> { new SubscriptionItemOptions { Price = "price_1234567890", // Your price ID here }, }, });

Updating a Subscription

Change of plans? No problem:

var updatedSubscription = await subscriptionService.UpdateAsync( subscription.Id, new SubscriptionUpdateOptions { Items = new List<SubscriptionItemOptions> { new SubscriptionItemOptions { Id = subscription.Items.Data[0].Id, Price = "price_0987654321", // New price ID }, }, } );

Canceling a Subscription

All good things must come to an end:

var canceledSubscription = await subscriptionService.CancelAsync(subscription.Id);

Working with Invoices

Creating an Invoice

Bill 'em up:

var invoiceService = new InvoiceService(); var invoice = await invoiceService.CreateAsync(new InvoiceCreateOptions { Customer = customer.Id, });

Retrieving Invoices

Let's see what's due:

var invoices = await invoiceService.ListAsync(new InvoiceListOptions { Customer = customer.Id, });

Paying an Invoice

Time to settle up:

var paidInvoice = await invoiceService.PayAsync(invoice.Id);

Webhook Integration

Listen up for Stripe's updates:

[HttpPost] public async Task<IActionResult> HandleWebhook() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); try { var stripeEvent = EventUtility.ConstructEvent( json, Request.Headers["Stripe-Signature"], "whsec_your_webhook_secret" ); // Handle the event if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; // Handle successful payment } return Ok(); } catch (StripeException e) { return BadRequest(); } }

Error Handling and Best Practices

Always wrap your Stripe calls in try-catch blocks. Stripe throws specific exceptions that you can catch and handle gracefully.

Security tip: Never log full card details or API keys. Your future self will thank you!

Testing

Stripe's got your back with a test mode. Use test API keys and card numbers to simulate transactions without moving real money.

For unit testing, consider mocking the Stripe service interfaces to isolate your code from the actual API calls.

Conclusion

And there you have it! You're now armed and dangerous with Stripe integration skills. Remember, the Stripe docs are your best friend for diving deeper.

Now go forth and process those payments like a boss! 💪💳✨