當我第一次考慮經過加密貨幣實施支付時,我查看了像Stripe這樣的可用解決方案。我以爲Stripe的問題在於,它只容許使用美國商家賬戶進行比特幣支付,因此這對我來講不是一個選擇。在以太坊世界,它看起來更糟糕。有一些較新的服務,但他們都想要分享蛋糕。php
那麼從頭開始構建以太坊支付系統,咱們須要什麼?node
咱們將使用nodejs中的vanity-eth來生成地址。git
npm install -g vanity-eth@1.0.4"
在Windows上安裝vanity-eth後:github
還須要一些Etherum節點。我正在使用Parity,由於它快速可靠。npm
使用這些參數啓動它,但不要將節點直接暴露給Internet,將它們保留在防火牆後面而不進行端口轉發。json
parity --jsonrpc-interface 0.0.0.0 --jsonrpc-hosts="all" --auto-update=all --jsonrpc-cors null
完成同步的奇偶校驗日誌:後端
爲了更快地部署,您可使用Parity Docker容器。還能夠保存數據,這樣每次從新制做容器時都沒必要從新同步。api
首先建立一個名爲libs
的文件夾,而後將php-ethereum repo克隆到其中。ethereum-php項目是json-rpc類的一個很好的封裝。服務器
而後咱們使用如下類並將其另存爲ethpay.php。這是支付處理的主要邏輯。你能夠用它來:網絡
<?php define('RPC_IP','127.0.0.1'); define('RPC_PORT',8545); require 'libs/ethereum-php/ethereum.php'; $e = new EthPay(); class EthPay { private $eth; //讓咱們創建與parity節點的鏈接 function __construct() { $this->eth = new Ethereum(RPC_IP, RPC_PORT); if(!$this->eth->net_version()) die('RPC ERROR'); } / * *獲得一個地址的餘額, *來自parity的餘額以十六進制形式出如今wei中 *使用bc數學函數轉換它 * / function getBalanceOfAddress($addr) { $eth_hex = $this->eth->eth_getBalance($addr, 'latest'); $eth = $this->wei2eth($this->bchexdec($eth_hex)); $pending_hex = $this->eth->eth_getBalance($addr, 'pending'); $pending = $this->wei2eth($this->bchexdec($pending_hex)); return array('balance'=>$eth,'pending'=>$pending); } function getCurrentPrice($currency='USD') { $data = json_decode(file_get_contents('https://api.coinbase.com/v2/prices/ETH-'.$currency.'/spot'),true); return $data['data']['amount']; } /* *咱們將使用vanityeth生成私鑰對 * npm install -g vanity-eth *咱們必須從新格式化輸出字符串以用做JSON * / function genPair() { exec('vanityeth', $outputAndErrors, $return_value); $answer = implode(NULL,$outputAndErrors); $answer = str_replace('address:','"address":',$answer); $answer = str_replace('privKey:','"privKey":',$answer); $answer = str_replace('\'','"',$answer); return json_decode($answer,true); } //如下功能用於轉換和處理大數字 function wei2eth($wei) { return bcdiv($wei,1000000000000000000,18); } function bchexdec($hex) { if(strlen($hex) == 1) { return hexdec($hex); } else { $remain = substr($hex, 0, -1); $last = substr($hex, -1); return bcadd(bcmul(16, $this->bchexdec($remain)), hexdec($last)); } } }
根據您的服務,有多種方法能夠執行此操做。
在API Heaven,咱們爲每位客戶提供一個能夠存入資金的ETH地址。cronjob每分鐘檢查全部客戶地址以檢測更改。若是他們將ETH添加到地址,則餘額將轉換爲API配額,所以咱們的客戶甚至不須要登陸該站點來添加資金。
API Heaven中的示例集成:
另外一個方法是計算固訂價格並將其保存在用戶會話中。客戶必須在網站上付款,而且您須要向AJAX查詢已收到的付款。若是收到所有金額,後端會觸發銷售。
最重要的是,您不須要外部服務來在您的網站上集成以太坊支付系統。來一塊兒邊學邊玩以太坊吧。
學習php以太坊開發的也能夠支持下個人課程:http://t.cn/RrRAlAO,謝謝!