PHP 怎么PHP 钱包连接

wen PHP项目 1

本文目录导读:

PHP 怎么PHP 钱包连接

  1. 通过JSON-RPC连接本地钱包节点
  2. 连接Web3钱包(如MetaMask)
  3. 连接第三方钱包服务API
  4. 连接交易所钱包API(示例:Binance)
  5. 安全注意事项
  6. 完整示例:创建并发送交易
  7. 推荐使用的PHP钱包库

在PHP中实现钱包连接(特别是区块链钱包),通常不是直接通过PHP连接钱包本身,而是通过API接口RPC调用与钱包服务进行交互,以下是几种常见场景及实现方式:

通过JSON-RPC连接本地钱包节点

以太坊钱包连接示例(使用web3.php)

// 安装: composer require web3/web3
require 'vendor/autoload.php';
use Web3\Web3;
use Web3\Providers\HttpProvider;
// 连接本地或远程以太坊节点
$web3 = new Web3(new HttpProvider('https://mainnet.infura.io/v3/YOUR_PROJECT_ID'));
// 或者连接本地节点
// $web3 = new Web3(new HttpProvider('http://localhost:8545'));
// 获取区块信息
$web3->eth->blockNumber(function ($err, $blockNumber) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    echo 'Latest block: ' . $blockNumber . "\n";
});
// 获取账户余额
$web3->eth->getBalance('0xYourAddress', function ($err, $balance) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    echo 'Balance: ' . $balance . "\n";
});

比特币钱包连接示例(使用bitcoinrpc)

// 使用bitcoin-php库
// 安装: composer require denpa/bitcoin-php
require 'vendor/autoload.php';
use Denpa\Bitcoin\Client as BitcoinClient;
$bitcoind = new BitcoinClient([
    'scheme' => 'http',
    'host'   => '127.0.0.1',
    'port'   => 8332,
    'user'   => 'rpcuser',
    'password' => 'rpcpassword',
]);
// 获取区块链信息
$info = $bitcoind->getBlockchainInfo();
echo 'Block count: ' . $info['blocks'] . "\n";
// 获取账户余额
try {
    $balance = $bitcoind->getBalance('account_name');
    echo 'Balance: ' . $balance . "\n";
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

连接Web3钱包(如MetaMask)

后端验证签名

// 用户前端使用MetaMask签名后,后端验证
function verifySignature($message, $signature, $address) {
    // 使用以太坊签名验证逻辑
    $personalMessage = "\x19Ethereum Signed Message:\n" . strlen($message) . $message;
    $msgHash = hash('keccak256', $personalMessage, true);
    // 恢复到签名地址
    $recovered = \BitWasp\Bitcoin\Crypto\EcAdapter\EcSerializer::getSerializer(
        \BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Signature\CompactSignatureSerializerInterface::class
    )->parse($signature);
    return strtolower($recovered) === strtolower($address);
}
// API端点验证用户
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $address = $data['address'];
    $signature = $data['signature'];
    $message = $data['message'];
    if (verifySignature($message, $signature, $address)) {
        // 验证成功,创建会话
        $_SESSION['wallet_address'] = $address;
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid signature']);
    }
}

连接第三方钱包服务API

使用BlockCypher API

// 安装: composer require blockcypher/php-client
require 'vendor/autoload.php';
use BlockCypher\Client\AddressClient;
use BlockCypher\Api\Address;
$client = new \BlockCypher\Client\BlockCypherRestClient([
    'api_key' => 'YOUR_API_KEY',
    'network' => 'btc.main' // 或 eth.main
]);
$addressClient = new AddressClient($client);
// 查询地址余额
try {
    $address = $addressClient->get('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa');
    echo 'Final balance: ' . $address->getFinalBalance() . " satoshis\n";
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

连接交易所钱包API(示例:Binance)

require 'vendor/autoload.php';
use Binance\API;
$api = new API([
    'key' => 'YOUR_API_KEY',
    'secret' => 'YOUR_API_SECRET'
]);
// 获取账户信息
try {
    $account = $api->account();
    echo 'balances: ' . json_encode($account['balances']) . "\n";
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

安全注意事项

私钥安全存储

// 永远不要在代码中硬编码私钥
// 使用环境变量或加密存储
class SecureWalletStorage {
    private $encryptedStore;
    public function __construct($encryptionKey) {
        $this->encryptionKey = $encryptionKey;
    }
    public function storePrivateKey($address, $privateKey) {
        $encrypted = openssl_encrypt(
            $privateKey,
            'aes-256-cbc',
            $this->encryptionKey,
            0,
            $iv
        );
        // 存储到数据库
        DB::table('wallet_keys')->insert([
            'address' => $address,
            'encrypted_key' => base64_encode($encrypted),
            'iv' => base64_encode($iv),
            'created_at' => now()
        ]);
    }
    public function getPrivateKey($address) {
        $record = DB::table('wallet_keys')->where('address', $address)->first();
        if (!$record) {
            throw new Exception('Address not found');
        }
        $decrypted = openssl_decrypt(
            base64_decode($record->encrypted_key),
            'aes-256-cbc',
            $this->encryptionKey,
            0,
            base64_decode($record->iv)
        );
        return $decrypted;
    }
}

完整示例:创建并发送交易

// 以太坊交易示例
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\Transaction;
$web3 = new Web3(new HttpProvider('http://localhost:8545'));
// 创建交易
$transaction = new Transaction([
    'from' => '0xYourAddress',
    'to' => '0xRecipientAddress',
    'value' => '0x' . dechex(0.1 * 1e18), // 0.1 ETH
    'gas' => '0x5208', // 21000
    'gasPrice' => '0x' . dechex(20e9), // 20 Gwei
    'nonce' => 1,
]);
// 签名并发送
$signedTransaction = $transaction->sign('your-private-key');
$web3->eth->sendRawTransaction($signedTransaction, function ($err, $txHash) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    echo 'Transaction hash: ' . $txHash . "\n";
});

推荐使用的PHP钱包库

  1. ethereum-php / web3.php - 以太坊钱包操作
  2. bitcoin-php - 比特币钱包操作
  3. walletconnect/monorepo - WalletConnect协议PHP实现
  4. simplito/elliptic-php - 椭圆曲线加密库
  5. blockcypher/php-client - 多链钱包API

选择哪种方式取决于你的具体需求:

  • 如果只是查询余额:使用第三方API最简单
  • 如果需要完整钱包功能:建议运行本地节点并使用JSON-RPC
  • 如果需要用户授权:使用WalletConnect或MetaMask集成

抱歉,评论功能暂时关闭!