Not the most elegant solution, but should work. You have to replace the key, secret and client id on the first line.
Of course you also need to specify the amount of USD you want to buy and the destination Bitcoin address.
/**
* BitStamp Order and Withdraw
* https://bitcointalk.org/index.php?topic=2102954.msg21033624#msg21033624
**/
function bitstamp_query($path, array $req = array(), $verb = 'post', $key="KEY_HERE", $secret="SECRET_HERE", $client_id="CLIENT_ID_HERE"){
// generate a nonce as microtime, with as-string handling to avoid problems with 32bits systems
$mt = explode(' ', microtime());
$req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
$req['key'] = $key;
$req['signature'] = bitstamp_get_signature($req['nonce'],$key,$secret,$client_id);
// generate the POST data string
$post_data = http_build_query($req, '', '&');
// any extra headers
$headers = array();
// our curl handle (initialize if required)
static $ch = null;
if (is_null($ch)){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; BitStamp PHP Client');
}
curl_setopt($ch, CURLOPT_URL, 'https://www.bitstamp.net/api/' . $path .'/');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); // man-in-the-middle defense by verifying ssl cert.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // man-in-the-middle defense by verifying ssl cert.
if ($verb == 'post'){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// run the query
$res = curl_exec($ch);
if ($res === false)
return false;
$dec = json_decode($res, true);
if (is_null($dec))
return false;
return $dec;
}
function bitstamp_get_signature($nonce,$key,$secret,$client_id){
$message = $nonce.$client_id.$key;
return strtoupper(hash_hmac('sha256', $message, $secret));
}
// Amount of USD to buy
$bitstamp_usd_amount=USD_AMOUNT_HERE;
// Bitcoin address to send to
$bitstamp_bitcoin_address="DESTINATION_BITCOIN_ADDRESS_HERE";
$bitstamp_eurusd=bitstamp_query("eur_usd",array(),"get");
$bitstamp_eur_amount=$bitstamp_usd_amount/$bitstamp_eurusd["buy"];
$bitstamp_buy_order=bitstamp_query("v2/buy/market/btceur",array("amount"=>$bitstamp_eur_amount));
$bitstamp_ordered_amount=$bitstamp_buy_order["amount"];
print_r(bitstamp_query("bitcoin_withdrawal",array(
"amount" => $bitstamp_ordered_amount,
"address" => $bitstamp_bitcoin_address,
"instant" => 0 // set to 1 to send a BitGo instant payment. An additional fee apply.
)));
// get balance
print_r(bitstamp_query("balance",array()));
My Bitcoin address: 3KRvcgq8odGDN4DXN9iLpEMnE4mseVbmyP
Derived from
a class made for BitStamp.