需要:
1. 以太坊节点服务器
2. jsonrpc 接口 eth_sendTransaction ,personal_unlockAccount,personal_lockAccount
3. 组装jsonrpc 发送请求数据 (1:解锁账户, 2:发起交易 ,3: 锁定账户)
4. 发送请求
地址: http://localhost
端口:8545
节点服务器搭建请看 : 以太坊代币usdt节点搭建.
eth_sendTransaction 发起转账
from: DATA, 20字节 - 发送交易的源地址
to: DATA, 20字节 - 交易的目标地址,当创建新合约时可选
gas:QUANTITY - 交易执行可用gas量,可选整数,默认值90000,未用gas将返还。
gasPrice: QUANTITY -gas价格,可选,默认值:待定(To-Be-Determined)
value: QUANTITY - 交易发送的金额,可选整数
data:DATA - 合约的编译带啊或被调用方法的签名及编码参数
nonce: QUANTITY - nonce,可选。可以使用同一个nonce来实现挂起的交易的重写
personal_unlockAccount 解锁账户
QUANTITY -解锁地址
QUANTITY -解锁地址密码
personal_lockAccount 锁定账户
QUANTITY -锁定地址
jsonprc 公用参数
$opts = [
'jsonrpc' => '2.0',
'method' => '',
'params' => [],
'id' => time()
];
curl post 请求
/**
* @param $url 节点url 地址 "http://localhost:8845"
* @param $post_data 发起请求post数据 $opts
* @return array
*/
function curlPost( $url, $post_data )
{
$curl = curl_init();
$jsonStringData = json_encode( $post_data );
$options = [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0",
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: ' . strlen( $jsonStringData )
],
];
curl_setopt_array( $curl, $options );
//设置post数据
curl_setopt( $curl, CURLOPT_POSTFIELDS, $jsonStringData );
//执行命令
$data = curl_exec( $curl );
//关闭URL请求
if ( $data ) {
curl_close( $curl );
$res_data = json_decode( $data, true );
return ['status' => true, 'data' => $res_data];
} else {
$error = curl_errno( $curl );
curl_close( $curl );
return ['status' => false, 'data' => '', 'msg' => $error];
}
}
先解锁账户
$opts = [
'jsonrpc' => '2.0',
'method' => 'personal_unlockAccount', //解锁账户接口
'params' => [
'0xb60e8dd61c5d32be8058bb8eb970870f07233155', //解锁账户地址
'123456' //账户密码
],
'id' => time()
];
解锁账户常见错误
发起交易
$opts = [
'jsonrpc' => '2.0',
'method' => 'eth_sendTransaction', //转账接口
'params' => [
0=>[
'from' =>'0xb60e8dd61c5d32be8058bb8eb970870f07233155',//转账地址
'to' => '0xdac17f958d2ee523a2206206994597c13d831ec7', //收款地址
'value'=>'0x'.dechex('1000000000000000000'),
//转账金额1eth 1* 1000000000000000000 , eth小数位为18位
'gas'=>'0x' . dechex( '21000' ),, // 21000 可根据自己修改, 少的话,交易失败率高
'gasPrice'=>'0x' . dechex( '1000000000' ), //同 gas
],
],
'id' => time()
];
转账结果
array(2) {
["status"] => bool(true)
["data"] => array(3) {
["jsonrpc"] => string(3) "2.0"
["id"] => int(1574131996)
["result"] => string(66) "0xa284222543831e4ad0c363c0c6eadd94f25f829150e0fbb37680c54c6ccacc6c"
}
}
// result 为交易hash
锁定账户
$opts = [
'jsonrpc' => '2.0',
'method' => 'personal_lockAccount', //锁定账户接口
'params' => [
'0xb60e8dd61c5d32be8058bb8eb970870f07233155' //锁定账户地址
],
'id' => time()
];
交易结束