手记

PHP调用Web3实现转账交易量化

php也可以调用web3相关接口进行转账交易,唯一需要注册的就是 https://developer.metamask.io/  开发者网站 ,获得一个密钥,然后就可以调用了,首先:

composer require web3p/web3.php:0.2.1
composer require blockchainethdev/ethereum-tx


获取免费RPC地址的方法
通过MetaMask开发者网站注册 访问 MetaMask开发者网站,可以注册并获取免费的RPC地址。该网站提供了与MetaMask钱包集成的详细文档和资源,包括RPC配置信息。

使用Chainlist查找免费RPC 访问 Chainlist,搜索目标网络(如Ethereum Mainnet)。Chainlist会列出多个可用的免费RPC URL,用户可以根据需求选择合适的节点。

验证RPC可用性 在选择RPC URL后,建议测试其响应速度和稳定性。可以通过简单的API调用或钱包连接测试,确保节点可用。

配置钱包使用RPC 将获取的RPC URL配置到钱包(如MetaMask)中。通常需要输入链ID、网络名称和符号信息,具体参数可在ChainlistMetaMask文档中找到。

注意事项 部分免费RPC可能有请求限制或延迟问题。对于高频使用的场景,建议选择多个备用节点或考虑付费服务以提高可靠性。


下面示例在php 7.3.33版本运行正常测试通过,其他版本请自行测试是否能用。

下面是一些简单的示例:

<?php
require('vendor/autoload.php');
use Web3\Web3;
use Web3\Contract;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
use Blockchainethdev\EthereumTx\Transaction;
define('your_private_key','96991d589fe5fbb2decd399c01d8912d05e1b82ab037472ec46a5f61840dfb91');
define('your_wallet_address','0x9411B02906FE57C8E7f8597F888AA358aDC7a410');
define('chainId',1);
/*
 * 其他网络的chainId如下:
 * Ethereum Mainnet : 1
 * BNB Smart Chain Mainnet : 56
 * Arbitrum One : 42161
 * Polygon Mainnet : 137
 * OP Mainnet : 10
 *
 * 可以去 https://chainlist.org/zh 查看其他网络id
 */
//在 https://infura.io 注册获得免费的rpc地址,也可以去 https://chainlist.org/zh
// 找到对应的网络比如 Ethereum Mainnet 然后可以找到很多免费的RPC URL
$Web3 = new Web3(new HttpProvider(new HttpRequestManager("https://mainnet.infura.io/v3/{密钥}")));
define('usdt_address','0xdAC17F958D2ee523a2206206994597C13D831ec7');
define('wbtc_address','0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599');
define('erc20_abi','[{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]');
$Eth = $Web3->getEth();
function get_eth_balance($owner_address){
    /*
    获取指定账户的eth余额
    owner_address: 指定账户地址

    :return:账户余额
    */
    global $Eth;
    $Eth->getBalance($owner_address, function ($err, $balance) {
        if ($err !== null) {
        }
        echo 'Balance: ' . $balance->toString() . PHP_EOL;
    });
}
function get_erc20_balance($erc20_address, $owner_address){
    /*
    获取指定账户的erc20代币余额
    erc20_address:erc20合约地址
    owner_address: 指定账户地址

    :return:账户erc20代币余额
    */
    global $Web3;
    $contract = new Contract($Web3->getProvider(), erc20_abi);
    $contract->at($erc20_address)->call("balanceOf", $owner_address, function ($err, $balance) {
        if ($err !== null) {
        }
        echo 'Balance: ' . $balance[0]->toString() . PHP_EOL;
    });
}
function transfer_eth($to_address, $amount){
    /*
    发送指定数量的eth给指定地址
    to_address:接收方地址
    amount:发送eth数量
    */
    global $Eth;
    $Eth->getTransactionCount(your_wallet_address, function ($err, $transactionCount)use($to_address,$Eth,$amount) {
        if ($err !== null) {
            return print_r($err);
        }
        $Eth->gasPrice(function ($err, $gasPrice)use($transactionCount,$to_address,$Eth,$amount) {
            if ($err !== null) {
                return print_r($err);
            }
            $nonce = $transactionCount->toString();
            $transaction = new Transaction([
                'nonce' => intval($nonce),
                'from' => your_wallet_address,
                'to' => $to_address,
                'gas' => 21000,
                'gasPrice' => intval($gasPrice->toString()),
                'value' => $amount,
                'chainId' => chainId, // optional
            ]);
            $sign_data = $transaction->sign(your_private_key);
            $Eth->sendRawTransaction("0x".$sign_data, function ($err, $transaction) {
                print_r([$err,$transaction]);
                if ($err !== null) {
                    print_r($err);
                }
                echo 'tx id: ' . $transaction . PHP_EOL;
            });
        });

    });
}
function contract_call($from_address,$contract_address,$callData){
    global $Eth;
    $transaction_dict =[
        'from' => $from_address,
        'to' => $contract_address,
        'data' => $callData
    ];
    $Eth->getTransactionCount(your_wallet_address, function ($err, $transactionCount)use($contract_address,$callData,$Eth,$transaction_dict) {
        if ($err !== null) {
            //print_r($err);
        }
        $nonce = $transactionCount->toString();
        $transaction_dict['nonce'] = intval($nonce);
        $Eth->gasPrice(function ($err, $gasPrice)use($nonce,$contract_address,$callData,$Eth,$transaction_dict) {
            $Eth->estimateGas($transaction_dict, function ($err, $gas)use($gasPrice,$Eth,$transaction_dict) {
                if ($err !== null) {
                    //print_r($err);
                    exit(1);
                }
                $transaction_dict['gasPrice'] =intval($gasPrice->toString());
                $transaction_dict["gas"] = intval($gas->toString());
                $transaction_dict["chainId"] = chainId;
                $transaction = new Transaction($transaction_dict);
                $sign_data = $transaction->sign(your_private_key);
                $Eth->sendRawTransaction("0x".$sign_data, function ($err, $transaction) {
                    if ($err !== null) {
                        //print_r($err);
                        exit(1);
                    }
                    echo 'tx id: ' . $transaction . PHP_EOL;
                });
            });
        });
    });
}
function transfer_erc20($erc20_address, $to_address, $amount){
    /*
    发送erc20代币给指定地址指定数量
    erc20_address:erc20代币合约地址
    to_address:接收方地址
    amount:发送erc20代币数量
     */
    global $Web3;
    $contract = new Contract($Web3->getProvider(), erc20_abi);
    $callData = $contract->getData("transfer",$to_address , $amount);
    contract_call(your_wallet_address,$erc20_address,"0x".$callData);
}
function approve($erc20_address, $approve_contract_address, $approve_amount){
    /*
    授权给指定地址指定数量的消费额度
    erc20_address: erc20代币地址
    approve_contract_address:指定的其他消费代币的合约地址
    approve_amount:授权数量
     */
    global $Web3;
    $contract = new Contract($Web3->getProvider(), erc20_abi);
    $callData = $contract->getData("approve",$approve_contract_address , $approve_amount);
    contract_call(your_wallet_address,$erc20_address,"0x".$callData);
}

//# 获取账户eth余额
get_eth_balance(your_wallet_address);
//# 获取账户usdt余额
get_erc20_balance(usdt_address,your_wallet_address);
//# 发送1个以太坊给 0x95341E8d48ebCF212e0Eb8a314244Ba0cdFC85B5
transfer_eth("0x95341E8d48ebCF212e0Eb8a314244Ba0cdFC85B5",1*pow(10,16));
//# 发送1usdt 给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707
transfer_erc20(usdt_address,"0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707",1*pow(10,6));
//# 给 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 授权 10btc的消费额度
approve(wbtc_address,"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",10*pow(10,8));



0人推荐
随时随地看视频
慕课网APP