How to build a cryptocurrency app
learn to build your first cryptocurrency app using angular 4 , expressjs and coinbase api
Introduction to TutorialTerms like bitcoin , litecoin and ethereum have become the part of many everyday conversations these days. These are the names of cryptocurrencies which are trending these days and our tutorial is very closely related to these as in this tutorial, we aim build a very simple cryptocurrency app. This tutorial will help you gain deeper insights into the world of crypto because we'll look closely into what're the different operations a crypto exchange does. Our app will utilize the coinbase api. we'll introducecoinbase in the following section. Tech ComponentsWe'll be using the following tech components in this tutorial ::
- Angular 4 :: Angular 4 is a frontend framework and hence it will be utilized to design the front end experience of our app. If you're new to Angular 4 , you can visit the Angular 4 tutorial here .
- ExpressJS :: ExpressJS is a web application framework based on nodejs , need more information on express ? visit this link.
- Coinbase API :: Coinbase is a cryptocurrency exchange which supports 3 major cryptocurrencies bitcoin , ethereum and litecoin as of now. We'll use coinbase api as coinbase is considered one of the best cryptocurrency exchanges. If you don't have an account on coinbase yet , you can create a free one here .
Pre-requisitesYou'll need the following tools to run code we're about to write in this tutorial:
- NPM and Node.js
- ExpressJS [ can be installed with command : npm install express --save ]
- Angular 4
- Coinbase Account [ create free coinbase account here ]
Note that prior knowledge of angular and express is assumed , if you're not familiar with these please visit the above tutorial links to get information. Action PlanFollowing is our action plan for this tutorial ::
- Create and configure an Oauth based app with Coinbase
- Create an angular 4 app
- Implement the Oauth based flow for user authentication
- Write supporting backend code using express
- Once authentication is done , perform requests and display results
- Suggestions for further expansion of the app
Lots to get done , let's get started.Create an App with CoinbaseWe first need an app with coinbase so we can interact with the coinbase api. Let's do that now:
- Visit https://developers.coinbase.com/ this link and click on the my apps button , as shown in the screenshot below.
- Click on the New Oauth2 App button
- Fill in the required details , give a name and description to your app along with other details , note that in order to follow this tutorial you've to fill the following value in the redirect url field:http://localhost:3000/callback
- When done , click on the Create application button to complete the process.
- Note down the CLIENT_ID and CLIENT_SECRET and Sample Authorize URL of your app from the information page that shows up. We'll require these details later on. [ Get full Code on Github ]
Great! , our coin base app is all setup , now let's go on and create an express app and add the relevant code to it. Create Express appCreate a file named server.js and add the following code to it. Don't forget to replace CLIENT_ID and CLIENT_SECRET placeholders with your actual client id and client secret that you got from coinbase app.
// server.js
const fs = require('fs');
const path = require('path');
const bodyParser = require("body-parser");
const express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var request = require('request');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/', express.static(path.join(__dirname, 'static')))
app.get('/callback', function(req, res) {
var q = req.query.code;
console.log(q);
var formdata = {
grant_type: 'authorization_code',
code: q,
client_id: 'YOUR_CLIENT_ID_HERE',
client_secret: 'YOUR_CLIENT_SECRET_HERE',
redirect_uri: 'http://localhost:3000/callback'
}
request.post({ url: 'https://api.coinbase.com/oauth/token', formData: formdata }, function(err, httpResponse, body) {
body = JSON.parse(body);
if (err) {
return console.error('upload failed:', err);
}
console.log('mission successful! Server responded with:', body);
var resbody = ' \
window.opener.postMessage("' + body.access_token + '","http://localhost:3000"); window.close() '
return res.send(resbody);
});
});
app.get('/user', function(req, res) {
var access_token = req.query.token;
console.log('token is ' + access_token);
request.get('https://api.coinbase.com/v2/user', {
'auth': {
'bearer': access_token
}
}).pipe(res);
})
// end point used to fetch account info
app.get('/accounts', function(req, res) {
var access_token = req.query.token;
request.get('https://api.coinbase.com/v2/accounts', {
'auth': {
'bearer': access_token
}
}).pipe(res);
})
server.listen(3000);
console.log('listening on 3000');
As you can see , the above app has 3 main endpoints ::
- Redirect url for authentication
- Fetching User's information
- Fetching Client's information
You can start the above server using the following command , it starts the app on http://localhost:3000
node server.js
Set up your angular 4 appWe have setup the coinbase app and the express app endpoints needed to support our application , now we'll create our angular app which will be the actual point of interaction for the user and it will also consume the api we created using express. Let's create our angular app using the following command :
ng new CryptoBazaar
Note that we've named our app CryptoBazaar , you can name yours whatever your feel suitable.Edit the App ComponentNow we'll edit our app component i.e. app.component.ts . Note that this file will be created when you execute the command mentioned in the above section. If you're not aware of the angular project structure or the location of different files , please visit this link first . Open the app.component.ts file and add following code.
import { Component } from '@angular/core';
// import the service class
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] ,
providers: [ AppService ]
})
export class AppComponent {
title = 'crypto bazaar';
isClassVisible = false;
name = '';
account_id = '';
account_name = '';
constructor(private appService : AppService ) {
}
startAuth = () => {
this.appService.startAuth()
.then( ( args ) => {
if(args == true) {
this.isClassVisible = true;
this.renderHome();
}
})
}
renderHome = () => {
this.appService.getUser()
.then( (args) => {
this.appService.getAccounts()
.then( ( account ) => {
this.name = args.data.name;
this.account_id = account.data[0].id;
this.account_name = account.data[0].name;
})
})
}
logout = () => {
this.isClassVisible = false;
}
}
Create the angular serviceAs you can see above , our app needs a service. you can create it using the following command.
ng g service app
The above command creates a new file app.service.ts in the app folder of your src directory. Just open this file and paste the following code. Don't forget to replace the placeholder YOUR_CLIENT_ID with your actual client id.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppService {
token:string = '';
constructor( private http: HttpClient ) {
this.token = '';
}
startAuth : any = () => {
var self = this;
return new Promise((resolve, reject) => {
var url = 'https://www.coinbase.com/oauth/authorize?client_id=YOUR_CLIENT_IDd&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&response_type=code&scope=wallet%3Auser%3Aread+wallet%3Aaccounts%3Aread';
var name = 'CryptoBazaar';
var params = 'width=800,height=600';
var popup = window.open(url , name , params );
window.addEventListener('message' , (msg) => {
if(msg.data) {
self.setToken(msg.data);
resolve(true);
}
else {
reject(false);
}
})
})
}
setToken = (token) => {
this.token = token;
}
getToken = () => {
return this.token;
}
getUser: any = () => {
return new Promise( ( resolve , reject ) => {
this.http.get('http://localhost:3000/user?token='+this.getToken()).subscribe(data => {
console.log(data);
resolve(data);
})
});
}
getAccounts: any = () => {
return new Promise( (resolve , reject) => {
this.http.get('http://localhost:3000/accounts?token='+this.getToken()).subscribe(data => {
console.log(data);
resolve(data);
})
})
}
}
The app.service.ts file has all the code required by our component file. Next we edit app.module.ts file. Open app.module.ts and add following code to it.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import {HttpClientModule} from '@angular/common/http';
import {
} from '@angular/material';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now open the app.component.html file and add following code to it.
<div [ngClass]="{'invisible': isClassVisible }">
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
</h1>
<img width="300" src="assets/logo.png" />
</div>
<hr>
<div class="parent">
<button mat-button (click)="startAuth()" class="btn btn-lg btn-success riobtn"> Start using Crypto Bazaar </button>
</div>
</div>
<div [ngClass]="{'invisible': !isClassVisible }">
<div class="home">
<h2> Welcome {{ name }} </h2>
<h3> Account Id :: {{ account_id }} </h3>
<h3> Account Name :: {{ account_name }} </h3>
<hr>
<button mat-button (click)="logout()" class="btn btn-lg btn-danger"> LogOut </button>
</div>
</div>
Note that we've skipped the css files here , you can find them in our github repo [ given below ] , also note that to keep our app simple we've simply sent back the access_token to client side [ which is a security risk if used in production ] , so don't try to use the same technique in anything close to a production environment.If you've set up the code , it's time to run it. First build your angular app with following command ::
ng build
You'll see that a dist folder has been created which contains all the files necessary to run our angular app in browser. Just copy the contents of dist folder and paste them in static directory [ see code on github ] of the express app we created above. If all works fine , you should see the app running and performing the operations we mentioned above. See the screenshots of the app in action below.Further ExpansionIn the code for express app , you can observe that we're calling coinbase api for users and accounts , we've used only a few endpoints to keep things simple , but you can perform more operations like ::
- Transactions involving BTC , ETH etc
- Buys and Selling of Bitcoin and Ethereum
- Deposits
- Withdrawls
All you have to do is to use the right HTTP verb and call the corresponding API end point and you've your required results.SummaryIn this minimal tutorial on creating a cryptocurrency app we touched upon the coinbase api and learned about authentication and getting user and accounts data. We hope you found it to be useful and helpful for further strengthening your knowledge on cryptocurrencies and how they work. You can get the complete code of the tutorial on github by following the link given below.
Hi @bitcoinburza, Thanks for the post. Can I please recommend you remove the unnecessary spaces from the code next time onwards as its making it hard to follow.
But the post itself is quite interesting. keep up the good work!!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit