auth(); $uid = (int)$user['id']; $total = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', '<>', 2)->sum('amount'); $settled = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 1)->sum('amount'); $pending = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 0)->sum('amount'); $applied = (float)Db::name('fc_withdraw')->where('user_id', $uid) ->where('status', 'in', ['auditing', 'paying', 'paid'])->sum('amount'); $withdrawable = $settled - $applied; $todayStart = strtotime(date('Y-m-d')); $todayCommission = (float)Db::name('fc_commission')->where('user_id', $uid) ->where('createtime', '>=', $todayStart)->sum('amount'); $l1 = (int)Db::name('fc_dist_relation')->where('parent_id', $uid)->where('level', 1)->count(); $l2 = (int)Db::name('fc_dist_relation')->where('parent_id', $uid)->where('level', 2)->count(); $ext = $this->ext($uid); $code = (string)$ext['invite_code']; $shareUrl = 'https://fenleixinxi.gzyakj.com.cn/#/pages/index/index?ic=' . urlencode($code); // 查询当前用户的上级推荐人信息(用于前端展示「已绑定推荐人」或「手动绑定邀请码」入口) $inviterId = (int)(isset($ext['inviter_id']) ? $ext['inviter_id'] : 0); if ($inviterId <= 0) { $l1Rel = Db::name('fc_dist_relation')->where('user_id', $uid)->where('level', 1)->find(); if ($l1Rel && (int)$l1Rel['parent_id'] > 0) { $inviterId = (int)$l1Rel['parent_id']; } } $inviterNickname = ''; if ($inviterId > 0) { $inviterUser = Db::name('user')->where('id', $inviterId)->field('nickname,username')->find(); if ($inviterUser) { $inviterNickname = (string)($inviterUser['nickname'] ?: $inviterUser['username']); } } // 商家转账确认收款页需要的商户号与小程序 AppID(非敏感,可下发) $epay = (array)get_addon_config('epay'); $wx = isset($epay['wechat']) && is_array($epay['wechat']) ? $epay['wechat'] : []; $this->ok([ 'totalCommission' => round($total, 2), 'settled' => round($settled, 2), 'pendingCommission' => round($pending, 2), 'withdrawable' => round(max(0, $withdrawable), 2), 'todayCommission' => round($todayCommission, 2), 'teamCount' => $l1 + $l2, 'l1Count' => $l1, 'l2Count' => $l2, 'inviteCode' => $code, 'inviterId' => $inviterId, 'inviterNickname' => $inviterNickname, 'shareUrl' => $shareUrl, 'posterUrl' => '', // 最低提现金额(后台「分销设置」下发,微信审核规范要求无门槛,默认 0.1) 'minWithdraw' => (float)$this->cfg('dist.minWithdraw', 0.1), // 分销比例与配置规则 'level1Rate' => (float)$this->cfg('dist.level1Rate', 20), 'level2Rate' => (float)$this->cfg('dist.level2Rate', 10), 'settleCycle' => (string)$this->cfg('dist.settleCycle', '实时结算'), 'ruleContent' => (string)$this->cfg('dist.ruleContent', ''), 'enabled' => (int)$this->cfg('dist.enabled', 1), // 提现收款人实名(未填写时前端需先采集) 'realname' => isset($ext['realname']) ? (string)$ext['realname'] : '', 'transferMchId' => isset($wx['mch_id']) ? (string)$wx['mch_id'] : '', 'transferAppId' => isset($wx['miniapp_id']) ? (string)$wx['miniapp_id'] : '', ]); } /** * D2 我的团队 * GET /api/v1/distribution/team 入参 {level?,page,size} * 分页查询直推(1级)和间推(2级)下线团队成员 * * @return void 输出团队成员分页列表JSON */ public function team() { $user = $this->auth(); $uid = (int)$user['id']; $level = $this->input('level', ''); // 闭包重建查询:TP5.0 的 count() 会清空 Query::options,不能复用同一对象 list($rows, $total, $page, $size) = $this->pageQuery(function ($forCount) use ($uid, $level) { $q = Db::name('fc_dist_relation')->alias('r') ->join('user u', 'u.id = r.user_id') ->where('r.parent_id', $uid); if ($level !== '' && $level !== null) { $q->where('r.level', (int)$level); } if ($forCount) { return $q; } return $q->field('r.id,r.user_id,r.level,r.createtime,u.nickname,u.avatar,u.mobile') ->order('r.createtime desc'); }); $list = []; foreach ($rows as $row) { $childId = (int)$row['user_id']; $commission = (float)Db::name('fc_commission') ->where('user_id', $uid) ->where('from_user_id', $childId) ->sum('amount'); $orderAmount = (float)Db::name('fc_order') ->where('user_id', $childId) ->where('status', 'paid') ->sum('amount'); $performance = $orderAmount > 0 ? $orderAmount : $commission * 5; $mobile = (string)(isset($row['mobile']) ? $row['mobile'] : ''); $maskedMobile = (strlen($mobile) === 11) ? substr($mobile, 0, 3) . '****' . substr($mobile, -4) : ''; $list[] = [ 'id' => $childId, 'nickname' => (string)$row['nickname'], 'avatar' => (string)(isset($row['avatar']) ? $row['avatar'] : ''), 'mobile' => $maskedMobile, 'level' => (int)$row['level'], 'joinedAt' => $this->iso($row['createtime']), 'performance' => round($performance, 2), 'commission' => round($commission, 2), ]; } $this->ok($this->paginate($list, $total, $page, $size)); } /** * D3 分销收益明细(佣金流水账单) * GET /api/v1/distribution/commissions 入参 {status?,level?,page,size} * 分页查询下线消费产生的佣金记录明细及结算状态 * * @return void 输出佣金明细列表与汇总统计JSON */ public function commissions() { $user = $this->auth(); $uid = (int)$user['id']; $status = $this->input('status', ''); $level = $this->input('level', ''); list($rows, $total, $page, $size) = $this->pageQuery(function ($forCount) use ($uid, $status, $level) { $q = Db::name('fc_commission')->alias('c') ->join('user u', 'u.id = c.from_user_id', 'LEFT') ->join('fc_order o', 'o.order_no = c.order_no', 'LEFT') ->where('c.user_id', $uid); if ($status !== '' && $status !== null) { $q->where('c.status', (int)$status); } if ($level !== '' && $level !== null) { $q->where('c.level', (int)$level); } if ($forCount) { return $q; } return $q->field('c.*,u.nickname as from_nickname,u.avatar as from_avatar,o.title as order_title,o.amount as order_amount') ->order('c.createtime desc'); }); $typeMap = [ 'post' => '信息发布/置顶', 'member' => 'VIP会员购买', 'payview' => '付费查看信息', 'refresh' => '信息一键刷新', 'merchant' => '商家认证入驻', ]; $statusMap = [ 0 => '待结算', 1 => '已结算', 2 => '已失效', ]; $list = []; foreach ($rows as $row) { $orderType = (string)(isset($row['order_type']) ? $row['order_type'] : 'post'); $st = (int)$row['status']; $list[] = [ 'id' => (int)$row['id'], 'orderNo' => (string)$row['order_no'], 'orderType' => $orderType, 'orderTypeName' => isset($typeMap[$orderType]) ? $typeMap[$orderType] : (isset($row['order_title']) && $row['order_title'] ? $row['order_title'] : '同城消费'), 'orderAmount' => round((float)(isset($row['order_amount']) ? $row['order_amount'] : 0), 2), 'amount' => round((float)$row['amount'], 2), 'rate' => (float)$row['rate'], 'level' => (int)$row['level'], 'status' => $st, 'statusText' => isset($statusMap[$st]) ? $statusMap[$st] : '处理中', 'settleDue' => !empty($row['settle_due']) ? $this->iso($row['settle_due']) : '', 'settletime' => !empty($row['settletime']) ? $this->iso($row['settletime']) : '', 'createdAt' => $this->iso($row['createtime']), 'fromUser' => [ 'id' => (int)$row['from_user_id'], 'nickname' => (string)(isset($row['from_nickname']) && $row['from_nickname'] !== '' ? $row['from_nickname'] : '同城好友'), 'avatar' => (string)(isset($row['from_avatar']) ? $row['from_avatar'] : ''), ], ]; } $res = $this->paginate($list, $total, $page, $size); $res['summary'] = [ 'totalCommission' => round((float)Db::name('fc_commission')->where('user_id', $uid)->where('status', '<>', 2)->sum('amount'), 2), 'settledCommission' => round((float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 1)->sum('amount'), 2), 'pendingCommission' => round((float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 0)->sum('amount'), 2), ]; $this->ok($res); } /** * D4 分销海报生成要素 * GET /api/v1/distribution/poster * 获取用于前端合成或分享专属推广海报的元数据(含官方小程序码 URL,支持传入 postId 生成详情页小程序码) * * @return void 输出海报配置与素材信息的JSON */ public function poster() { $user = $this->auth(); $uid = (int)$user['id']; $ext = $this->ext($uid); $siteName = (string)$this->cfg('app.name', '同城分类信息'); $slogan = (string)$this->cfg('dist.slogan', '同城便民生活 · 随时随地发布与求助'); $code = (string)$ext['invite_code']; $postId = (int)$this->input('postId', 0); if ($postId > 0) { $scene = 'id_' . $postId . '_u_' . $uid; $page = 'pages/detail/detail'; } else { $scene = 'ic_' . $code; $page = 'pages/index/index'; } $wxacodeUrl = \app\common\library\WxMini::wxacodeUnlimit($scene, $page, 280); $this->ok([ 'inviteCode' => $code, 'siteName' => $siteName, 'slogan' => $slogan, 'nickname' => (string)(isset($user['nickname']) && $user['nickname'] !== '' ? $user['nickname'] : '同城合伙人'), 'avatar' => (string)(isset($user['avatar']) ? $user['avatar'] : ''), 'path' => $postId > 0 ? ('pages/detail/detail?id=' . $postId . '&ic=' . $code) : ('pages/index/index?ic=' . $code), 'wxacodeUrl' => $wxacodeUrl, ]); } /** * D5 申请提现 * POST /api/v1/distribution/withdraw 入参 {amount,channel?} → {withdrawNo,status:'auditing'} * 规则 BR-09:金额必填且 >0、且不超过可提现余额 * * @return void 输出提现单号与状态JSON */ public function withdraw() { $user = $this->auth(); $uid = (int)$user['id']; $this->rateLimit('withdraw:' . $uid, 3, 60); $amount = round((float)$this->input('amount', 0), 2); $min = (float)$this->cfg('dist.minWithdraw', 0.1); if ($amount <= 0) { $this->fail('提现金额不合法'); } if ($min > 0 && $amount < $min) { $this->fail('最低提现金额为 ' . $min . ' 元'); } // 微信商家转账会校验收款人实名,未填写姓名不允许提现 $ext = $this->ext($uid); if (trim((string)(isset($ext['realname']) ? $ext['realname'] : '')) === '') { $this->fail('请先填写收款人真实姓名(需与微信实名一致)'); } $channel = trim((string)$this->input('channel', '')); if ($channel === '') { $channel = 'wxpay'; } $withdrawNo = $this->orderNo('WD'); try { Db::transaction(function () use ($uid, $amount, $channel, $withdrawNo) { // 用户扩展行加锁:同一用户的提现申请串行化,避免并发双花 Db::name('fc_user_ext')->where('user_id', $uid)->lock(true)->find(); if ($amount > $this->withdrawable($uid)) { throw new \RuntimeException('提现金额超过可提现余额'); } Db::name('fc_withdraw')->insert([ 'withdraw_no' => $withdrawNo, 'user_id' => $uid, 'amount' => $amount, 'channel' => $channel, 'status' => 'auditing', 'reason' => '', 'paytime' => null, 'createtime' => time(), 'updatetime' => time(), ]); }); } catch (\Throwable $e) { $this->fail($e->getMessage() ?: '提现申请失败,请重试'); } $this->notify($uid, 'system', '提现申请已提交', '提现 ¥' . $amount . ' 已提交,预计 T+7 到账'); $this->ok(['withdrawNo' => $withdrawNo, 'status' => 'auditing']); } /** * D6 提现记录 * GET /api/v1/distribution/withdraw-records → [{id,withdrawNo,amount,status,createdAt}] * 获取当前用户的历史提现记录与商家转账确认参数 * * @return void 输出提现历史记录列表JSON */ public function withdrawRecords() { $user = $this->auth(); $rows = Db::name('fc_withdraw')->where('user_id', $user['id']) ->order('createtime desc')->select(); $epay = (array)get_addon_config('epay'); $wx = isset($epay['wechat']) && is_array($epay['wechat']) ? $epay['wechat'] : []; $mchId = isset($wx['mch_id']) ? (string)$wx['mch_id'] : '1118898018'; $appId = isset($wx['miniapp_id']) ? (string)$wx['miniapp_id'] : 'wxbfcb778f3019cff8'; $list = []; foreach ($rows as $row) { $list[] = [ 'id' => (int)$row['id'], 'withdrawNo' => (string)$row['withdraw_no'], 'amount' => round((float)$row['amount'], 2), 'status' => (string)$row['status'], 'transferStatus' => (string)(isset($row['transfer_status']) ? $row['transfer_status'] : ''), 'packageInfo' => (string)(isset($row['package_info']) ? $row['package_info'] : ''), 'failReason' => WithdrawText::fail(isset($row['fail_reason']) ? $row['fail_reason'] : ''), 'createdAt' => $this->iso($row['createtime']), 'transferMchId' => $mchId, 'transferAppId' => $appId, ]; } $this->ok($list); } /** * D8 提现单详情 * GET /api/v1/distribution/withdraw-detail 入参 {id|withdrawNo} * * @return void 输出提现流水单据详细信息JSON */ public function withdrawDetail() { $user = $this->auth(); $id = (int)$this->input('id', 0); $no = trim((string)$this->input('withdrawNo', '')); $query = Db::name('fc_withdraw')->where('user_id', $user['id']); if ($id > 0) { $query->where('id', $id); } elseif ($no !== '') { $query->where('withdraw_no', $no); } else { $this->fail('参数错误'); } $row = $query->find(); if (!$row) { $this->fail('提现记录不存在'); } $epay = (array)get_addon_config('epay'); $wx = isset($epay['wechat']) && is_array($epay['wechat']) ? $epay['wechat'] : []; $mchId = isset($wx['mch_id']) ? (string)$wx['mch_id'] : '1118898018'; $appId = isset($wx['miniapp_id']) ? (string)$wx['miniapp_id'] : 'wxbfcb778f3019cff8'; $this->ok([ 'id' => (int)$row['id'], 'withdrawNo' => (string)$row['withdraw_no'], 'amount' => round((float)$row['amount'], 2), 'channel' => (string)$row['channel'], 'status' => (string)$row['status'], 'reason' => WithdrawText::reason($row['reason']), 'outBillNo' => (string)$row['out_bill_no'], 'transferStatus' => (string)$row['transfer_status'], 'transferId' => (string)$row['transfer_id'], 'packageInfo' => (string)$row['package_info'], 'failReason' => WithdrawText::fail($row['fail_reason']), 'createdAt' => $this->iso($row['createtime']), 'payTime' => !empty($row['paytime']) ? $this->iso($row['paytime']) : '', 'transferTime' => !empty($row['transfer_time']) ? $this->iso($row['transfer_time']) : '', 'transferMchId' => $mchId, 'transferAppId' => $appId, ]); } /** * D7 手动输入邀请码补绑推荐人(老用户不支持自动补绑,仅支持通过手动填写邀请码完成补绑) * POST /api/v1/distribution/bind 入参 {inviteCode} * * @return void 输出绑定结果与推荐人信息JSON */ public function bind() { $user = $this->auth(); $uid = (int)$user['id']; $inviteCode = strtoupper(trim((string)$this->input('inviteCode', $this->input('invite_code', '')))); if ($inviteCode === '') { $this->fail('请输入有效的邀请码'); } // 检查当前用户是否已绑定过推荐人 $ext = $this->ext($uid); $existingInviter = (int)(isset($ext['inviter_id']) ? $ext['inviter_id'] : 0); if ($existingInviter <= 0) { $l1Rel = Db::name('fc_dist_relation')->where('user_id', $uid)->where('level', 1)->find(); if ($l1Rel && (int)$l1Rel['parent_id'] > 0) { $existingInviter = (int)$l1Rel['parent_id']; } } if ($existingInviter > 0) { $this->fail('您已绑定过推荐人,不可重复绑定'); } // 校验邀请码并定位目标推荐人 if (isset($ext['invite_code']) && strtoupper((string)$ext['invite_code']) === $inviteCode) { $this->fail('不能填写自己的邀请码'); } $parentExt = Db::name('fc_user_ext')->where('invite_code', $inviteCode)->find(); if (!$parentExt || (int)$parentExt['user_id'] <= 0) { $this->fail('邀请码不存在,请核对后重试'); } $targetInviterId = (int)$parentExt['user_id']; if ($targetInviterId === $uid) { $this->fail('不能绑定自己为推荐人'); } // 防环校验:不能绑定自己的下级成员 $isDownline = Db::name('fc_dist_relation') ->where('user_id', $targetInviterId) ->where('parent_id', $uid) ->count(); if ($isDownline > 0) { $this->fail('不能绑定您的下级成员为推荐人'); } $ok = \app\common\library\DistributionService::bindRelation($uid, $targetInviterId, $inviteCode); if (!$ok) { $this->fail('绑定失败,请核对邀请码后重试'); } $inviterUser = Db::name('user')->where('id', $targetInviterId)->field('nickname,username')->find(); $inviterNickname = $inviterUser ? (string)($inviterUser['nickname'] ?: $inviterUser['username']) : '同城合伙人'; $this->ok([ 'bound' => true, 'inviterId' => $targetInviterId, 'inviterNickname' => $inviterNickname, ]); } /** * 计算当前用户可提现余额 * 可提现余额 = Σ已结算佣金(status=1) - Σ(申请中/已打款)提现 * * @param int $uid 用户ID * @return float 可提现余额数值 */ protected function withdrawable($uid) { $settled = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 1)->sum('amount'); $applied = (float)Db::name('fc_withdraw')->where('user_id', $uid) ->where('status', 'in', ['auditing', 'paying', 'paid'])->sum('amount'); return $settled - $applied; } }