You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用私钥和密码发送以太币?PHP+Cron实现及Node库咨询

Hey there! Let's work through your problem of sending Ether via a cron job—whether you stick with PHP or switch to Node.js. First, let's answer your direct question about Node.js POST libraries, then dive into full implementation steps.

Node.js Libraries for POST Requests

Absolutely—Node.js has tons of great options for making POST requests, both for general API calls and Ethereum RPC endpoints:

  • Axios: The most popular choice for its clean syntax and built-in features like automatic JSON parsing.
  • node-fetch: A Node.js implementation of the browser's fetch API, so if you're familiar with that, it's a natural fit.
  • Built-in http/https modules: No need to install extra packages if you want to stick to core Node.js, though it's a bit more verbose.

Here's a quick example using Axios to send an Ethereum RPC request (which is how you'll actually broadcast transactions):

const axios = require('axios');

async function sendEtherRpc() {
  const rpcUrl = 'https://your-ethereum-node-url'; // e.g., Infura, Alchemy
  const signedTransactionHex = 'YOUR_SIGNED_TRANSACTION_HEX'; // Generated via web3/ethers

  try {
    const response = await axios.post(rpcUrl, {
      jsonrpc: '2.0',
      method: 'eth_sendRawTransaction',
      params: [signedTransactionHex],
      id: 1
    });
    console.log('Transaction hash:', response.data.result);
  } catch (error) {
    console.error('RPC request failed:', error.response?.data || error.message);
  }
}

sendEtherRpc();
Full Node.js + Cron Implementation Guide

Since you mentioned issues running JavaScript via Cron, a standalone Node.js script is perfect for this—it's designed to run in terminal environments. Here's how to set it up end-to-end:

1. Pull Account Data from MySQL

First, install the mysql2 package to interact with your database:

npm install mysql2

Then write code to fetch and parse your JSON account data:

const mysql = require('mysql2/promise');

async function getAccountFromDb() {
  const connection = await mysql.createConnection({
    host: 'your-db-host',
    user: 'your-db-user',
    password: 'your-db-password',
    database: 'your-db-name'
  });

  const [rows] = await connection.execute('SELECT your_json_column FROM your_table WHERE ...');
  await connection.end();

  if (rows.length === 0) throw new Error('No account found in database');
  return JSON.parse(rows[0].your_json_column);
}

2. Sign and Send the Ether Transaction

Use a battle-tested Ethereum library like ethers.js (easier to use for transaction signing than raw RPC calls):

npm install ethers

Add this to your script to handle transaction signing and broadcasting:

const { ethers } = require('ethers');

async function sendEther(accountData, toAddress, amountInEth) {
  const provider = new ethers.JsonRpcProvider('https://your-ethereum-node-url');
  const wallet = new ethers.Wallet(accountData.privateKey, provider);

  // Build transaction
  const transaction = {
    to: toAddress,
    value: ethers.parseEther(amountInEth), // Convert ETH to Wei
    gasLimit: 21000, // Standard gas limit for simple transfers
    gasPrice: await provider.getGasPrice()
  };

  // Sign and send transaction
  const txResponse = await wallet.sendTransaction(transaction);
  await txResponse.wait(); // Wait for transaction confirmation
  console.log(`Transaction confirmed: ${txResponse.hash}`);
}

3. Set Up the Cron Job

To run this script on a schedule:

  1. Add #!/usr/bin/env node at the top of your script to mark it as executable, then set permissions: chmod +x your-script.js.
  2. Open your crontab editor with crontab -e.
  3. Add a line like this to run the script every day at 9 AM (adjust the schedule as needed):
0 9 * * * /usr/bin/node /path/to/your/script.js >> /path/to/logs/eth-sender.log 2>&1
  • The >> ... 2>&1 part logs both output and errors to a file, which is crucial for debugging cron jobs.
Critical Security Reminders

Storing private keys in plaintext in a database is a huge risk—here's how to fix that:

  • Encrypt private keys at rest: Use a strong encryption algorithm (like AES-256) to encrypt the private key before storing it in MySQL. Decrypt it only when needed in your script.
  • Restrict database access: Make sure your database user only has read access to the account table, and limit IPs that can connect to the database.
  • Lock down your script: Set file permissions to chmod 600 your-script.js so only the user running the cron job can read it.
  • Never log sensitive data: Avoid printing private keys, passwords, or transaction details to logs unless absolutely necessary.
Alternative: PHP Implementation

If you'd rather stick with PHP, you can use the web3.php library to handle Ethereum transactions. Here's a quick snippet:

<?php
require 'vendor/autoload.php';

use Web3\Web3;
use Web3\Utils;

// Fetch account data from MySQL (parse JSON)
$accountJson = '{"address":"0x22b853A8Df90BF9A7e21445C16FBbEaa43e0c307","password":"inu8p","privateKey":"0xb9cabca09e5cbdfb2c953d574bce5b9d837a91ffe1f3817fc6a01da63bf5ff56"}';
$account = json_decode($accountJson, true);

$web3 = new Web3('https://your-ethereum-node-url');
$wallet = $web3->eth->accounts->privateKeyToAccount($account['privateKey']);

// Build transaction
$tx = [
    'from' => $account['address'],
    'to' => '0xRecipientAddress',
    'value' => Utils::toWei('0.1', 'ether'),
    'gas' => '21000',
    'gasPrice' => $web3->eth->gasPrice->wait()
];

// Sign and send
$signedTx = $wallet->signTransaction($tx);
$web3->eth->sendRawTransaction($signedTx, function($err, $txHash) {
    if ($err) {
        echo 'Error: ' . $err->getMessage();
    } else {
        echo 'Transaction hash: ' . $txHash;
    }
});
?>

To run this via cron, add a line like:

0 9 * * * /usr/bin/php /path/to/your/script.php >> /path/to/logs/eth-sender.log 2>&1

内容的提问来源于stack exchange,提问作者Ronnie Jaimungal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:22:48