【发布时间】:2018-10-04 23:07:29
【问题描述】:
我想开始在我的网站上接受比特币。
为了做到这一点,我编写了以下代码,但我真的很难理解在事务完成后如何实现正确的业务逻辑。
代码如下:
<html>
<head>
<title>Pay with Bitcoin</title>
<script>
//Gets the URL of the Webpage and gets the price value of this transaction in USD.
//For simplicity Here the Value is passed in the URL.
//However in production you wanna use POST instead of GET.
const myUrl = window.location.href;
const url = new URL(myUrl);
const usdPrice = url.searchParams.get("price");
//This is the function where all the magin happens
const showQR = () => {
//URL of the api which will provide us with current BTC exchange rate
const apiUrl = "https://blockchain.info/ticker";
const hr = new XMLHttpRequest();
hr.open('GET', apiUrl, true);
hr.onreadystatechange = function(){
//Make sure the API sent a valid response
if(hr.readyState == 4){
let ticker = JSON.parse(hr.responseText);
//Get last BTC/USD exchange value from the API , then convert Price from USD to BTC
let BTCprice = ticker.USD.last;
let btcToPay = usdPrice / BTCprice;
//Make sure you have just 8 decimal points in your BTC price!!
btcToPay = btcToPay.toFixed(8);
//Use google API (or other...) to create the QR code. Pass on your btc public address and
//the amount (btc price) dynamically created. Message and label parameters can be dynamic too.
let qrurl = "https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=bitcoin:1BAnkZn1qW42uRTyG2sCRN9F5kgtfb5Bci?amount="+btcToPay+"%26label=CarRental%26message=BookingID123456";
//Populate the 'btc' DIV with QR code and other info...
document.getElementById('btc').innerHTML = "<img src=" +qrurl+"><br> <span class = 'greenMoney'>" + usdPrice + " usd / " + btcToPay + " BTC </span>";
}
}
hr.send();
};
</script>
</head>
<body onload = "showQR()">
<h1>Pay with BitCoin</h1>
<div id = "btc">
</div>
</body>
</html>
此代码执行以下操作:
使用区块链 API 获取当前 USD/BTC 汇率。
获取 URL 的美元价格并将其转换为 BTC
使用 google API 生成二维码。
将价格、标签和信息嵌入二维码
在 DIV 中呈现二维码
我还设置了一个网络挂钩服务,它将监听指定钱包地址中发生的新交易。然后通过 POST 请求对我的服务器进行回调。
问题是:传递给二维码的标签和消息参数不会写入区块链。
它们只是客户方便的参考,以提醒他该特定交易支付的费用。
因此,对我的服务器的回调实际上是无用的。
事实上,回调不会返回任何预订 ID 或任何其他可以帮助我了解谁支付了哪些信息的信息。不用说,在这种情况下,业务逻辑是不可能的:我无法更新我的数据库中的订单状态,我无法向正确的客户发送确认电子邮件。
如何将相关信息(例如预订 ID)嵌入到 BTC 支付中,最好是通过二维码?
如果可能的话,我以后如何在我的服务器收到回调通知我有新的付款到我的 BTC 钱包时检索此信息?
【问题讨论】:
标签: javascript html blockchain webhooks bitcoin