Difference between revisions of "PHP developer intro"

From Bitcoin Wiki
Jump to: navigation, search
m (Accounts: typo fix)
Line 1: Line 1:
 
'''L'''inux '''A'''pache '''M'''ySQL '''P'''HP + Bitcoin tutorial.
 
'''L'''inux '''A'''pache '''M'''ySQL '''P'''HP + Bitcoin tutorial.
  
For the sake of this tutorial we assume an Ubuntu server running with PHP. The use case here is integrating a shopping system to accept Bitcoins. We assume some knowledge of Bitcoin and experience in PHP.
+
For this introduction we assume that you have GNU/Linux server with Apache and PHP and that you wish to interact with the Bitcoin network from a web application. We assume some knowledge of Bitcoin and experience in PHP.
  
You can substitute any other language here for PHP. See the associated [[API reference (JSON-RPC)|API reference]] pages for info on other languages.
+
While this is written for PHP, the same principles apply for other languages. See the associated [[API reference (JSON-RPC)|API reference]] pages for info on other languages.
  
You will run Bitcoin in daemon mode. The way PHP communicates is through localhost HTTP requests. You use a library called [http://jsonrpcphp.org/ JSON-RPC] to call the various functions. It will respond back with a [http://en.wikipedia.org/wiki/Json JSON object].
+
The easiest way to get started is to run Bitcoin in daemon mode with which PHP communicates via local HTTP requests. A library called [http://jsonrpcphp.org/ JSON-RPC] is used to call the various functions of bitcoind, which will respond back with a [http://en.wikipedia.org/wiki/Json JSON object].
  
 
== Setting up Bitcoin ==
 
== Setting up Bitcoin ==
  
You need the bitcoind command-line daemon.  You can either compile it from source or download a binary from the bitcoin.org homepage.
+
You can download the Bitcoin daemon from the [[Main_Page|homepage]] and run one of the included binaries or compile your own from the included source code. See [[Running Bitcoin]] for details on configuring bitcoind.
  
See [[Running Bitcoin]] for details on configuring bitcoin.
+
Before running bitcoind you will need to create a configuration file in the Bitcoin data directory (~/.bitcoin/bitcoin.conf on Linux):
 
 
Before running bitcoind you will need to create a file in the bitcoin data directory (~/.bitcoin/bitcoin.conf on Linux):
 
 
<source lang="bash">
 
<source lang="bash">
 
rpcuser=user
 
rpcuser=user
 
rpcpassword={you MUST pick a unique password to be secure}
 
rpcpassword={you MUST pick a unique password to be secure}
 
</source>
 
</source>
 +
If you miss this step, bitcoind will remind you.
  
 
Now run bitcoind:
 
Now run bitcoind:
Line 24: Line 23:
 
# wait a few seconds for it to start up
 
# wait a few seconds for it to start up
 
$ ./bitcoind getinfo
 
$ ./bitcoind getinfo
# various info shown
+
# various information will be shown. If you get an error, try again until you see some useful output.
 
$ ./bitcoind help
 
$ ./bitcoind help
# help on commands
+
# get help on commands, note no dash before help
 
</source>
 
</source>
  
Bitcoin is now initialising and you must wait until "blocks" is at the [http://blockexplorer.com/q/getblockcount current count].
+
Bitcoin will begin synchronizing with the network and downloading a complete copy of the block chain. As of August 2012, more than 2gb of data must be downloaded and verified during this process. It may take two or more hours to complete. You will know when it's done when the block count reaches the [http://blockexplorer.com/q/getblockcount current count].
 +
 
 +
== Getinfo (Bitcoind's version of Hello World) ==
  
== First steps ==
+
Assuming Bitcoin has finished the initialisation process; download the file jsonRPCClient.php from [http://jsonrpcphp.org/ JSON-RPC PHP] and place it in a web-accessible location.
  
Assuming Bitcoin has finished the initialisation process; download the file jsonRPCClient.php from [http://jsonrpcphp.org/ JSON-RPC PHP]. The other files can be safely discarded.
+
Second, create a PHP file with the following and visit it with your browser to test.
  
 
<source lang="php">
 
<source lang="php">
Line 47: Line 48:
 
== Precision ==
 
== Precision ==
  
Bitcoin amounts can range from 1 (0.00000001 BTC) to nearly 2,100,000,000,000,000 (21,000,000 BTC).  To avoid rounding errors, you must make sure your PHP implementation supports the full range of bitcoin values without losing precision.  Most PHP implementations use IEEE 64-bit double-precision floating point numbers, which have 53 bits of precision, which is enough to correctly represent the full range of bitcoin values.
+
Bitcoin amounts can range from 1 (0.00000001 BTC) to nearly 2,100,000,000,000,000 (21,000,000 BTC).  To avoid rounding errors, you must make sure your PHP implementation supports the full range of Bitcoin values without losing precision.  Most PHP implementations use IEEE 64-bit double-precision floating point numbers with 53 bits of precision, which is enough to correctly represent the full range of bitcoin values.
  
 
See [[Proper Money Handling (JSON-RPC)]] for more information.
 
See [[Proper Money Handling (JSON-RPC)]] for more information.

Revision as of 03:01, 10 August 2012

Linux Apache MySQL PHP + Bitcoin tutorial.

For this introduction we assume that you have GNU/Linux server with Apache and PHP and that you wish to interact with the Bitcoin network from a web application. We assume some knowledge of Bitcoin and experience in PHP.

While this is written for PHP, the same principles apply for other languages. See the associated API reference pages for info on other languages.

The easiest way to get started is to run Bitcoin in daemon mode with which PHP communicates via local HTTP requests. A library called JSON-RPC is used to call the various functions of bitcoind, which will respond back with a JSON object.

Setting up Bitcoin

You can download the Bitcoin daemon from the homepage and run one of the included binaries or compile your own from the included source code. See Running Bitcoin for details on configuring bitcoind.

Before running bitcoind you will need to create a configuration file in the Bitcoin data directory (~/.bitcoin/bitcoin.conf on Linux):

rpcuser=user
rpcpassword={you MUST pick a unique password to be secure}

If you miss this step, bitcoind will remind you.

Now run bitcoind:

$ ./bitcoind
# wait a few seconds for it to start up
$ ./bitcoind getinfo
# various information will be shown. If you get an error, try again until you see some useful output.
$ ./bitcoind help
# get help on commands, note no dash before help

Bitcoin will begin synchronizing with the network and downloading a complete copy of the block chain. As of August 2012, more than 2gb of data must be downloaded and verified during this process. It may take two or more hours to complete. You will know when it's done when the block count reaches the current count.

Getinfo (Bitcoind's version of Hello World)

Assuming Bitcoin has finished the initialisation process; download the file jsonRPCClient.php from JSON-RPC PHP and place it in a web-accessible location.

Second, create a PHP file with the following and visit it with your browser to test.

  require_once 'jsonRPCClient.php';
  
  $bitcoin = new jsonRPCClient('http://user:password@127.0.0.1:8332/');
   
  echo "<pre>\n";
  print_r($bitcoin->getinfo());
  echo "</pre>";

Precision

Bitcoin amounts can range from 1 (0.00000001 BTC) to nearly 2,100,000,000,000,000 (21,000,000 BTC). To avoid rounding errors, you must make sure your PHP implementation supports the full range of Bitcoin values without losing precision. Most PHP implementations use IEEE 64-bit double-precision floating point numbers with 53 bits of precision, which is enough to correctly represent the full range of bitcoin values.

See Proper Money Handling (JSON-RPC) for more information.

If your PHP implementation does not support 64-bit numbers (again, this is very rare), you must use a version of bitcoind that sends values as strings (genjix maintains a fork at http://github.com/genjix/bitcoin) and use the GMP and BC Math libraries for all calculations involving bitcoin amounts.

Accounts

In Bitcoin, money is sent to addresses. Your balance is the total of all the money in all the addresses in your wallet.

Bitcoin goes another step. You can have accounts. Each account holds multiple addresses and acts like a mini-Bitcoin.

$ ./bitcoind listaccounts
# show list of accounts and various info for each one
$ ./bitcoind getaccountaddress user889
# get an address to receive money to that is unique for the account user889
$ ./bitcoind getbalance user889
# get the sum of all the money in the addresses owned by the account user889

In your shopping system, each user should have a unique username. You then query bitcoin for a unique address using $bitcoin->getaccountaddress("user889"); [gets the first address for user889] or $bitcoin->getnewaddress("user889"); [creates a new address for user889].

The customer then deposits to this address.

You can check the funds for that customer by doing $bitcoin->getbalance("user889", 4);. The 4 indicates the minimum number of confirmations we will accept before assuming this payment is valid.

getnewaddress vs getaccountaddress

Using getnewaddress helps increase the anonymity of your customers by making it hard to track their payments from the POV of a malicious agent. However running it too often will cause your wallet to become filled with many empty addresses.

I recommend that you do something like:

<?php
    require_once('jsonRPCClient.php');
    $bitcoin = new jsonRPCClient('http://root:root@127.0.0.1:8332/'); 
    # now check for appropriate funds in user account
    try {
        $username = ...
        if(isset($_SESSION['sendaddress']))
            $sendaddress = $_SESSION['sendaddress'];
        else {
            $sendaddress = $bitcoin->getnewaddress($username);
            $_SESSION['sendaddress'] = $sendaddress;
        }
        $balance = $bitcoin->getbalance($username);
    }
    catch (Exception $e) {
        die("<p>Server error! Please contact the admin.</p>");
    }
?>

This creates a new address at the beginning of every new session, and stores it in the session variable.

See Also