Blockchain By Example
上QQ阅读APP看书,第一时间看更新

Building a payment request URI

First off, we define the testnet as the default network for our application and a merchant address. Simply put within the server's code the following lines:

bitcore_lib.Networks.defaultNetwork = bitcore_lib.Networks.testnet; // the project runs only on testnet
var Merchant_address = "mhc5YipxN6GhRRXtgakRBjrNUCbz6ypg66";

In this example, we used a static bitcoin address but in a real implementation, the merchant has to generate a unique payment address associated with the customer's order. Alternatively, you can generate a random address using the following:

var privateKey = bitcore_lib.PrivateKey(merchant_pkey); // we pass a specific private key as argument
var publicKey = bitcore_lib.PublicKey(privateKey);
bitcore_lib.Address(publicKey, bitcore_lib.Networks.defaultNetwork ));

We then define a simple function, compose_uri(), to build the bitcoin payment URI:

function compose_uri(amount_to_pay) {
var pay_url = "http://"+IP+":"+http_port+"/request";
var uriString = new URI({
address: Merchant_address,
amount : amount_to_pay, // amount in satoshis
message: 'payment request'
});
var paymentUri = uriString+"&r="+pay_url;
return paymentUri;
}

The compose_uri() function generates the request payment URI starting with the prefix bitcoin: (defined in BIP 21), and containing the destination and amount. The overall URI is a BIP-72-style with the special query parameter rwhich specifies from where the payment request will be fetched from. Custom URIs are very helpful as browsers and mobile apps use them to launch the registered protocol handler, in this case a bitcoin client.

So now that we have all that up and running, it's time to actually handle requests.