Building an API service can be complex and time-intensive, but a few well-positioned API services and open source libraries can reduce developer frustration and accelerate your time-to-market. In this post, you’ll create a complete API service plus a site to consume it and then drop in a few clever additions to smooth your way.

When you’re done with the example API service you’ll be able to:

  • Allow user registration, with Stormpath as middleware
  • Store user account data securely with Stormpath
  • Create API Keys for the user with Stormpath
  • Handle credit card payments with Stripe
  • Bill users on per-API call basis with Stripe
  • Find Bitcoin exchange rates with Bitcoin Charts
  • Send SMS messages with the Bitcoin exchange rate with Twilio

You’ll begin with Stormpath Evangelist Lee Brandt’s AngularJS + ASP.NET Core starter project, and add code to keep track of user account data such as API keys, total API queries, and balance. Finally, you’ll create a form to allow users to add credit to their accounts. As long as they have credit, they will be able to use your API service at a rate of $0.02/request.

bitcoin for user auth in asp.net core

You can find the code that backs this project on GitHub.

Now, let’s get started!

Start with ASP.NET Core + AngularJS

Lee wrote a simple and useful tutorial about creating an application with User Authentication in AngularJS and ASP.NET Core. The application is a to-do CRUD app with authentication and authorization. Clone the finished branch or download the finished project.

Stormpath Setup

The Stormpath ASP.NET Core Quickstart shows how to create an API key; here’s the abridged version:

From the Home tab of the Admin Console select Manage API Keys under the Developer Tools heading. Click the Create API Key button to trigger a download of a apiKey-{API_KEY}.properties file. Open the file in Notepad.

Using the Command Prompt or Powershell, run these commands:

Once you get your Stormpath API keys and run the finished application, you should see something like this:

btc login

Set Up Twilio

Twilio is an API service that helps your application send and receive calls and SMS messages. In this article, we’re going to explore just the SMS functionality.

Create your free Twilio trial account and get your own dedicated phone number.

You will need a verified caller ID to receive SMS messages from your Twilio account. For this article’s purpose, I am going to use a public free SMS number.

Twilio will send you a verification code and you will have to enter it on the site to confirm your number. The SMS message should be something like this:

twilio - verify number

Now, go to your Twilio Account Page and copy your API key credentials. Twilio gives you two API tokens: an Account SID and an Auth Token. Keep them safe and don’t share them with anyone!

twilio api credentials

Now that you have your sender (your Twilio trial number) and receiver (which must be verified by Twilio) numbers and your API keys, write them down somewhere handy, we’ll use them shortly.

Create the Backend Logic to Support Sending SMS Messages

Twilio’s CSharp library is not yet compatible with ASP.NET Core but there is a workaround via the Twilio REST API.
To store your sensitive Twilio data, you’ll want to use the ASP.NET Core User Secrets Manager and the IOptions pattern. If you want to learn more about different approaches to storing sensitive data check out my post on how to store and protect sensitive data.

Let’s set that up now. Create a class for Twilio Settings:

Right-click on the project and select Manage User Secrets. Edit the secrets.json file and add these configuration settings:

In “From” set your trial Twilio number, it should be something like: 12022022022. As you can see, you have to use your LIVE secrets but with your trial you should be fine to do this tutorial for free.

In the Startup class, add the AddUserSecrets method in the constructor to load your settings from the secrets.json file.

To bind the SmsSettings class to your application you will need to add it to the ConfigureServices method of the Startup class.

Create a Services folder and add a new class called SmsService, this class will be responsible for sending your application’s SMS messages.

Don’t forget to add this service in the ConfigureService method to also be injected by the framework later:

Thus far, you have all the logic needed to send SMS messages, but you will see this in action in the following steps. Now, let’s continue with Stripe to manage payments.

Set up Stripe

Visit Stripe, and create your Stripe account if you don’t have one already. Once you’re logged in, go to Account – API and copy your test API keys to be used later on. You’ll need both the public (publishable) and private (secret) key.

Create the Backend Logic to Support Credit Card Payments

You’ll need to store the Stripe API keys securely, simply replicate the approach applied above for Twilio’s sensitive data.

Create a PaymentSettings class to store your Stripe API Keys.

Open the secrets.json file and add your Stripe API keys next to your Twilio settings:

Then, bind the PaymentSettings with your secrets by adding the following code in the ConfigureServices method of the Startup class:

Install Stripe.NET using the NuGet Package Manager, or from the Package Manager Console:

Then, add a new service class called PaymentService to your “Services” folder. This class will be responsible for handling and processing the payment:

Register the PaymentService and the StripeChargeService in the Startup class to be injected later on by the framework:

Create the Backend Logic to Manage the User Account

Create a class UserAccountInfo in the Models folder to store the user account data:

Then, create a service in the Services folder called AccountService. This service will be responsible for handling the user account data:

Then, replace the AddStormpath() configuration line in the ConfigureServices of the Startup class by the following code:

Here, you added a handler to be executed after user registration and initialize the user’s custom data fields. These fields will hold the user’s API call volume (their total queries) and the money that the user has in their balance.

Create the Bitcoin Backend Logic

Let’s do a little recap: Thus far, you have built the backend services to send SMS messages via Twilio and process payments with Stripe. Also, your backend is capable of managing the user account, including reading and updating its custom data, where you will store the user balance and the number of API calls.

You will now create the service to retrieve the Bitcoin exchange rate:
Create a BtcExchangeRateResponse and a BtcExchangeRateCurrency class in the Models folder:

These classes will hold the Bitcoin data.

Create a BitcoinExchangeRateService in the Services folder:

The bitcoincharts site provides a publicly available API that lets you grab the current Bitcoin exchange rates. Here, you’ll be using the bitcoincharts API to get the current Bitcoin exchange rate.

Again, you’ll have to configure this service in the Startup.cs so it can be injected into the controller:

Create the Controllers

Now that you have all the services that you need, it’s time to create the controllers to expose the endpoints!

Create a MeController in the Controllers folder. This controller will allow you to grab the user account info.

Then, create the PaymentController in the Controllers folder, this controller will allow you to update the user’s balance.

As you can see, the Post method receives PaymentFormData as parameter. This object is a wrapper to encapsulate the Stripe response token.

Create the PaymentFormData class in the Models folder:

Lastly, create a MessageController in the Controllers folder:

The [Authorize] attribute ensures that only authenticated users have access.
The MessageController uses the AccountService to grab and update the user’s balance and query count. It also uses BitcoinExchangeRateService to get the Bitcoin rate, and sends the SMS message to the provided phone number through the SmsService.

Whew! You now have a full-fledged API service! But wait! There’s more! Keep going to see your service in action.

Create the Dashboard View and Files

Thus far, you have all the backend logic ready. Now, is time to build the frontend and integrate it with your API.
In this section, I will show you how to build all the stuff related to the front-end, such as: dashboard and payment views, controllers and services.

You will have now to update the index.html so that your web application has a Dashboard option in the nav bar. This option will be available for authenticated users, and once they enter to this section, they will see all their account information.

As you can see, the Index.html includes a couple of new script tags, such as Angular Payments, which will help you with the Stripe payment form and Angular Material js files to improve the app user experience.
The dashboard and auth services, view and controllers are added too. Below, I will show you how to create each of them.

Create a folder called dashboard under the wwwroot > app folder. Then, under dashboard create three new folders: controllers, services and views. These will be for the dashboard.controller.js, dashboard.service.js and the dashboard.view.html files, respectively.

Now, create the dashboard.service to encapsulate the dashboard api calls and logic:

Create the dashboard.controller to encapsulate the logic to interact with the view:

Create the dashboard.view.html:

Create a template folder to include a template for the payment form view:

Finally, modify the app.js to include the dashboard url in the routes. Make sure you paste in your Stripe public (publishable) key!

Note: Be sure to have the img folder just as it is on the GitHub repository and set your Stripe public key in the placeholder!

Now you’ll want to modify the main.css stylesheet to make sure your application looks polished.

Modify the applicationUrl property in the launchSettings.json and set the default route. In my case:

And… that’s it! You just have built an API in ASP.NET Core with Stormpath, Stripe and Twilio.

I hope you have found this post useful and that it inspires you to apply new ideas to your projects. There’s much more to learn about, continue exploring and check out some of our other interesting posts!

  • Build a Freemium Site with Stormpath and Stripe in ASP.NET Core
  • Build a REST API for Your Mobile Apps with ASP.NET Core
  • 5 Tips for Building an API in ASP.NET Core