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
}
}
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");
}
Create the Model
// 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; }
}
}
Create the Controller
// 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 = "auread",
Source = "tok_visa",
ReceiptEmail = "hello_dotnet@example.com",
};
var service = new ChargeService();
var charge = service.Create(options);
return charge;
}
}
}
Sending the request on HTTPie
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.
In this example using HTTPie, call http POST http://localhost:5000/api/charges amount:=1700 receipt_email=hello_dotnet@example.com and we will get back our charge results sent as JSON. Hooray!
I chose to use HTTPie because I feel it is a fun tool that more should know about! Alternative, you could do the above using curl as well (or anything that can make a POST request for a matter of fact).