以下是一个简单的以太坊支付代码示例,使用Web3.js库与以太坊网络进行交互:
javascript
// 引入Web3.js库
const Web3 = require(‘web3’);
// 创建一个新的Web3实例,连接到以太坊网络(可以使用自己的以太坊节点URL)
const web3 = new Web3(‘https://mainnet.infura.io/v3/your-infura-project-id’);
// 定义以太坊支付函数
async function makeEthereumPayment(receiverAddress, amountInEther, privateKey) {
try {
// 将私钥导入账户
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
// 构建交易对象
const txObject = {
to: receiverAddress,
value: web3.utils.toWei(amountInEther.toString(), ‘ether’),
gas: 21000, // 默认燃气限制
};
// 使用私钥对交易进行签名
const signedTx = await account.signTransaction(txObject);
// 发送已签名的交易到以太坊网络
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
// 打印交易哈希和状态
console.log(‘Transaction Hash:’, receipt.transactionHash);
console.log(‘Transaction Status:’, receipt.status);
} catch (error) {
console.error(‘Error:’, error);
}
}
// 调用以太坊支付函数
const receiverAddress = ‘0xYourReceiverAddress’;
const amountInEther = 0.1;
const privateKey = ‘0xYourPrivateKey’;
makeEthereumPayment(receiverAddress, amountInEther, privateKey);
请注意,这只是一个简单的示例,需要将其中的地址、私钥和其他参数替换为适合实际情况的值。此外,确保已连接到以太坊网络,并具有足够的以太币用于支付交易费用。