php实现转账
PHP实现转账功能
实现转账功能需要考虑安全性、数据一致性和错误处理。以下是一个基本的PHP转账实现方案:
数据库设计
创建用户账户表和交易记录表:
CREATE TABLE accounts (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL,
balance DECIMAL(15,2) NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE transactions (
id INT PRIMARY KEY AUTO_INCREMENT,
from_account INT NOT NULL,
to_account INT NOT NULL,
amount DECIMAL(15,2) NOT NULL,
status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
转账核心逻辑
function transferMoney($pdo, $fromUserId, $toUserId, $amount) {
try {
$pdo->beginTransaction();
// 检查金额是否有效
if ($amount <= 0) {
throw new Exception("转账金额必须大于零");
}
// 获取转出账户信息并加锁
$stmt = $pdo->prepare("SELECT id, balance FROM accounts WHERE user_id = ? FOR UPDATE");
$stmt->execute([$fromUserId]);
$fromAccount = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$fromAccount) {
throw new Exception("转出账户不存在");
}
// 检查余额是否充足
if ($fromAccount['balance'] < $amount) {
throw new Exception("账户余额不足");
}
// 获取转入账户信息并加锁
$stmt = $pdo->prepare("SELECT id FROM accounts WHERE user_id = ? FOR UPDATE");
$stmt->execute([$toUserId]);
$toAccount = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$toAccount) {
throw new Exception("转入账户不存在");
}
// 记录交易
$stmt = $pdo->prepare("INSERT INTO transactions (from_account, to_account, amount, status) VALUES (?, ?, ?, 'pending')");
$stmt->execute([$fromAccount['id'], $toAccount['id'], $amount]);
$transactionId = $pdo->lastInsertId();
// 扣除转出账户金额
$stmt = $pdo->prepare("UPDATE accounts SET balance = balance - ? WHERE id = ?");
$stmt->execute([$amount, $fromAccount['id']]);
// 增加转入账户金额
$stmt = $pdo->prepare("UPDATE accounts SET balance = balance + ? WHERE id = ?");
$stmt->execute([$amount, $toAccount['id']]);
// 更新交易状态
$stmt = $pdo->prepare("UPDATE transactions SET status = 'completed' WHERE id = ?");
$stmt->execute([$transactionId]);
$pdo->commit();
return ['success' => true, 'transaction_id' => $transactionId];
} catch (Exception $e) {
$pdo->rollBack();
return ['success' => false, 'error' => $e->getMessage()];
}
}
安全注意事项
- 使用预处理语句防止SQL注入
- 事务处理确保数据一致性
- 行级锁(FOR UPDATE)防止并发问题
- 验证输入金额的有效性
- 检查账户余额是否充足
- 记录完整的交易日志
调用示例
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$result = transferMoney($pdo, 1, 2, 100.00);
if ($result['success']) {
echo "转账成功,交易ID: " . $result['transaction_id'];
} else {
echo "转账失败: " . $result['error'];
}
扩展功能建议
- 添加每日转账限额检查
- 实现短信或邮件通知
- 添加交易手续费计算
- 实现批量转账功能
- 添加管理员审核机制







