Lucas A.
Lucas A.

Reputation: 99

How to receive bitcoin payments using bitcoinjs-lib in node js

Basically I've been trying to figure out how to use bitcoinjs-lib to have a quick and easy wallet (in node js). This program isn't gonna be a full fledged wallet, it just needs to be able to tell when a bitcoin address receives payment and how much it's gotten.

Upvotes: 1

Views: 1933

Answers (1)

Kostas Minaidis
Kostas Minaidis

Reputation: 5517

You can use the WebSocket service by Blockchain.info to get an update on an address and then calculate the total amount received through the outputs:

var WebSocket = require('ws');
var btcWS = new WebSocket("wss://ws.blockchain.info/inv");
var BTC_ADDR = "1FoxBitjXcBeZUS4eDzPZ7b124q3N7QJK7";

// NOTIFY ON ADDRESS UPDATE
btcWS.onopen = function(){ btcWS.send(JSON.stringify({ "op": "addr_sub", "addr" : BTC_ADDR })); };

// WE GOT AN UPDATE
btcWS.onmessage = function(msg){

    var response  = JSON.parse(msg.data);
    var getOuts   = response.x.out;

    // LET'S CHECK THE OUTPUTS
    getOuts.map(function(out,i){

        if ( BTC_ADDR == out.addr ){

            var amount = out.value;
            var calAmount = amount / 100000000;
            console.log(calAmount + " BTC");    // <-- The total amount just received

        }

    });

};

btcWS.onerror = function (error){ console.log('connection.onerror', error); };

Upvotes: 1

Related Questions