# install stripe dotnet add package Stripe.net # for reading local env file # NOT REQUIRED unless you want to read from .env dotnet add package DotNetEnv # install required code generation code Microsoft.VisualStudio.Web.CodeGeneration.Design # global install scaffolding tool dotnet tool install --global dotnet-aspnet-codegenerator
touch .env
Within the Dotenv file, we need to add your test keys from Stripe's website.
SK_TEST_KEY= sk_test... PK_TEST_KEY=pk_test...
If you are going to use another method to fetch the variables (ie secrets etc), you could add the following to your appsettings.json
file:
{ // previous key/values omitted for brevity "Stripe": { "SecretKey": "SK_TEST_KEY", // this will eval to sk_test_... .env "PublishableKey": "PK_TEST_KEY" // this will eval to sk_test_... from .env } }
Make sure to check the docs on passing parameters
using Stripe; using DotNetEnv; // ... code omitted for brevity public Startup(IConfiguration configuration) { Configuration = configuration; // load .env file DotNetEnv.Env.Load(); // set config using env var StripeConfiguration.ApiKey = System.Environment.GetEnvironmentVariable("SK_TEST_KEY"); }
// in Models/StripeCharge.cs namespace ChargeApi.Models { public class StripeCharge { public long Amount { get; set; } public string Currency { get; set; } public string Source { get; set; } public string ReceiptEmail { get; set; } } }
// Controllers/Charge.cs using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Stripe; using ChargeApi.Models; namespace dotnet_stripe.Controllers { [ApiController] [Route("api/charges")] public class ChargesController : Controller { [HttpPost] public Stripe.Charge CreateCharge([FromBody] StripeCharge createOptions) { var options = new ChargeCreateOptions { Amount = createOptions.Amount, Currency = "usd", Source = "tok_visa", ReceiptEmail = "tim.apple@example.com", }; var service = new ChargeService(); var charge = service.Create(options); return charge; } } }
Since we are sending back the response from the Stripe.Charge
object, it will be very verbose and not what you want to do in reality for the API.
Using HTTPie (check resource [12]), we can check for our 200 response with the full JSON body returned by Stripe by calling http POST http://localhost:5000/api/charges Amount:=200
in our console.
Heading to our Stripe dashboard and checking under Developers > Events
, one can see our payment made for US$2.00
by "tim.apple@example.com"
. Great success!
Of course, all those values are coded and not exactly what we want in the real world... but we are connected.