php实现购买功能
PHP实现购买功能的基本步骤
数据库设计
创建必要的数据库表,如products(商品表)、users(用户表)、orders(订单表)。商品表需包含id、name、price、stock等字段;订单表需包含order_id、user_id、product_id、quantity、total_price、status等字段。
用户登录验证 使用Session或JWT实现用户登录状态验证,确保只有登录用户可发起购买请求。未登录用户跳转至登录页面:
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
商品展示页面 从数据库查询商品信息并展示,提供购买按钮:

$stmt = $pdo->query("SELECT * FROM products WHERE stock > 0");
while ($row = $stmt->fetch()) {
echo "<div>{$row['name']} - {$row['price']}元
<form action='purchase.php' method='post'>
<input type='hidden' name='product_id' value='{$row['id']}'>
<input type='number' name='quantity' min='1' max='{$row['stock']}'>
<button type='submit'>购买</button>
</form></div>";
}
处理购买请求的核心逻辑
库存与支付验证
在purchase.php中处理表单提交,验证库存和用户余额:
$product_id = $_POST['product_id'];
$quantity = (int)$_POST['quantity'];
// 开启事务
$pdo->beginTransaction();
try {
// 锁定商品行防止并发修改
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? FOR UPDATE");
$stmt->execute([$product_id]);
$product = $stmt->fetch();
if (!$product || $product['stock'] < $quantity) {
throw new Exception("库存不足");
}
// 计算总价
$total = $product['price'] * $quantity;
// 更新库存
$pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?")
->execute([$quantity, $product_id]);
// 创建订单记录
$pdo->prepare("INSERT INTO orders (...) VALUES (...)")
->execute([...]);
$pdo->commit();
echo "购买成功!";
} catch (Exception $e) {
$pdo->rollBack();
echo "错误: " . $e->getMessage();
}
支付系统集成
第三方支付对接 以支付宝为例,使用官方SDK生成支付链接:

require_once 'alipay-sdk-PHP/AopSdk.php';
$c = new AopClient();
$c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
$c->appId = "your_app_id";
$c->rsaPrivateKey = 'your_private_key';
$request = new AlipayTradePagePayRequest();
$request->setReturnUrl("http://yoursite.com/return_url.php");
$request->setNotifyUrl("http://yoursite.com/notify_url.php");
$request->setBizContent(json_encode([
'out_trade_no' => uniqid(),
'total_amount' => $total,
'subject' => $product['name'],
'product_code' => 'FAST_INSTANT_TRADE_PAY'
]));
$response = $c->pageExecute($request);
echo $response;
订单状态处理
支付回调验证
在notify_url.php中验证支付结果并更新订单状态:
$alipaySign = $_POST['sign'];
$params = $_POST;
unset($params['sign_type']);
ksort($params);
$sign = $c->rsaVerify(http_build_query($params), $alipaySign);
if ($sign && $_POST['trade_status'] == 'TRADE_SUCCESS') {
$pdo->prepare("UPDATE orders SET status = 'paid' WHERE order_id = ?")
->execute([$_POST['out_trade_no']]);
}
安全防护措施
CSRF防护 在表单中添加CSRF令牌:
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
echo "<input type='hidden' name='csrf_token' value='{$_SESSION['csrf_token']}'>";
输入过滤 对所有用户输入进行过滤:
$quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1]
]);
if (!$quantity) {
die("无效的数量");
}
防止超卖
使用数据库悲观锁(SELECT FOR UPDATE)或乐观锁(版本号机制)确保库存一致性,如事务示例所示。高并发场景建议引入Redis缓存或消息队列。






