Merchant side

To start off, we build a basic Node.js server accepting HTTP and HTTPS requests using our generated certificates. As this book is not about either Node.js or JavaScript, I'll put the main emphasis on presenting the code related to bitcoin and the bitcore library. For now, let's start building our web server:

'use strict';
var bitcore_lib = require('bitcore-lib');
var PaymentProtocol = require('bitcore-payment-protocol');
var express = require('express');
var bodyParser = require('body-parser');
var URI = require('bitcore-lib/lib/uri');
var request = require("request");
const https = require('https');
var fs = require("fs");

var dcert = fs.readFileSync('./keys/cert.der');
var mcert = fs.readFileSync('./keys/cert.pem'); // For HTTPS server
var mkey = fs.readFileSync('./keys/key.pem');

var credentials = {key: mkey, cert: mcert};
var app = express();
var os = require('os');
var interfaces = os.networkInterfaces();
var addresses = [];
for (var k in interfaces) {
for (var k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address);
}
}
}

var IP = addresses[0];
var port = 8883;
var http_port = 3000;

app.get("/", function(req, res) {
res.send('Bitcoin Payment protocol');
});

app.listen(http_port, function() {
console.log("-http Server listening on :"+IP+":"+ http_port);
});

https.createServer(credentials, app).listen(port, function() {
console.log("-https Server listening on :"+IP+":"+ port);
});

This big chunk of code creates a simple Node.js server to serve the HTTP requests. Save this code in a file named server.js  and run it with node server.js. Your server will start and listen on two different ports: 3000 for HTTP and 8883 for HTTPS.

You might get the error  Error: More than one instance of bitcore-lib found; in this case, refer to https://github.com/bellaj/Bitcoin_payment, where I propose a sketchy workaround.

Since the certificate is self-signed, if you open any browser to the server's address with port 8883, it will yield a warning, and not allow the communication to continue without an explicit exception. To solve that, you have to manually install the certificate (cert.der) into your browser. Next, try to visit locally http://localhost:3000; the browser window should display a Bitcoin Payment protocol message.

Before we move on, stop the running server by pressing Ctrl + C in the server's Terminal window. Let's expand our code to make use of the bitcore library to create the payment request.