Blockchain

使用 Blockchain PHP API 收到付款時如何更新索引?

  • January 9, 2017

我想開始在我的網站上接受比特幣付款,我得到了回調並且索引工作正常,唯一的問題是一旦收到付款它就不會更新索引,我想給使用者一些收到付款後的實時回饋,我該怎麼做?

下面是我得到的。

索引.php

<?php

$api_key = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx";

$xpub = "xpubxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

$secret = "xxxxxxxxxxxxxxxxxxxx";

$rootURL = "https://xxxxxxxxxx.org/BlockChain";

$orderID = uniqid();

$callback_url = $rootURL . "/callback.php?invoice=" . $orderID . "&secret=" . $secret . "&username=Teste" . "&password=qwerty123";
$receive_url = "https://api.blockchain.info/v2/receive?key=" . $api_key . "&xpub=" . $xpub . "&callback=" . urlencode($callback_url);

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $receive_url);
$ccc = curl_exec($ch);

$json = json_decode($ccc, true);

$payTo = $json['address'];

echo $payTo;

?>

回調.php

   $secret = "xxxxxxxxxxxxxxxxxxxx";

   if ($_GET['secret'] != $secret) {
       die("Stop doing that!");
   }

   else {
       //Register new user, insert more days, etc...

       //# START DEBUG #
       $fff = fopen("text.txt", "w");
       $value = $_GET['value'] . " - ";
       $fw = fwrite($fff, $value);

       $txhash = $_GET['transaction_hash'] . " - ";
       $fw = fwrite($fff, $txhash);

       $invoice = $_GET['invoice'] . " - ";
       $fw = fwrite($fff, $invoice);

       $value_in_btc = $_GET['value'] / 100000000 . " - ";
       $fw = fwrite($fff, $value_in_btc);

       $username = $_GET['username'] . " - ";
       $fw = fwrite($fff, $username);

       $password = $_GET['password'] . " - ";
       $fw = fwrite($fff, $password);

       fclose($fff);
       //# END DEBUG #

       echo "*ok*"; //Tell blockchain everything is ok, so they stop.
   }

   ?>

您的回調將更新您的伺服器,但使用者必須刷新頁面才能看到更改,或者您可以使用 AJAX(但這可能很浪費,因為它會發送多個請求直到有更新)。我建議您使用他們的 websocket API 來監控交易,以便您可以在頁面上實時通知使用者。

下面是一個簡單的範例,只需確保address使用要監視的地址更新變數即可。您可以將 PHP 輸出放在 javascript 中,例如 var address = <?php echo $payTo; ?>;

<html>
User Page<br>
<div id="notifications">Waiting for Payment...</div>
<script>
var address = "BTC_ADDRESS_TO_MONITOR";
var btcs = new WebSocket('wss://ws.blockchain.info/inv');
btcs.onopen = function(){
   btcs.send(JSON.stringify({"op":"addr_sub", "addr":address}));
};
btcs.onmessage = function(onmsg)
{
 var response = JSON.parse(onmsg.data);
 var getOuts = response.x.out;
 var countOuts = getOuts.length; 
 for(i = 0; i < countOuts; i++)
 {
   //check every output to see if it matches specified address
   var outAdd = response.x.out[i].addr;
   var specAdd = address;
      if (outAdd == specAdd)
      {
      var amount = response.x.out[i].value;
      var calAmount = amount / 100000000;
      document.getElementById("notifications").innerHTML = "Received: " + calAmount + "BTC";
      };
 }; 
}
</script>
</html>

引用自:https://bitcoin.stackexchange.com/questions/50673