web3.php 是一个 PHP 接口,主要用于与以太坊区块链及其生态系统进行交互
安装:通过 Composer 来管理依赖关系,首先将 minimum-stability 设置为 dev
"minimum-stability": "dev"
然后执行:
composer require sc0vu/web3.php dev-master
或者你可以在 composer.json 中添加这行
"sc0vu/web3.php": "dev-master"
用法
实例
use Web3\Web3;
$web3 = new Web3('http://localhost:8545');
接口调用
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
$web3 = new Web3(new HttpProvider(new HttpRequestManager('http://localhost:8545')));
// timeout
$web3 = new Web3(new HttpProvider(new HttpRequestManager('http://localhost:8545', 0.1)));
使用回调函数调用 rpc
$web3->clientVersion(function ($err, $version) {
if ($err !== null) {
// do something
return;
}
if (isset($client)) {
echo 'Client version: ' . $version;
}
});
ETH
use Web3\Web3;
$web3 = new Web3('http://localhost:8545');
$eth = $web3->eth;
ETH
use Web3\Eth;
$eth = new Eth('http://localhost:8545');
NET
use Web3\Web3;
$web3 = new Web3('http://localhost:8545');
$net = $web3->net;
NET
use Web3\Net;
$net = new Net('http://localhost:8545');
batch
web3
$web3->batch(true);
$web3->clientVersion();
$web3->hash('0x1234');
$web3->execute(function ($err, $data) {
if ($err !== null) {
// do something
// it may throw exception or array of exception depends on error type
// connection error: throw exception
// json rpc error: array of exception
return;
}
// do something
});
ETH
$eth->batch(true);
$eth->protocolVersion();
$eth->syncing();
$eth->provider->execute(function ($err, $data) {
if ($err !== null) {
// do something
return;
}
// do something
});
NET
$net->batch(true);
$net->version();
$net->listening();
$net->provider->execute(function ($err, $data) {
if ($err !== null) {
// do something
return;
}
// do something
});
personal
$personal->batch(true);
$personal->listAccounts();
$personal->newAccount('123456');
$personal->provider->execute(function ($err, $data) {
if ($err !== null) {
// do something
return;
}
// do something
});
智能合约 Contract
use Web3\Contract;
$contract = new Contract('http://localhost:8545', $abi);
// deploy contract
$contract->bytecode($bytecode)->new($params, $callback);
// call contract function
$contract->at($contractAddress)->call($functionName, $params, $callback);
// change function state
$contract->at($contractAddress)->send($functionName, $params, $callback);
// estimate deploy contract gas
$contract->bytecode($bytecode)->estimateGas($params, $callback);
// estimate function gas
$contract->at($contractAddress)->estimateGas($functionName, $params, $callback);
// get constructor data
$constructorData = $contract->bytecode($bytecode)->getData($params);
// get function data
$functionData = $contract->at($contractAddress)->getData($functionName, $params);
将值分配给外部域(从回调域到域外)
由于和 javascript 回调不同,如果需要将值赋值到域外,我们需要给回调赋值。
$newAccount = '';
$web3->personal->newAccount('123456', function ($err, $account) use (&$newAccount) {
if ($err !== null) {
echo 'Error: ' . $err->getMessage();
return;
}
$newAccount = $account;
echo 'New account: ' . $account . PHP_EOL;
});