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!
Before we jump in, make sure you've got:
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?
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!
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" });
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, } );
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, });
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 }, }, });
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 }, }, } );
All good things must come to an end:
var canceledSubscription = await subscriptionService.CancelAsync(subscription.Id);
Bill 'em up:
var invoiceService = new InvoiceService(); var invoice = await invoiceService.CreateAsync(new InvoiceCreateOptions { Customer = customer.Id, });
Let's see what's due:
var invoices = await invoiceService.ListAsync(new InvoiceListOptions { Customer = customer.Id, });
Time to settle up:
var paidInvoice = await invoiceService.PayAsync(invoice.Id);
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(); } }
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!
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.
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! 💪💳✨