php实现分销
PHP实现分销系统的基本方法
分销系统通常涉及多级佣金计算和用户关系管理。以下是一个基于PHP的实现方案:
数据库设计 创建必要的表结构存储用户关系和佣金记录:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50),
parent_id INT, -- 上级ID
level INT DEFAULT 0 -- 分销层级
);
CREATE TABLE commissions (
id INT PRIMARY KEY AUTO_INCREMENT,
order_id INT,
user_id INT,
amount DECIMAL(10,2),
level INT,
status TINYINT DEFAULT 0,
create_time TIMESTAMP
);
用户关系绑定 当新用户注册时,通过推荐链接或推荐码建立关系:
function bindParent($userId, $parentId) {
$parent = getUserById($parentId);
if (!$parent) return false;
$level = $parent['level'] + 1;
$sql = "UPDATE users SET parent_id = ?, level = ? WHERE id = ?";
executeQuery($sql, [$parentId, $level, $userId]);
return true;
}
佣金分配逻辑 订单完成时,向上追溯分配各级佣金:

function distributeCommission($orderId, $userId, $totalAmount) {
$currentUser = getUserById($userId);
$commissionRates = [0.3, 0.2, 0.1]; // 三级分佣比例
for ($i = 0; $i < count($commissionRates); $i++) {
if (!$currentUser['parent_id']) break;
$parent = getUserById($currentUser['parent_id']);
$amount = $totalAmount * $commissionRates[$i];
$sql = "INSERT INTO commissions (order_id, user_id, amount, level)
VALUES (?, ?, ?, ?)";
executeQuery($sql, [$orderId, $parent['id'], $amount, $i+1]);
$currentUser = $parent;
}
}
分销层级控制
无限级分销实现 使用递归或迭代方式处理无限层级:
function getAncestors($userId, $maxLevel = 10) {
$ancestors = [];
$currentUser = getUserById($userId);
while ($currentUser['parent_id'] && count($ancestors) < $maxLevel) {
$parent = getUserById($currentUser['parent_id']);
$ancestors[] = $parent;
$currentUser = $parent;
}
return $ancestors;
}
层级限制 在配置中设置最大分销层级:
define('MAX_LEVEL', 3); // 限制三级分销
佣金结算与提现
佣金统计查询

function getUserCommission($userId) {
$sql = "SELECT SUM(amount) as total, level
FROM commissions
WHERE user_id = ? AND status = 0
GROUP BY level";
return fetchAll($sql, [$userId]);
}
提现申请处理
function applyWithdraw($userId, $amount) {
$balance = getBalance($userId);
if ($balance < $amount) return false;
startTransaction();
try {
$sql = "UPDATE commissions SET status = 1
WHERE user_id = ? AND status = 0
ORDER BY create_time LIMIT ?";
executeQuery($sql, [$userId, $amount]);
recordWithdraw($userId, $amount);
commit();
return true;
} catch (Exception $e) {
rollback();
return false;
}
}
安全与性能优化
防循环引用检测 在绑定关系时检查是否形成循环:
function isCircularReference($userId, $parentId) {
$ancestors = getAncestors($parentId);
foreach ($ancestors as $ancestor) {
if ($ancestor['id'] == $userId) {
return true;
}
}
return false;
}
数据缓存优化 使用Redis缓存用户关系树:
function getAncestorsCached($userId) {
$cacheKey = "user_ancestors:$userId";
if ($cached = redisGet($cacheKey)) {
return json_decode($cached, true);
}
$ancestors = getAncestors($userId);
redisSet($cacheKey, json_encode($ancestors), 3600);
return $ancestors;
}
以上代码提供了PHP实现分销系统的核心功能框架,实际应用中需要根据具体业务需求进行调整和完善。






