feat(api): 新增小程序用户端与后台管理端 v1 业务接口(62 端点)

一、基础设施
- route.php:58 条路由覆盖 /api/v1/**;:id 用 \d+ 约束、长路径优先
- api/controller/V1.php:响应适配为 {code,message,data}(FastAdmin 原生 {code,msg,time,data} 不兼容);
  Authorization Bearer 鉴权;统一分页;业务公共 userInfo/ext/flow/notify/adminLog
- admin/command/FcInstall.php:19 张 fa_fc_* 表 + 种子数据,幂等可重跑

二、控制器 17 个
- 用户端 Auth/Home/Post/Member/Distribution/Message/Setting
- 后台端 AdminDashboard/AdminMerchant/AdminMember/AdminPost/AdminComment/
  AdminDist/AdminOrder/AdminFinance/AdminRbac/AdminSetting

三、契约一致性
- 字段与小程序 common/mock/data.js 逐字段对齐,Mock 与真实接口可对拍
- 实现 BR-01~BR-12,错误文案与前端 mock 完全一致
- 详情联系方式强制脱敏,付费/会员方可解锁

四、验证
- tools/verify-api.mjs:63 端点契约 + 12 条业务规则 + 8 步双端闭环
- docs/05-后端实现规范.md
这个提交包含在:
linda
2026-10-15 14:36:26 +08:00
父节点 f8c6a31684
当前提交 a09a0a10be
共有 22 个文件被更改,包括 4473 次插入 和 9 次删除

查看文件

@@ -0,0 +1,109 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 评价管理(Module-ADM-COMMENT)
* 路由:
* GET /api/v1/admin/comments AC1 评价列表
* POST /api/v1/admin/comment/:id/reply AC2 评价回复
* GET /api/v1/admin/reports AC3 举报列表
*/
class AdminComment extends V1
{
/**
* AC1 评价列表
* GET /api/v1/admin/comments 入参 {page,size}
* → 分页 {list:[{id,postId,postTitle,user,score,content,images,reply,top,createdAt}],page,size,total,hasMore}
*/
public function index()
{
list($page, $size) = $this->pager();
$query = Db::name('fc_comment')->alias('co')
->join('fc_post p', 'p.id = co.post_id', 'LEFT')
->join('user u', 'u.id = co.user_id', 'LEFT');
$total = $query->count();
$rows = $query->field('co.*, p.title AS post_title, u.nickname AS nickname')
->order('co.id desc')
->page($page, $size)
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'postId' => (int)$row['post_id'],
'postTitle' => (string)$row['post_title'],
'user' => (string)$row['nickname'],
'score' => (int)$row['score'],
'content' => (string)$row['content'],
'images' => $this->jsonArr($row['images']),
'reply' => (string)$row['reply'],
'top' => (bool)$row['top'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* AC2 评价回复
* POST /api/v1/admin/comment/:id/reply 入参 {id?,reply} → {id,reply}
*/
public function reply()
{
$id = (int)$this->request->param('id', 0);
if (!$id) {
$id = (int)$this->input('id', 0);
}
$reply = trim((string)$this->input('reply', ''));
if ($reply === '') {
$this->fail('回复内容不能为空');
}
$comment = Db::name('fc_comment')->where('id', $id)->find();
if (!$comment) {
$this->fail('评价不存在', 404);
}
Db::name('fc_comment')->where('id', $id)->update([
'reply' => $reply,
'replytime' => time(),
]);
$this->notify($comment['user_id'], 'interact', '评价已回复', '您的评价收到商家回复:' . $reply);
$this->adminLog('回复评价 #' . $id);
$this->ok(['id' => (int)$id, 'reply' => $reply]);
}
/**
* AC3 举报列表
* GET /api/v1/admin/reports → 数组 [{id,targetType,targetId,reason,reporter,status,createdAt}]
*/
public function reports()
{
$rows = Db::name('fc_report')->order('createtime desc')->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'targetType' => (string)$row['target_type'],
'targetId' => (int)$row['target_id'],
'reason' => (string)$row['reason'],
'reporter' => (string)$row['reporter_id'],
'status' => (string)$row['status'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($list);
}
}

查看文件

@@ -0,0 +1,100 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 数据总览(Module-ADM-DASHBOARD)
* 路由:
* GET /api/v1/admin/dashboard/overview AD1 核心指标
* GET /api/v1/admin/dashboard/trend AD2 趋势(近 7 天)
*/
class AdminDashboard extends V1
{
/**
* AD1 核心指标
* GET /api/v1/admin/dashboard/overview
* → {pv,uv,todayPostCount,todayOrderAmount,memberCount,merchantCount,commissionTotal,pendingAudit,postGrowth,orderGrowth,userGrowth}
*/
public function overview()
{
$pv = (int)Db::name('fc_post')->sum('views');
$uv = (int)Db::name('user')->count();
$todayStart = strtotime(date('Y-m-d'));
$todayPostCount = (int)Db::name('fc_post')->where('createtime', '>=', $todayStart)->count();
$todayOrderAmount = (float)Db::name('fc_order')->where('status', 'paid')
->where('createtime', '>=', $todayStart)->sum('amount');
$now = time();
$memberCount = (int)Db::name('fc_user_ext')->where('is_member', 1)
->where(function ($q) use ($now) {
$q->whereNull('member_expiretime')->whereOr('member_expiretime', '>', $now);
})->count();
$merchantCount = (int)Db::name('fc_merchant')->count();
$commissionTotal = (float)Db::name('fc_commission')->sum('amount');
$pendingAudit = (int)Db::name('fc_post')->where('audit_status', 0)->count();
$this->ok([
'pv' => $pv,
'uv' => $uv,
'todayPostCount' => $todayPostCount,
'todayOrderAmount' => round($todayOrderAmount, 2),
'memberCount' => $memberCount,
'merchantCount' => $merchantCount,
'commissionTotal' => round($commissionTotal, 2),
'pendingAudit' => $pendingAudit,
'postGrowth' => 0.0,
'orderGrowth' => 0.0,
'userGrowth' => 0.0,
]);
}
/**
* AD2 趋势(近 7 天,含当天)
* GET /api/v1/admin/dashboard/trend 入参 {type} type∈traffic|revenue|userGrowth
* traffic → [{date,pv,uv}] uv=当天新增用户
* revenue → [{date,amount}] 当天 paid 订单金额
* userGrowth → [{date,newUser,totalUser}]
* 未知 type 回退 traffic
*/
public function trend()
{
$type = (string)$this->input('type', 'traffic');
if (!in_array($type, ['traffic', 'revenue', 'userGrowth'], true)) {
$type = 'traffic';
}
$days = [];
for ($i = 6; $i >= 0; $i--) {
$days[] = date('Y-m-d', strtotime('-' . $i . ' day'));
}
$result = [];
foreach ($days as $date) {
$start = strtotime($date);
$end = $start + 86400;
if ($type === 'traffic') {
$pv = (int)Db::name('fc_post')->where('createtime', '>=', $start)
->where('createtime', '<', $end)->sum('views');
$uv = (int)Db::name('user')->where('jointime', '>=', $start)
->where('jointime', '<', $end)->count();
$result[] = ['date' => $date, 'pv' => $pv, 'uv' => $uv];
} elseif ($type === 'revenue') {
$amount = (float)Db::name('fc_order')->where('status', 'paid')
->where('createtime', '>=', $start)->where('createtime', '<', $end)->sum('amount');
$result[] = ['date' => $date, 'amount' => round($amount, 2)];
} else {
$newUser = (int)Db::name('user')->where('jointime', '>=', $start)
->where('jointime', '<', $end)->count();
$totalUser = (int)Db::name('user')->where('jointime', '<', $end)->count();
$result[] = ['date' => $date, 'newUser' => $newUser, 'totalUser' => $totalUser];
}
}
$this->ok($result);
}
}

查看文件

@@ -0,0 +1,141 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 分销管理(Module-ADM-DIST)
* 路由:
* GET /api/v1/admin/dist/setting AD1 分销设置读取
* POST /api/v1/admin/dist/setting AD2 分销设置保存
* GET /api/v1/admin/dist/withdraws AD3 提现申请列表
* POST /api/v1/admin/dist/withdraw/:id/pay AD4 提现审核(打款/驳回)
*/
class AdminDist extends V1
{
/**
* AD1 分销设置读取
* GET /api/v1/admin/dist/setting → {enabled,level,level1Rate,level2Rate,settleCycle,minWithdraw}
*/
public function setting()
{
if ($this->request->isPost()) {
$this->saveSetting();
}
$this->ok($this->distConfig());
}
/**
* AD2 分销设置保存
* POST /api/v1/admin/dist/setting 入参 {enabled,level,level1Rate,level2Rate,settleCycle,minWithdraw}
* 规则 BR-08:一级+二级分佣比例不能超过 100%
*/
public function saveSetting()
{
$enabled = $this->input('enabled', $this->cfg('dist.enabled', 1));
$level = (int)$this->input('level', $this->cfg('dist.level', 2));
$level1Rate = (float)$this->input('level1Rate', $this->cfg('dist.level1Rate', 20));
$level2Rate = (float)$this->input('level2Rate', $this->cfg('dist.level2Rate', 10));
$settleCycle = (string)$this->input('settleCycle', $this->cfg('dist.settleCycle', 'T+7'));
$minWithdraw = (float)$this->input('minWithdraw', $this->cfg('dist.minWithdraw', 50));
if ($level1Rate + $level2Rate > 100) {
$this->fail('一级+二级分佣比例不能超过 100%');
}
$this->setCfg('dist.enabled', $enabled ? 1 : 0);
$this->setCfg('dist.level', $level);
$this->setCfg('dist.level1Rate', $level1Rate);
$this->setCfg('dist.level2Rate', $level2Rate);
$this->setCfg('dist.settleCycle', $settleCycle);
$this->setCfg('dist.minWithdraw', $minWithdraw);
$this->adminLog('修改分销设置');
$this->ok($this->distConfig());
}
/**
* AD3 提现申请列表
* GET /api/v1/admin/dist/withdraws → 数组 [{id,withdrawNo,user,amount,status,channel,createdAt}]
*/
public function withdraws()
{
$rows = Db::name('fc_withdraw')->alias('w')
->join('user u', 'u.id = w.user_id', 'LEFT')
->field('w.*, u.nickname AS nickname')
->order('w.createtime desc')
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'withdrawNo' => (string)$row['withdraw_no'],
'user' => (string)$row['nickname'],
'amount' => (float)$row['amount'],
'status' => (string)$row['status'],
'channel' => (string)$row['channel'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($list);
}
/**
* AD4 提现审核
* POST /api/v1/admin/dist/withdraw/:id/pay 入参 {op,reason?} → {id,status}
* 规则 BR-09:op=reject 时 reason 必填
*/
public function handleWithdraw()
{
$id = (int)$this->request->param('id', 0);
$op = (string)$this->input('op', '');
$reason = trim((string)$this->input('reason', ''));
if ($op === 'reject' && $reason === '') {
$this->fail('驳回需填写原因');
}
$withdraw = Db::name('fc_withdraw')->where('id', $id)->find();
if (!$withdraw) {
$this->fail('提现记录不存在', 404);
}
if ($op === 'reject') {
$status = 'rejected';
Db::name('fc_withdraw')->where('id', $id)->update([
'status' => $status,
'reason' => $reason,
]);
$this->notify($withdraw['user_id'], 'system', '提现被驳回', '您的提现申请被驳回:' . $reason);
} else {
$status = 'paid';
Db::name('fc_withdraw')->where('id', $id)->update([
'status' => $status,
'paytime' => time(),
]);
$this->flow('expense', '佣金提现', $withdraw['amount'], 0, $id);
$this->notify($withdraw['user_id'], 'system', '提现已打款', '您的提现申请已打款,请注意查收。');
}
$this->adminLog('处理提现 #' . $id . ' 结果' . $status);
$this->ok(['id' => (int)$id, 'status' => $status]);
}
/** 组装分销设置结构 */
protected function distConfig()
{
return [
'enabled' => (bool)$this->cfg('dist.enabled', 1),
'level' => (int)$this->cfg('dist.level', 2),
'level1Rate' => (float)$this->cfg('dist.level1Rate', 20),
'level2Rate' => (float)$this->cfg('dist.level2Rate', 10),
'settleCycle' => (string)$this->cfg('dist.settleCycle', 'T+7'),
'minWithdraw' => (float)$this->cfg('dist.minWithdraw', 50),
];
}
}

查看文件

@@ -0,0 +1,129 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 财务管理(Module-ADM-FINANCE)
* 路由:
* GET /api/v1/admin/finance/flows AF1 资金流水
* GET /api/v1/admin/finance/report AF2 财务报表
*/
class AdminFinance extends V1
{
/**
* AF1 资金流水
* GET /api/v1/admin/finance/flows 入参 {type?,page,size}
* → 分页 {list:[{id,flowNo,type,scene,amount,balance,createdAt}],page,size,total,hasMore}
*/
public function flows()
{
list($page, $size) = $this->pager();
$type = trim((string)$this->input('type', ''));
$query = Db::name('fc_finance_flow');
if ($type !== '') {
$query->where('type', $type);
}
$total = $query->count();
$rows = $query->order('createtime desc')->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'flowNo' => (string)$row['flow_no'],
'type' => (string)$row['type'],
'scene' => (string)$row['scene'],
'amount' => (float)$row['amount'],
'balance' => (float)$row['balance'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* AF2 财务报表
* GET /api/v1/admin/finance/report 入参 {period: day|month|year}
* → {period, rows:[{period,postIncome,memberIncome,rechargeIncome,withdraw,net}]}
*/
public function report()
{
$period = trim((string)$this->input('period', 'day'));
if (!in_array($period, ['day', 'month', 'year'], true)) {
$period = 'day';
}
$fmtMap = ['day' => '%Y-%m-%d', 'month' => '%Y-%m', 'year' => '%Y'];
$fmt = $fmtMap[$period];
$post = $this->periodOrderSum('post', $fmt);
$member = $this->periodOrderSum('member', $fmt);
$recharge = $this->periodOrderSum('recharge', $fmt);
$withdraw = $this->periodWithdrawSum($fmt);
$keys = array_unique(array_merge(
array_keys($post),
array_keys($member),
array_keys($recharge),
array_keys($withdraw)
));
sort($keys);
$rows = [];
foreach ($keys as $k) {
$p = isset($post[$k]) ? (float)$post[$k] : 0;
$m = isset($member[$k]) ? (float)$member[$k] : 0;
$r = isset($recharge[$k]) ? (float)$recharge[$k] : 0;
$w = isset($withdraw[$k]) ? (float)$withdraw[$k] : 0;
$rows[] = [
'period' => (string)$k,
'postIncome' => $p,
'memberIncome' => $m,
'rechargeIncome' => $r,
'withdraw' => $w,
'net' => round($p + $m + $r - $w, 2),
];
}
$this->ok(['period' => $period, 'rows' => $rows]);
}
/** 按周期聚合某类已支付订单金额,返回 [period => total] */
protected function periodOrderSum($type, $fmt)
{
$rows = Db::name('fc_order')
->where('status', 'paid')
->where('type', $type)
->field("FROM_UNIXTIME(createtime, '{$fmt}') AS period, SUM(amount) AS total")
->group('period')
->select();
$map = [];
foreach ($rows as $row) {
$map[$row['period']] = (float)$row['total'];
}
return $map;
}
/** 按周期聚合已打款提现金额,返回 [period => total] */
protected function periodWithdrawSum($fmt)
{
$rows = Db::name('fc_withdraw')
->where('status', 'paid')
->whereNotNull('paytime')
->field("FROM_UNIXTIME(paytime, '{$fmt}') AS period, SUM(amount) AS total")
->group('period')
->select();
$map = [];
foreach ($rows as $row) {
$map[$row['period']] = (float)$row['total'];
}
return $map;
}
}

查看文件

@@ -0,0 +1,110 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 会员管理(Module-ADM-MEMBER)
* 路由:
* GET /api/v1/admin/users AMB1 用户列表
* POST /api/v1/admin/member/benefit AMB2 会员权益配置
*/
class AdminMember extends V1
{
/**
* AMB1 用户列表
* GET /api/v1/admin/users 入参 {page,size}
* → 分页 {list:[{id,nickname,phone,userType,isMember,status,registerAt}],page,size,total,hasMore}
*/
public function users()
{
list($page, $size) = $this->pager();
$query = Db::name('user')->alias('u')
->join('fc_user_ext e', 'e.user_id = u.id', 'LEFT');
$total = (int)$query->count();
$rows = $query->field('u.id,u.nickname,u.mobile,u.status,u.jointime,e.user_type,e.is_member,e.member_expiretime')
->order('u.id desc')
->page($page, $size)
->select();
$now = time();
$list = [];
foreach ($rows as $row) {
$isMember = (int)$row['is_member'] === 1
&& (!$row['member_expiretime'] || (int)$row['member_expiretime'] > $now);
$list[] = [
'id' => (int)$row['id'],
'nickname' => (string)$row['nickname'],
'phone' => (string)$row['mobile'],
'userType' => (int)$row['user_type'],
'isMember' => $isMember,
'status' => $row['status'] === 'normal' ? 1 : 0,
'registerAt' => $this->iso($row['jointime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* AMB2 会员权益配置
* POST /api/v1/admin/member/benefit 入参 {freeView,postDiscount,distRate,benefits[]}
* → {freeView,postDiscount,distRate,benefits[]}
* 未被传入的字段保持原值;freeView <0 报错
*/
public function saveBenefit()
{
$current = $this->cfg('member.benefit', []);
if (!is_array($current)) {
$current = [];
}
$freeView = $this->input('freeView', null);
if ($freeView !== null && $freeView !== '') {
if ((int)$freeView < 0) {
$this->fail('免费查看条数不能为负');
}
$current['freeView'] = (int)$freeView;
}
$postDiscount = $this->input('postDiscount', null);
if ($postDiscount !== null && $postDiscount !== '') {
$current['postDiscount'] = (string)$postDiscount;
}
$distRate = $this->input('distRate', null);
if ($distRate !== null && $distRate !== '') {
$current['distRate'] = (string)$distRate;
}
$benefits = $this->input('benefits', null);
if ($benefits !== null && $benefits !== '') {
if (is_array($benefits)) {
$current['benefits'] = array_values($benefits);
} else {
$decoded = json_decode((string)$benefits, true);
$current['benefits'] = is_array($decoded) ? $decoded : [(string)$benefits];
}
}
$defaults = [
'freeView' => 20,
'postDiscount' => '8 折',
'distRate' => '一级 20% / 二级 10%',
'benefits' => [],
];
$current = array_merge($defaults, $current);
$this->setCfg('member.benefit', $current);
$this->adminLog('修改会员权益配置');
$this->ok([
'freeView' => (int)$current['freeView'],
'postDiscount' => (string)$current['postDiscount'],
'distRate' => (string)$current['distRate'],
'benefits' => array_values((array)$current['benefits']),
]);
}
}

查看文件

@@ -0,0 +1,98 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 商家管理(Module-ADM-MERCHANT)
* 路由:
* GET /api/v1/admin/merchants AM1 商家列表
* POST /api/v1/admin/merchant/:id/audit AM2 商家资质审核
*/
class AdminMerchant extends V1
{
/**
* AM1 商家列表
* GET /api/v1/admin/merchants 入参 {status?,keyword?,page,size}
* → 分页 {list:[{id,name,logo,contact,category,auditStatus,license,shopStatus,violations,postCount,createdAt}],page,size,total,hasMore}
* 注意:id 返回 fc_merchant.user_id(与前端商家列表一致)
*/
public function index()
{
list($page, $size) = $this->pager();
$status = $this->input('status', '');
$keyword = trim((string)$this->input('keyword', ''));
$query = Db::name('fc_merchant');
if ($status !== '' && $status !== null) {
$query->where('audit_status', (int)$status);
}
if ($keyword !== '') {
$query->where('name', 'like', '%' . $keyword . '%');
}
$total = $query->count();
$rows = $query->order('id desc')->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['user_id'],
'name' => (string)$row['name'],
'logo' => (string)$row['logo'],
'contact' => (string)$row['contact'],
'category' => (string)$row['category'],
'auditStatus' => (int)$row['audit_status'],
'license' => (string)$row['license'],
'shopStatus' => (string)$row['shop_status'],
'violations' => (int)$row['violations'],
'postCount' => (int)$row['post_count'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* AM2 商家资质审核
* POST /api/v1/admin/merchant/:id/audit 入参 {auditStatus,reason?} → {id,auditStatus}
* 规则 BR-11:auditStatus 仅允许 1(通过)/2(驳回)
*/
public function audit()
{
$id = (int)$this->request->param('id', 0);
$auditStatus = (int)$this->input('auditStatus', 0);
$reason = trim((string)$this->input('reason', ''));
if (!in_array($auditStatus, [1, 2], true)) {
$this->fail('审核状态仅支持通过(1)/驳回(2)');
}
$merchant = Db::name('fc_merchant')->where('user_id', $id)->find();
if (!$merchant) {
$this->fail('商家不存在', 404);
}
Db::name('fc_merchant')->where('user_id', $id)->update([
'audit_status' => $auditStatus,
'audit_reason' => $reason,
'shop_status' => $auditStatus === 1 ? 'normal' : 'banned',
'updatetime' => time(),
]);
if ($auditStatus === 1) {
Db::name('fc_user_ext')->where('user_id', $id)->update([
'user_type' => 2,
'updatetime' => time(),
]);
$this->notify($id, 'system', '商家资质审核结果', '恭喜,您的商家资质已通过审核。');
} else {
$this->notify($id, 'system', '商家资质审核结果', '您的商家资质未通过:' . $reason);
}
$this->adminLog('审核商家 #' . $id . ' 结果' . $auditStatus);
$this->ok(['id' => $id, 'auditStatus' => $auditStatus]);
}
}

查看文件

@@ -0,0 +1,118 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 订单管理(Module-ADM-ORDER)
* 路由:
* GET /api/v1/admin/orders AO1 订单列表
* POST /api/v1/admin/order/:id/refund AO2 订单退款
* POST /api/v1/admin/order/supplement AO3 订单补单
*/
class AdminOrder extends V1
{
/**
* AO1 订单列表
* GET /api/v1/admin/orders 入参 {type?,page,size}
* → 分页 {list:[{id,orderNo,type,title,amount,payType,status,userId,userName,createdAt}],page,size,total,hasMore}
*/
public function index()
{
list($page, $size) = $this->pager();
$type = trim((string)$this->input('type', ''));
$query = Db::name('fc_order')->alias('o')
->join('user u', 'u.id = o.user_id', 'LEFT');
if ($type !== '') {
$query->where('o.type', $type);
}
$total = $query->count();
$rows = $query->field('o.*, u.nickname AS nickname')
->order('o.createtime desc')
->page($page, $size)
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'orderNo' => (string)$row['order_no'],
'type' => (string)$row['type'],
'title' => (string)$row['title'],
'amount' => (float)$row['amount'],
'payType' => (string)$row['pay_type'],
'status' => (string)$row['status'],
'userId' => (int)$row['user_id'],
'userName' => (string)$row['nickname'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* AO2 订单退款
* POST /api/v1/admin/order/:id/refund 入参 {amount,reason?} → {id,refunded}
* 规则 BR-10:退款金额需大于 0
*/
public function refund()
{
$id = (int)$this->request->param('id', 0);
$amount = round((float)$this->input('amount', 0), 2);
$reason = trim((string)$this->input('reason', ''));
if ($amount <= 0) {
$this->fail('退款金额需大于 0');
}
$order = Db::name('fc_order')->where('id', $id)->find();
if (!$order) {
$this->fail('订单不存在', 404);
}
Db::name('fc_order')->where('id', $id)->update([
'status' => 'refunded',
'refund_amount' => $amount,
'refund_reason' => $reason,
]);
$this->notify($order['user_id'], 'system', '订单已退款', '您的订单「' . $order['title'] . '」已退款 ' . $amount . ' 元。');
$this->adminLog('订单退款 #' . $id . ' 金额' . $amount);
$this->ok(['id' => (int)$id, 'refunded' => true]);
}
/**
* AO3 订单补单
* POST /api/v1/admin/order/supplement 入参 {orderNo} → {orderNo,supplemented}
* 幂等:已支付直接返回
*/
public function supplement()
{
$orderNo = trim((string)$this->input('orderNo', ''));
if ($orderNo === '') {
$this->fail('订单号不能为空');
}
$order = Db::name('fc_order')->where('order_no', $orderNo)->find();
if (!$order) {
$this->fail('订单不存在', 404);
}
if ($order['status'] !== 'paid') {
Db::name('fc_order')->where('id', $order['id'])->update([
'status' => 'paid',
'paytime' => time(),
]);
$this->flow('income', '订单补单', $order['amount'], 0, $order['id']);
$this->adminLog('订单补单 #' . $orderNo);
}
$this->ok(['orderNo' => (string)$orderNo, 'supplemented' => true]);
}
}

查看文件

@@ -0,0 +1,120 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 信息审核(Module-ADM-AUDIT)
* 路由:
* GET /api/v1/admin/posts/pending AP1 待审核信息列表
* POST /api/v1/admin/post/:id/audit AP2 信息审核(通过/驳回)
* POST /api/v1/admin/post/:id/offline AP3 信息下架
*/
class AdminPost extends V1
{
/**
* AP1 待审核信息列表
* GET /api/v1/admin/posts/pending 入参 {page,size}
* → 分页 {list:[{id,title,categoryId,categoryName,userId,userName,area,price,priceUnit,createdAt,isPaid,content}],page,size,total,hasMore}
* 条件:audit_status=0 且未删除(deletetime is null),按 createtime 升序
*/
public function pending()
{
list($page, $size) = $this->pager();
$query = Db::name('fc_post')->alias('p')
->join('fc_category c', 'c.id = p.category_id', 'LEFT')
->join('user u', 'u.id = p.user_id', 'LEFT')
->where('p.audit_status', 0)
->whereNull('p.deletetime');
$total = $query->count();
$rows = $query->field('p.*, c.name AS category_name, u.nickname AS user_name')
->order('p.createtime asc')
->page($page, $size)
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'title' => (string)$row['title'],
'categoryId' => (int)$row['category_id'],
'categoryName' => (string)$row['category_name'],
'userId' => (int)$row['user_id'],
'userName' => (string)$row['user_name'],
'area' => (string)$row['area'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'createdAt' => $this->iso($row['createtime']),
'isPaid' => (bool)$row['is_paid'],
'content' => (string)$row['content'],
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* AP2 信息审核
* POST /api/v1/admin/post/:id/audit 入参 {auditStatus,reason?} → {id,auditStatus}
* 规则 BR-11:auditStatus 仅允许 1(通过)/2(驳回)
*/
public function audit()
{
$id = (int)$this->request->param('id', 0);
$auditStatus = (int)$this->input('auditStatus', 0);
$reason = trim((string)$this->input('reason', ''));
if (!in_array($auditStatus, [1, 2], true)) {
$this->fail('审核状态仅支持通过(1)/驳回(2)');
}
$post = Db::name('fc_post')->where('id', $id)->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
Db::name('fc_post')->where('id', $id)->update([
'audit_status' => $auditStatus,
'audit_reason' => $reason,
'updatetime' => time(),
]);
if ($auditStatus === 1) {
Db::name('fc_category')->where('id', $post['category_id'])->setInc('post_count');
$this->notify($post['user_id'], 'system', '审核通过', '您发布的信息「' . $post['title'] . '」已审核通过。');
} else {
$this->notify($post['user_id'], 'system', '审核驳回', '您发布的信息「' . $post['title'] . '」被驳回:' . $reason);
}
$this->adminLog('审核信息 #' . $id . ' 结果' . $auditStatus);
$this->ok(['id' => (int)$id, 'auditStatus' => (int)$auditStatus]);
}
/**
* AP3 信息下架
* POST /api/v1/admin/post/:id/offline → {id,offline}
*/
public function offline()
{
$id = (int)$this->request->param('id', 0);
$post = Db::name('fc_post')->where('id', $id)->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
Db::name('fc_post')->where('id', $id)->update([
'status' => 0,
'updatetime' => time(),
]);
$this->notify($post['user_id'], 'system', '信息已下架', '您发布的信息「' . $post['title'] . '」已被下架。');
$this->adminLog('下架信息 #' . $id);
$this->ok(['id' => (int)$id, 'offline' => true]);
}
}

查看文件

@@ -0,0 +1,151 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 权限管理(Module-ADM-RBAC)
* 路由:
* GET /api/v1/admin/roles AR1 角色列表
* POST /api/v1/admin/role AR2 新增/保存角色
* GET /api/v1/admin/accounts AR3 子账号列表
* GET /api/v1/admin/logs AR4 操作日志
*
* 注意:fa_auth_group 实际无 remark 字段(id,pid,name,rules,createtime,updatetime,status),
* roles() 的 remark 固定返回 '';saveRole() 写库不写 remark。
*/
class AdminRbac extends V1
{
/**
* AR1 角色列表
* GET /api/v1/admin/roles → 数组 [{id,name,permissions,remark}]
*/
public function roles()
{
$rows = Db::name('auth_group')->order('id asc')->select();
$list = [];
foreach ($rows as $row) {
$rules = (string)$row['rules'];
if ($rules === '*') {
$permissions = ['*'];
} else {
$permissions = array_values(array_filter(array_map('strval', explode(',', $rules)), function ($v) {
return $v !== '';
}));
}
$list[] = [
'id' => (int)$row['id'],
'name' => (string)$row['name'],
'permissions' => $permissions,
'remark' => '',
];
}
$this->ok($list);
}
/**
* AR2 新增/保存角色
* POST /api/v1/admin/role 入参 {name,permissions[],remark?,id?} → {id,name,permissions,remark}
* 规则 BR-12:name 必填、permissions 非空
*/
public function saveRole()
{
$id = (int)$this->input('id', 0);
$name = trim((string)$this->input('name', ''));
$remark = trim((string)$this->input('remark', ''));
$permissions = (array)$this->input('permissions', []);
$permissions = array_values(array_filter(array_map(function ($v) {
return (string)$v;
}, $permissions), function ($v) {
return $v !== '';
}));
if ($name === '') {
$this->fail('请填写角色名称');
}
if (empty($permissions)) {
$this->fail('请至少分配一项权限');
}
$rules = implode(',', $permissions);
$data = [
'name' => $name,
'rules' => $rules,
'pid' => 0,
'status' => 'normal',
'updatetime' => time(),
];
if ($id && Db::name('auth_group')->where('id', $id)->find()) {
Db::name('auth_group')->where('id', $id)->update($data);
} else {
$data['createtime'] = time();
$id = Db::name('auth_group')->insertGetId($data);
}
$this->adminLog('保存角色 #' . $id . ' ' . $name);
$this->ok([
'id' => (int)$id,
'name' => $name,
'permissions' => $permissions,
'remark' => $remark,
]);
}
/**
* AR3 子账号列表
* GET /api/v1/admin/accounts → 数组 [{id,username,roleId,roleName,status,lastLoginAt}]
*/
public function accounts()
{
$groups = Db::name('auth_group')->column('name', 'id');
$rows = Db::name('admin')->order('id asc')->select();
$list = [];
foreach ($rows as $row) {
$gid = (int)$row['group_id'];
$roleName = ($gid && isset($groups[$gid])) ? (string)$groups[$gid] : '';
$list[] = [
'id' => (int)$row['id'],
'username' => (string)$row['username'],
'roleId' => $gid,
'roleName' => $roleName,
'status' => ((int)$row['logintime'] > 0) ? 1 : 0,
'lastLoginAt' => $this->iso($row['logintime']),
];
}
$this->ok($list);
}
/**
* AR4 操作日志
* GET /api/v1/admin/logs 入参 {page,size}
* → 分页 {list:[{id,account,action,ip,createdAt}],page,size,total,hasMore}
*/
public function logs()
{
list($page, $size) = $this->pager();
$total = Db::name('admin_log')->count();
$rows = Db::name('admin_log')->order('createtime desc')->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'account' => (string)$row['username'],
'action' => (string)$row['title'],
'ip' => (string)$row['ip'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
}

查看文件

@@ -0,0 +1,270 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 后台管理端 · 系统设置(Module-ADM-SETTING)
* 路由:
* GET|POST /api/v1/admin/setting/base AS1 基础配置
* POST /api/v1/admin/setting/pay AS2 微信支付配置
* GET|POST /api/v1/admin/setting/fee AS3 费用配置
* GET /api/v1/admin/setting/areas AS4 区域列表
* POST /api/v1/admin/setting/area AS5 保存区域
* GET|POST /api/v1/admin/setting/ui AS6 站点 UI 配置
* POST /api/v1/admin/setting/ui/reset AS7 重置 UI 配置
* POST /api/v1/admin/upload AS8 文件上传
*/
class AdminSetting extends V1
{
/**
* AS1 基础配置
* GET → {appName,logo,servicePhone,aboutUs,shareTitle}
* POST 入参 {appName,logo,servicePhone,aboutUs,shareTitle} → 合并后的完整配置
*/
public function base()
{
if ($this->request->isPost()) {
$appName = trim((string)$this->input('appName', ''));
if ($appName === '') {
$this->fail('小程序名称不能为空');
}
$this->setCfg('base.appName', $appName);
$this->setCfg('base.logo', (string)$this->input('logo', $this->cfg('base.logo', '')));
$this->setCfg('base.servicePhone', (string)$this->input('servicePhone', $this->cfg('base.servicePhone', '400-000-0000')));
$this->setCfg('base.aboutUs', (string)$this->input('aboutUs', $this->cfg('base.aboutUs', '')));
$this->setCfg('base.shareTitle', (string)$this->input('shareTitle', $this->cfg('base.shareTitle', '')));
$this->adminLog('修改基础配置');
}
$this->ok($this->baseConfig());
}
/**
* AS2 微信支付配置
* POST /api/v1/admin/setting/pay 入参 {mchId,apiKey} → {configured:true}
*/
public function pay()
{
$mchId = trim((string)$this->input('mchId', ''));
$apiKey = trim((string)$this->input('apiKey', ''));
if ($mchId === '') {
$this->fail('微信支付商户号不能为空');
}
if ($apiKey === '') {
$this->fail('支付密钥不能为空');
}
$this->setCfg('pay.mchId', $mchId);
$this->setCfg('pay.apiKey', $apiKey);
$this->adminLog('修改微信支付配置');
$this->ok(['configured' => true]);
}
/**
* AS3 费用配置
* GET → {singlePost,freePostPerDay,memberMonth,memberQuarter,memberYear}
* POST 入参同字段 → 合并后配置;同时同步 fc_plan 价格
*/
public function fee()
{
if ($this->request->isPost()) {
$singlePost = (float)$this->input('singlePost', $this->cfg('fee.singlePost', 5));
if ($singlePost < 0) {
$this->fail('单条发布价格不能为负');
}
$freePostPerDay = (int)$this->input('freePostPerDay', $this->cfg('fee.freePostPerDay', 2));
$memberMonth = (float)$this->input('memberMonth', $this->cfg('fee.memberMonth', 19.9));
$memberQuarter = (float)$this->input('memberQuarter', $this->cfg('fee.memberQuarter', 49.9));
$memberYear = (float)$this->input('memberYear', $this->cfg('fee.memberYear', 168));
$this->setCfg('fee.singlePost', $singlePost);
$this->setCfg('fee.freePostPerDay', $freePostPerDay);
$this->setCfg('fee.memberMonth', $memberMonth);
$this->setCfg('fee.memberQuarter', $memberQuarter);
$this->setCfg('fee.memberYear', $memberYear);
Db::name('fc_plan')->where('plan_code', 'M1')->update(['price' => $memberMonth]);
Db::name('fc_plan')->where('plan_code', 'M3')->update(['price' => $memberQuarter]);
Db::name('fc_plan')->where('plan_code', 'M12')->update(['price' => $memberYear]);
$this->adminLog('修改费用配置');
}
$this->ok($this->feeConfig());
}
/**
* AS4 区域列表
* GET /api/v1/admin/setting/areas → 数组 [{id,name,sort,enabled}]
*/
public function areas()
{
$rows = Db::name('fc_area')->order('sort asc')->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'name' => (string)$row['name'],
'sort' => (int)$row['sort'],
'enabled' => (bool)$row['enabled'],
];
}
$this->ok($list);
}
/**
* AS5 保存区域
* POST /api/v1/admin/setting/area 入参 {id?,name,sort,enabled} → {id,name}
*/
public function saveArea()
{
$id = (int)$this->input('id', 0);
$name = trim((string)$this->input('name', ''));
$sort = (int)$this->input('sort', 0);
$enabled = (bool)$this->input('enabled', true);
if ($name === '') {
$this->fail('区域名称不能为空');
}
$data = [
'name' => $name,
'sort' => $sort,
'enabled' => $enabled ? 1 : 0,
];
if ($id && Db::name('fc_area')->where('id', $id)->find()) {
Db::name('fc_area')->where('id', $id)->update($data);
} else {
$id = Db::name('fc_area')->insertGetId($data);
}
$this->adminLog('保存区域 #' . $id . ' ' . $name);
$this->ok(['id' => (int)$id, 'name' => $name]);
}
/**
* AS6 站点 UI 配置(LOGO / 图标)
* GET → {siteName,logo,icons,updatedAt}
* POST 入参 {siteName?,logo?,icons?}(合并语义:只覆盖传入的 key) → 完整配置
*/
public function ui()
{
if ($this->request->isPost()) {
$siteName = $this->input('siteName', null);
if ($siteName !== null) {
$this->setCfg('ui.siteName', (string)$siteName);
}
$logo = $this->input('logo', null);
if ($logo !== null) {
$this->setCfg('ui.logo', (string)$logo);
}
$icons = $this->input('icons', null);
if ($icons !== null) {
if (is_string($icons)) {
$icons = json_decode($icons, true);
}
$icons = is_array($icons) ? $icons : (array)$icons;
$merged = (array)$this->cfg('ui.icons', []);
foreach ($icons as $k => $v) {
if (!is_string($v)) {
$this->fail('图标 ' . $k . ' 的地址必须是字符串');
}
$merged[$k] = $v;
}
$this->setCfg('ui.icons', $merged);
}
$this->setCfg('ui.updatedAt', date('c'));
$this->adminLog('修改LOGO与图标配置');
}
$this->ok($this->uiConfig());
}
/**
* AS7 重置 UI 配置
* POST /api/v1/admin/setting/ui/reset → {siteName,logo,icons,reset}
*/
public function uiReset()
{
$this->setCfg('ui.logo', '');
$this->setCfg('ui.icons', []);
$this->setCfg('ui.updatedAt', date('c'));
$this->adminLog('重置LOGO与图标配置');
$this->ok([
'siteName' => (string)$this->cfg('ui.siteName', '同城分类信息'),
'logo' => '',
'icons' => (object)[],
'reset' => true,
]);
}
/**
* AS8 文件上传
* POST /api/v1/admin/upload multipart 字段 file → {url}
*/
public function upload()
{
$file = $this->request->file('file');
if (!$file) {
$this->fail('未接收到上传文件');
}
try {
$upload = new \app\common\library\Upload($file);
$attachment = $upload->upload();
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
$this->ok(['url' => cdnurl($attachment->url, true)]);
}
/** 基础配置结构 */
protected function baseConfig()
{
return [
'appName' => (string)$this->cfg('base.appName', '同城分类信息'),
'logo' => (string)$this->cfg('base.logo', ''),
'servicePhone' => (string)$this->cfg('base.servicePhone', '400-000-0000'),
'aboutUs' => (string)$this->cfg('base.aboutUs', ''),
'shareTitle' => (string)$this->cfg('base.shareTitle', ''),
];
}
/** 费用配置结构 */
protected function feeConfig()
{
return [
'singlePost' => (float)$this->cfg('fee.singlePost', 5),
'freePostPerDay' => (int)$this->cfg('fee.freePostPerDay', 2),
'memberMonth' => (float)$this->cfg('fee.memberMonth', 19.9),
'memberQuarter' => (float)$this->cfg('fee.memberQuarter', 49.9),
'memberYear' => (float)$this->cfg('fee.memberYear', 168),
];
}
/** UI 配置结构(icons 保证为对象) */
protected function uiConfig()
{
$icons = $this->cfg('ui.icons', []);
$icons = is_array($icons) ? $icons : (array)$icons;
return [
'siteName' => (string)$this->cfg('ui.siteName', '同城分类信息'),
'logo' => (string)$this->cfg('ui.logo', ''),
'icons' => (object)$icons,
'updatedAt' => (string)$this->cfg('ui.updatedAt', date('c')),
];
}
}

查看文件

@@ -0,0 +1,169 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 认证与登录(Module-AUTH)
* 路由:
* POST /api/v1/auth/wx-login A1 微信授权登录
* POST /api/v1/auth/bind-phone A2 手机号绑定
* POST /api/v1/auth/switch-type A3 个人/商家身份切换
* GET /api/v1/auth/profile A4 个人资料
*/
class Auth extends V1
{
/**
* A1 微信一键授权登录
* 入参 { code } → 出参 { token, refreshToken, userInfo }
* 规则:code 必填;首次登录自动建档并生成邀请码
*/
public function wxLogin()
{
$code = trim((string)$this->input('code', ''));
if (!$code) {
$this->fail('缺少微信授权 code');
}
$openid = $this->resolveOpenid($code);
$ext = Db::name('fc_user_ext')->where('openid', $openid)->find();
$user = $ext ? Db::name('user')->where('id', $ext['user_id'])->find() : null;
if (!$user) {
// 首次登录:自动建号
$uid = Db::name('user')->insertGetId([
'group_id' => 1,
'username' => 'wx' . substr(md5($openid), 0, 10),
'nickname' => '同城用户' . mt_rand(1000, 9999),
'password' => md5(mt_rand()),
'salt' => 'wx',
'email' => substr(md5($openid), 0, 12) . '@wx.local',
'mobile' => '',
'avatar' => '',
'level' => 1,
'money' => 0,
'score' => 0,
'status' => 'normal',
'jointime' => time(),
'joinip' => $this->request->ip(),
'createtime' => time(),
'updatetime' => time(),
]);
Db::name('fc_user_ext')->insert([
'user_id' => $uid, 'openid' => $openid, 'user_type' => 1, 'realname_status' => 0,
'is_member' => 0, 'member_level' => '', 'member_expiretime' => null,
'invite_code' => strtoupper(substr(md5('fc' . $uid), 0, 6)), 'inviter_id' => 0,
'free_view_date' => date('Y-m-d'), 'free_view_used' => 0,
'createtime' => time(), 'updatetime' => time(),
]);
$user = Db::name('user')->where('id', $uid)->find();
}
if ($user['status'] != 'normal') {
$this->fail('账号已被禁用,请联系客服');
}
$token = $this->issueToken($user['id']);
$this->ok([
'token' => $token,
'refreshToken' => md5($token . 'refresh'),
'userInfo' => $this->userInfo($user),
]);
}
/**
* A2 手机号授权绑定
* 入参 { phone } → 出参 { phone }
* 规则 BR-02:必须匹配 ^1\d{10}$
*/
public function bindPhone()
{
$user = $this->auth();
$phone = trim((string)$this->input('phone', ''));
if (!preg_match('/^1\d{10}$/', $phone)) {
$this->fail('手机号格式不正确');
}
Db::name('user')->where('id', $user['id'])->update([
'mobile' => $phone, 'updatetime' => time(),
]);
$this->ok(['phone' => $phone]);
}
/**
* A3 用户类型切换
* 入参 { userType: 1|2, license? } → 出参 { userType, needAudit }
* 规则 BR-01:切换商家必须提交营业执照,提交后进入待审核
*/
public function switchType()
{
$user = $this->auth();
$userType = (int)$this->input('userType', 0);
if (!in_array($userType, [1, 2], true)) {
$this->fail('用户类型不合法');
}
if ($userType === 2) {
$license = trim((string)$this->input('license', ''));
if (!$license) {
$this->fail('商家用户需上传营业执照完成资质认证');
}
$name = trim((string)$this->input('merchantName', ''));
$exists = Db::name('fc_merchant')->where('user_id', $user['id'])->find();
$data = [
'user_id' => $user['id'],
'name' => $name !== '' ? $name : (string)$user['nickname'],
'license' => $license,
'audit_status' => 0,
'shop_status' => 'pending',
'updatetime' => time(),
];
if ($exists) {
Db::name('fc_merchant')->where('id', $exists['id'])->update($data);
} else {
$data['createtime'] = time();
Db::name('fc_merchant')->insert($data);
}
}
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'user_type' => $userType, 'updatetime' => time(),
]);
$this->ok(['userType' => $userType, 'needAudit' => $userType === 2]);
}
/**
* A4 个人资料
* 返回 userInfo(含会员状态、余额)
*/
public function profile()
{
$user = $this->auth();
$this->ok($this->userInfo($user));
}
/**
* code -> openid
* 已配置微信参数时走 jscode2session;未配置(本地/联调)时用确定性派生,便于前后端联调。
*/
protected function resolveOpenid($code)
{
$appid = (string)$this->cfg('wx.appid', '');
$secret = (string)$this->cfg('wx.secret', '');
if ($appid && $secret) {
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid
. '&secret=' . $secret . '&js_code=' . urlencode($code) . '&grant_type=authorization_code';
$res = @json_decode(@file_get_contents($url), true);
if (!empty($res['openid'])) {
return $res['openid'];
}
}
// 未配置微信参数:若 code 本身即为 openid 标识则直接采用,否则派生
if (strpos($code, 'openid_') === 0) {
return $code;
}
return 'openid_' . md5($code);
}
}

查看文件

@@ -0,0 +1,173 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 分销中心(Module-DIST)
* 路由:
* GET /api/v1/distribution/overview D1 分销概览
* GET /api/v1/distribution/team D2 我的团队
* POST /api/v1/distribution/withdraw D3 申请提现
* GET /api/v1/distribution/withdraw-records D4 提现记录
*/
class Distribution extends V1
{
/**
* D1 分销概览
* GET /api/v1/distribution/overview → {totalCommission,settled,withdrawable,todayCommission,teamCount,l1Count,l2Count,inviteCode,posterUrl}
*/
public function overview()
{
$user = $this->auth();
$uid = (int)$user['id'];
$total = (float)Db::name('fc_commission')->where('user_id', $uid)->sum('amount');
$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', '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);
$this->ok([
'totalCommission' => round($total, 2),
'settled' => round($settled, 2),
'withdrawable' => round($withdrawable, 2),
'todayCommission' => round($todayCommission, 2),
'teamCount' => $l1 + $l2,
'l1Count' => $l1,
'l2Count' => $l2,
'inviteCode' => (string)$ext['invite_code'],
'posterUrl' => '',
]);
}
/**
* D2 我的团队
* GET /api/v1/distribution/team 入参 {level?,page,size}
* → 分页 {list:[{id,nickname,level,joinedAt,performance,commission}],page,size,total,hasMore}
*/
public function team()
{
$user = $this->auth();
$uid = (int)$user['id'];
list($page, $size) = $this->pager();
$level = $this->input('level', '');
$query = Db::name('fc_dist_relation')->alias('r')
->join('user u', 'u.id = r.user_id')
->where('r.parent_id', $uid);
if ($level !== '' && $level !== null) {
$query->where('r.level', (int)$level);
}
$total = $query->count();
$rows = $query->field('r.id,r.user_id,r.level,r.createtime,u.nickname')
->order('r.createtime desc')
->page($page, $size)
->select();
$list = [];
foreach ($rows as $row) {
$childId = (int)$row['user_id'];
$commission = (float)Db::name('fc_commission')->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;
$list[] = [
'id' => $childId,
'nickname' => (string)$row['nickname'],
'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 申请提现
* POST /api/v1/distribution/withdraw 入参 {amount,channel?} → {withdrawNo,status:'auditing'}
* 规则 BR-09:金额必填且 >0、且不超过可提现余额
*/
public function withdraw()
{
$user = $this->auth();
$uid = (int)$user['id'];
$amount = (float)$this->input('amount', 0);
if ($amount <= 0) {
$this->fail('提现金额不合法');
}
if ($amount > $this->withdrawable($uid)) {
$this->fail('提现金额超过可提现余额');
}
$channel = trim((string)$this->input('channel', ''));
if ($channel === '') {
$channel = 'wxpay';
}
$amount = round($amount, 2);
$withdrawNo = $this->orderNo('WD');
Db::name('fc_withdraw')->insert([
'withdraw_no' => $withdrawNo,
'user_id' => $uid,
'amount' => $amount,
'channel' => $channel,
'status' => 'auditing',
'reason' => '',
'paytime' => null,
'createtime' => time(),
'updatetime' => time(),
]);
$this->notify($uid, 'system', '提现申请已提交', '提现 ¥' . $amount . ' 已提交,预计 T+7 到账');
$this->ok(['withdrawNo' => $withdrawNo, 'status' => 'auditing']);
}
/**
* D4 提现记录
* GET /api/v1/distribution/withdraw-records → [{id,withdrawNo,amount,status,createdAt}]
*/
public function withdrawRecords()
{
$user = $this->auth();
$rows = Db::name('fc_withdraw')->where('user_id', $user['id'])
->order('createtime desc')->select();
$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'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($list);
}
/**
* 可提现余额 = Σ已结算佣金(status=1) - Σ(申请中/已打款)提现
*/
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', 'paid'])->sum('amount');
return $settled - $applied;
}
}

查看文件

@@ -0,0 +1,229 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 首页与展示(Module-HOME)
* 路由:
* GET /api/v1/home/banners H1 轮播广告位
* GET /api/v1/home/categories H2 分类导航
* GET /api/v1/home/search/hot H3 热门搜索
* GET /api/v1/home/feed H4 信息流
*/
class Home extends V1
{
/**
* H1 首页轮播广告位
* GET /api/v1/home/banners → [{id,title,image,link,color}]
* 规则:仅 enabled=1,按 sort asc;image 为空返回 ''
*/
public function banners()
{
$rows = Db::name('fc_banner')
->where('enabled', 1)
->order('sort asc')
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'title' => (string)$row['title'],
'image' => (string)$row['image'],
'link' => (string)$row['link'],
'color' => (string)$row['color'],
];
}
$this->ok($list);
}
/**
* H2 分类导航
* GET /api/v1/home/categories → [{id,name,iconKey,icon,color,count}]
* 规则:仅 enabled=1,按 sort asc;icon 为固定 /static/icons/ 文件名(按 id 映射)
*/
public function categories()
{
$rows = Db::name('fc_category')
->where('enabled', 1)
->order('sort asc')
->select();
$list = [];
foreach ($rows as $row) {
$id = (int)$row['id'];
$list[] = [
'id' => $id,
'name' => (string)$row['name'],
'iconKey' => (string)$row['icon_key'],
'icon' => '/static/icons/' . $this->iconFile($id),
'color' => (string)$row['color'],
'count' => (int)$row['post_count'],
];
}
$this->ok($list);
}
/**
* H3 热门搜索
* GET /api/v1/home/search/hot → [string]
* 规则:读配置 home.hotKeywords,未配置则返回默认
*/
public function hotKeywords()
{
$default = ['租房 一室一厅', '二手电动车', '急招快递员', '钢琴家教', '空调维修'];
$keywords = $this->cfg('home.hotKeywords', $default);
if (!is_array($keywords) || !$keywords) {
$keywords = $default;
}
$this->ok(array_values($keywords));
}
/**
* H4 信息流
* GET /api/v1/home/feed {categoryId?,keyword?,area?,sort?,page,size}
* → {list,page,size,total,hasMore}
* 规则:仅 audit_status=1 AND status=1 AND deletetime IS NULL
*/
public function feed()
{
list($page, $size) = $this->pager();
$categoryId = (int)$this->input('categoryId', 0);
$keyword = trim((string)$this->input('keyword', ''));
$area = trim((string)$this->input('area', ''));
$sort = (string)$this->input('sort', '');
$query = Db::name('fc_post')
->where('audit_status', 1)
->where('status', 1)
->whereNull('deletetime');
if ($categoryId > 0) {
$query->where('category_id', $categoryId);
}
if ($keyword !== '') {
$query->where('title', 'like', '%' . $keyword . '%');
}
if ($area !== '') {
$query->where('area', $area);
}
if ($sort === 'price') {
$query->order('price asc');
} elseif ($sort === 'hot') {
$query->order('views desc');
} else {
$query->order('createtime desc');
}
$counter = Db::name('fc_post')
->where('audit_status', 1)
->where('status', 1)
->whereNull('deletetime');
if ($categoryId > 0) {
$counter->where('category_id', $categoryId);
}
if ($keyword !== '') {
$counter->where('title', 'like', '%' . $keyword . '%');
}
if ($area !== '') {
$counter->where('area', $area);
}
$total = $counter->count();
$rows = $query->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$list[] = $this->buildPost($row);
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* 组装 Post 结构(与前端 mock 数据字段严格对齐)
* @param array $row fc_post 行
* @return array
*/
protected function buildPost($row)
{
$categoryName = '';
if (!empty($row['category_id'])) {
$cat = Db::name('fc_category')->where('id', $row['category_id'])->find();
if ($cat) {
$categoryName = (string)$cat['name'];
}
}
$publisher = ['id' => 0, 'name' => '', 'avatar' => '', 'isMerchant' => false, 'verified' => false];
if (!empty($row['user_id'])) {
$pub = Db::name('user')->where('id', $row['user_id'])->find();
if ($pub) {
$pubExt = Db::name('fc_user_ext')->where('user_id', $pub['id'])->find();
$isMerchant = $pubExt && (int)$pubExt['user_type'] === 2;
$publisher = [
'id' => (int)$pub['id'],
'name' => (string)$pub['nickname'],
'avatar' => (string)$pub['avatar'],
'isMerchant' => (bool)$isMerchant,
'verified' => (bool)$isMerchant,
];
}
}
$tags = [];
if (!empty($row['tags'])) {
foreach (explode(',', (string)$row['tags']) as $tag) {
$tag = trim($tag);
if ($tag !== '') {
$tags[] = $tag;
}
}
}
return [
'id' => (int)$row['id'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $categoryName,
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'cover' => (string)$row['cover'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'address' => (string)$row['address'],
'contact' => $this->maskPhone($row['phone']),
'views' => (int)$row['views'],
'likes' => (int)$row['likes'],
'isPaid' => (int)$row['is_paid'] === 1,
'auditStatus' => (int)$row['audit_status'],
'createdAt' => $this->iso($row['createtime']),
'tags' => $tags,
'publisher' => $publisher,
'commentCount' => (int)$row['comment_count'],
'distance' => (int)$row['distance'],
];
}
/**
* 分类 id → 固定图标文件名
* @param int $id
* @return string
*/
protected function iconFile($id)
{
$map = [
1 => 'cat-job.png',
2 => 'cat-house.png',
3 => 'cat-goods.png',
4 => 'cat-car.png',
5 => 'cat-service.png',
6 => 'cat-education.png',
7 => 'cat-clean.png',
8 => 'cat-friend.png',
];
return isset($map[$id]) ? $map[$id] : 'cat-job.png';
}
}

查看文件

@@ -0,0 +1,201 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 会员中心(Module-MEMBER)
* 路由:
* GET /api/v1/member/plans M1 会员套餐
* GET /api/v1/member/benefits M2 会员权益
* POST /api/v1/member/open M3 开通会员
* GET /api/v1/member/orders M4 我的订单
* GET /api/v1/member/assets M5 我的资产
*/
class Member extends V1
{
/**
* M1 会员套餐
* GET /api/v1/member/plans → [{planId,name,price,originPrice,days,tag}]
* 规则:仅 enabled=1,按 sort asc
*/
public function plans()
{
$rows = Db::name('fc_plan')
->where('enabled', 1)
->order('sort asc')
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'planId' => (string)$row['plan_code'],
'name' => (string)$row['name'],
'price' => (float)$row['price'],
'originPrice' => (float)$row['origin_price'],
'days' => (int)$row['days'],
'tag' => (string)$row['tag'],
];
}
$this->ok($list);
}
/**
* M2 会员权益
* GET /api/v1/member/benefits → {freeView,postDiscount,distRate,benefits[]}
* 规则:读配置 member.benefit,未配置返回默认
*/
public function benefits()
{
$default = [
'freeView' => 20,
'postDiscount' => '8 折',
'distRate' => '一级 20% / 二级 10%',
'benefits' => ['每日免费查看 20 条联系方式', '发布信息 8 折', '专属会员标识', '分销佣金加速结算'],
];
$cfg = $this->cfg('member.benefit', null);
if (!is_array($cfg)) {
$cfg = $default;
}
$benefits = isset($cfg['benefits']) && is_array($cfg['benefits']) && $cfg['benefits']
? array_values($cfg['benefits'])
: $default['benefits'];
$this->ok([
'freeView' => isset($cfg['freeView']) ? (int)$cfg['freeView'] : $default['freeView'],
'postDiscount' => isset($cfg['postDiscount']) ? (string)$cfg['postDiscount'] : $default['postDiscount'],
'distRate' => isset($cfg['distRate']) ? (string)$cfg['distRate'] : $default['distRate'],
'benefits' => $benefits,
]);
}
/**
* M3 开通会员
* POST /api/v1/member/open {planId,payType} → {orderNo,status,expireAt}
* 规则 BR-07;套餐按 plan_code 查;余额支付扣 fa_user.money
*/
public function open()
{
$user = $this->auth();
$planId = trim((string)$this->input('planId', ''));
if ($planId === '') {
$this->fail('请选择会员套餐');
}
$payType = (string)$this->input('payType', '');
if (!in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
}
$plan = Db::name('fc_plan')->where('plan_code', $planId)->find();
if (!$plan) {
$this->fail('套餐不存在');
}
$amount = round((float)$plan['price'], 2);
$now = time();
$orderNo = $this->orderNo('MO');
$orderId = Db::name('fc_order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'member',
'title' => (string)$plan['name'],
'amount' => $amount,
'pay_type' => $payType,
'status' => 'paid',
'paytime' => $now,
'related_id' => 0,
'createtime' => $now,
'updatetime' => $now,
]);
if ($payType === 'balance') {
$balance = (float)$user['money'];
if ($balance < $amount) {
$this->fail('余额不足');
}
$balance = round($balance - $amount, 2);
Db::name('user')->where('id', $user['id'])->update([
'money' => $balance,
'updatetime' => $now,
]);
}
$ext = $this->ext($user['id']);
$base = (int)$ext['member_expiretime'];
if ($base < $now) {
$base = $now;
}
$expire = $base + (int)$plan['days'] * 86400;
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'is_member' => 1,
'member_level' => (string)$plan['name'],
'member_expiretime' => $expire,
'updatetime' => $now,
]);
$this->flow('income', '会员开通', $amount, 0, $orderId);
$this->ok([
'orderNo' => $orderNo,
'status' => 'paid',
'expireAt' => $this->iso($expire),
]);
}
/**
* M4 我的订单
* GET /api/v1/member/orders {page,size} → {list,page,size,total,hasMore}
* 规则:按 createtime desc
*/
public function orders()
{
$user = $this->auth();
list($page, $size) = $this->pager();
$total = Db::name('fc_order')->where('user_id', $user['id'])->count();
$rows = Db::name('fc_order')
->where('user_id', $user['id'])
->order('createtime desc')
->page($page, $size)
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'orderNo' => (string)$row['order_no'],
'type' => (string)$row['type'],
'title' => (string)$row['title'],
'amount' => (float)$row['amount'],
'payType' => (string)$row['pay_type'],
'status' => (string)$row['status'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* M5 我的资产
* GET /api/v1/member/assets → {balance,coupons:[],points}
*/
public function assets()
{
$user = $this->auth();
$this->ok([
'balance' => (float)$user['money'],
'coupons' => [],
'points' => (int)$user['score'],
]);
}
}

查看文件

@@ -0,0 +1,67 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 消息中心(Module-MESSAGE)
* 路由:
* GET /api/v1/message/list M1 消息列表
* POST /api/v1/message/:id/read M2 标记已读
*
* 说明:user_id=0 表示全体广播消息,用户可见。
*/
class Message extends V1
{
/**
* M1 消息列表
* GET /api/v1/message/list 入参 {type?,page,size}
* → 分页 {list:[{id,type,title,content,read,createdAt}],page,size,total,hasMore}
*/
public function list()
{
$user = $this->auth();
$uid = (int)$user['id'];
list($page, $size) = $this->pager();
$type = $this->input('type', '');
$query = Db::name('fc_message')->where('user_id', 'in', [$uid, 0]);
if ($type !== '' && $type !== null) {
$query->where('type', $type);
}
$total = $query->count();
$rows = $query->order('createtime desc')->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'type' => (string)$row['type'],
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'read' => (bool)(int)$row['isread'],
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* M2 标记已读
* POST /api/v1/message/:id/read → {read:true}
*/
public function read()
{
$user = $this->auth();
$uid = (int)$user['id'];
$id = (int)$this->request->param('id', 0);
Db::name('fc_message')->where('id', $id)
->where('user_id', 'in', [$uid, 0])
->update(['isread' => 1, 'readtime' => time()]);
$this->ok(['read' => true]);
}
}

查看文件

@@ -0,0 +1,488 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 信息发布与详情(Module-POST)
* 路由:
* POST /api/v1/post/create P1 发布信息
* GET /api/v1/post/drafts P2 草稿列表
* POST /api/v1/post/draft P3 保存草稿
* DELETE /api/v1/post/:id P4 删除信息
* GET /api/v1/post/:id P5 信息详情
* POST /api/v1/post/:id/pay-view P6 付费查看联系方式
* POST /api/v1/post/:id/comment P7 发表评价
*/
class Post extends V1
{
/**
* P1 发布信息
* POST /api/v1/post/create
* 入参 {categoryId,title,content,media[],contact,phone,address,area,price,priceUnit,tags,paid,amount,payType}
* → {postId,auditStatus,order}
* 规则 BR-03/BR-04/BR-02
*/
public function create()
{
$user = $this->auth();
$categoryId = (int)$this->input('categoryId', 0);
$title = trim((string)$this->input('title', ''));
$content = trim((string)$this->input('content', ''));
if ($categoryId <= 0) {
$this->fail('分类不能为空');
}
if ($title === '') {
$this->fail('标题不能为空');
}
if ($content === '') {
$this->fail('内容不能为空');
}
if (mb_strlen($title) > 40) {
$this->fail('标题不能超过 40 字');
}
if (mb_strlen($content) > 500) {
$this->fail('内容不能超过 500 字');
}
$phone = trim((string)$this->input('phone', ''));
if ($phone !== '' && !preg_match('/^1\d{10}$/', $phone)) {
$this->fail('手机号格式不正确');
}
$paid = (bool)$this->input('paid', false);
$payType = (string)$this->input('payType', '');
$amount = 0;
if ($paid) {
$amount = $this->input('amount', null);
if ($amount === null || $amount === '') {
$amount = $this->cfg('fee.singlePost', 5);
}
$amount = round((float)$amount, 2);
}
$now = time();
$postId = Db::name('fc_post')->insertGetId([
'user_id' => $user['id'],
'category_id' => $categoryId,
'title' => $title,
'content' => $content,
'cover' => '',
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'price' => round((float)$this->input('price', 0), 2),
'price_unit' => (string)$this->input('priceUnit', ''),
'area' => (string)$this->input('area', ''),
'address' => (string)$this->input('address', ''),
'contact' => (string)$this->input('contact', ''),
'phone' => $phone,
'wechat' => '',
'tags' => $this->tagsString(),
'is_paid' => $paid ? 1 : 0,
'amount' => $paid ? $amount : 0,
'pay_type' => $paid ? $payType : '',
'audit_status' => 0,
'views' => 0,
'likes' => 0,
'comment_count' => 0,
'status' => 1,
'createtime' => $now,
'updatetime' => $now,
]);
$order = null;
if ($paid) {
$orderNo = $this->orderNo('PO');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'post',
'title' => $title,
'amount' => $amount,
'pay_type' => $payType,
'status' => 'pending',
'related_id' => $postId,
'createtime' => $now,
'updatetime' => $now,
]);
$order = ['orderNo' => $orderNo, 'amount' => $amount, 'payType' => $payType];
}
$this->ok([
'postId' => $postId,
'auditStatus' => 0,
'order' => $order,
]);
}
/**
* P2 草稿列表
* GET /api/v1/post/drafts → [{draftId,title,content,categoryId,savedAt}]
*/
public function drafts()
{
$user = $this->auth();
$rows = Db::name('fc_draft')
->where('user_id', $user['id'])
->order('savedat desc')
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'draftId' => (int)$row['id'],
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'categoryId' => (int)$row['category_id'],
'savedAt' => $this->iso($row['savedat']),
];
}
$this->ok($list);
}
/**
* P3 保存草稿
* POST /api/v1/post/draft {draftId?,categoryId?,title?,content?,media?,contact?,phone?,address?}
* → {draftId,savedAt,categoryId,title,content}
*/
public function saveDraft()
{
$user = $this->auth();
$draftId = (int)$this->input('draftId', 0);
$categoryId = (int)$this->input('categoryId', 0);
$title = (string)$this->input('title', '');
$content = (string)$this->input('content', '');
$now = time();
$data = [
'user_id' => $user['id'],
'category_id' => $categoryId,
'title' => $title,
'content' => $content,
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'contact' => (string)$this->input('contact', ''),
'phone' => (string)$this->input('phone', ''),
'address' => (string)$this->input('address', ''),
'savedat' => $now,
'updatetime' => $now,
];
if ($draftId > 0) {
$exist = Db::name('fc_draft')->where('id', $draftId)->find();
if (!$exist || (int)$exist['user_id'] !== (int)$user['id']) {
$this->fail('草稿不存在');
}
Db::name('fc_draft')->where('id', $draftId)->update($data);
} else {
$data['createtime'] = $now;
$draftId = Db::name('fc_draft')->insertGetId($data);
}
$this->ok([
'draftId' => $draftId,
'savedAt' => $this->iso($now),
'categoryId' => $categoryId,
'title' => $title,
'content' => $content,
]);
}
/**
* P4 删除信息(软删)
* DELETE /api/v1/post/:id → {deleted:true}
* 规则:仅能删除本人发布
*/
public function remove()
{
$user = $this->auth();
$id = $this->routeId();
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
if ((int)$post['user_id'] !== (int)$user['id']) {
$this->fail('无权操作');
}
Db::name('fc_post')->where('id', $id)->update([
'deletetime' => time(),
'updatetime' => time(),
]);
$this->ok(['deleted' => true]);
}
/**
* P5 信息详情
* GET /api/v1/post/:id → Post 结构(contact 为脱敏串,绝不返回完整手机号)
* 规则:允许游客;不存在 fail('信息不存在',404);每次浏览 views+1
*/
public function detail()
{
// GET /post/:id(详情)与 DELETE /post/:id(软删)共用同一路径,
// PHP 数组键无法为同一路径注册两条规则,故在此按请求方法分派。
if ($this->request->isDelete()) {
$this->remove();
}
$id = $this->routeId();
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
Db::name('fc_post')->where('id', $id)->setInc('views');
$post['views'] = (int)$post['views'] + 1;
$this->ok($this->buildPost($post));
}
/**
* P6 付费查看联系方式
* POST /api/v1/post/:id/pay-view {payType}
* → {unlocked:true,contact:{phone,wechat}}
* 规则 BR-05;金额取 fee.payView;会员或已解锁免费
*/
public function payView()
{
$user = $this->auth();
$id = $this->routeId();
$payType = (string)$this->input('payType', '');
if (!in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
}
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
$contact = [
'phone' => (string)$post['phone'],
'wechat' => $post['wechat'] !== '' ? (string)$post['wechat'] : ('tongcheng_' . $id),
];
// 已解锁直接返回
$exist = Db::name('fc_pay_view')
->where('user_id', $user['id'])
->where('post_id', $id)
->find();
if ($exist) {
$this->ok(['unlocked' => true, 'contact' => $contact]);
}
$amount = round((float)$this->cfg('fee.payView', 2), 2);
$now = time();
$ext = $this->ext($user['id']);
$isMember = (int)$ext['is_member'] === 1
&& (!$ext['member_expiretime'] || $ext['member_expiretime'] > $now);
$orderId = 0;
if ($isMember) {
// 会员免费解锁
$amount = 0;
$payType = 'free';
} elseif ($payType === 'balance') {
$balance = (float)$user['money'];
if ($balance < $amount) {
$this->fail('余额不足');
}
$balance = round($balance - $amount, 2);
Db::name('user')->where('id', $user['id'])->update([
'money' => $balance,
'updatetime' => $now,
]);
$this->flow('expense', '付费查看', $amount, $balance, $id);
} else {
// 微信支付:创建已支付订单
$orderId = Db::name('fc_order')->insertGetId([
'order_no' => $this->orderNo('VO'),
'user_id' => $user['id'],
'type' => 'post',
'title' => '付费查看 #' . $id,
'amount' => $amount,
'pay_type' => $payType,
'status' => 'paid',
'paytime' => $now,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
}
Db::name('fc_pay_view')->insert([
'user_id' => $user['id'],
'post_id' => $id,
'pay_type' => $payType,
'amount' => $amount,
'order_id' => $orderId,
'createtime' => $now,
]);
$this->ok(['unlocked' => true, 'contact' => $contact]);
}
/**
* P7 发表评价
* POST /api/v1/post/:id/comment {score,content} → {commentId}
* 规则 BR-06
*/
public function comment()
{
$user = $this->auth();
$id = $this->routeId();
$content = trim((string)$this->input('content', ''));
if ($content === '') {
$this->fail('评价内容不能为空');
}
$score = (int)$this->input('score', 5);
if ($score < 1 || $score > 5) {
$this->fail('评分需在 1-5 之间');
}
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
$now = time();
$commentId = Db::name('fc_comment')->insertGetId([
'post_id' => $id,
'user_id' => $user['id'],
'score' => $score,
'content' => $content,
'images' => '',
'reply' => '',
'top' => 0,
'status' => 1,
'createtime' => $now,
'updatetime' => $now,
]);
Db::name('fc_post')->where('id', $id)->setInc('comment_count');
$this->notify(
$post['user_id'],
'interact',
'收到新评价',
'用户「' . (string)$user['nickname'] . '」评价了您的信息:' . $content
);
$this->ok(['commentId' => $commentId]);
}
/**
* 读取路由 :id 参数(兼容 POST 体/查询串传入)
* @return int
*/
protected function routeId()
{
$id = (int)$this->input('id', 0);
if ($id <= 0) {
$id = (int)$this->request->param('id', 0);
}
return $id;
}
/**
* media 入参归一化为数组
* @return array
*/
protected function mediaArray()
{
$media = $this->input('media', []);
if (is_string($media)) {
$decoded = json_decode($media, true);
$media = is_array($decoded) ? $decoded : [];
}
return is_array($media) ? array_values($media) : [];
}
/**
* tags 入参归一化为逗号分隔字符串
* @return string
*/
protected function tagsString()
{
$tags = $this->input('tags', []);
if (is_array($tags)) {
$tags = implode(',', $tags);
}
return (string)$tags;
}
/**
* 组装 Post 结构(与前端 mock 数据字段严格对齐)
* @param array $row fc_post 行
* @return array
*/
protected function buildPost($row)
{
$categoryName = '';
if (!empty($row['category_id'])) {
$cat = Db::name('fc_category')->where('id', $row['category_id'])->find();
if ($cat) {
$categoryName = (string)$cat['name'];
}
}
$publisher = ['id' => 0, 'name' => '', 'avatar' => '', 'isMerchant' => false, 'verified' => false];
if (!empty($row['user_id'])) {
$pub = Db::name('user')->where('id', $row['user_id'])->find();
if ($pub) {
$pubExt = Db::name('fc_user_ext')->where('user_id', $pub['id'])->find();
$isMerchant = $pubExt && (int)$pubExt['user_type'] === 2;
$publisher = [
'id' => (int)$pub['id'],
'name' => (string)$pub['nickname'],
'avatar' => (string)$pub['avatar'],
'isMerchant' => (bool)$isMerchant,
'verified' => (bool)$isMerchant,
];
}
}
$tags = [];
if (!empty($row['tags'])) {
foreach (explode(',', (string)$row['tags']) as $tag) {
$tag = trim($tag);
if ($tag !== '') {
$tags[] = $tag;
}
}
}
return [
'id' => (int)$row['id'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $categoryName,
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'cover' => (string)$row['cover'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'address' => (string)$row['address'],
'contact' => $this->maskPhone($row['phone']),
'views' => (int)$row['views'],
'likes' => (int)$row['likes'],
'isPaid' => (int)$row['is_paid'] === 1,
'auditStatus' => (int)$row['audit_status'],
'createdAt' => $this->iso($row['createtime']),
'tags' => $tags,
'publisher' => $publisher,
'commentCount' => (int)$row['comment_count'],
'distance' => (int)$row['distance'],
];
}
}

查看文件

@@ -0,0 +1,32 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 站点 UI 配置(用户端读取,Module-SETTING)
* 路由:
* GET /api/v1/setting/ui 站点名称/LOGO/图标覆盖(允许游客访问)
*/
class Setting extends V1
{
/**
* 站点 UI 配置(游客可用)
* GET /api/v1/setting/ui
* → {siteName, logo, icons}(icons 恒为对象)
*/
public function ui()
{
$icons = $this->cfg('ui.icons', []);
if (!is_array($icons)) {
$icons = [];
}
$this->ok([
'siteName' => (string)$this->cfg('ui.siteName', '同城分类信息'),
'logo' => (string)$this->cfg('ui.logo', ''),
'icons' => (object)$icons,
]);
}
}

查看文件

@@ -0,0 +1,373 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
use think\Response;
use think\exception\HttpResponseException;
/**
* v1 业务接口基类
*
* 职责:
* 1) 统一响应结构(覆盖 FastAdmin 原生 {code,msg,time,data})
* 成功:{"code":0,"message":"ok","data":...}
* 失败:{"code":<业务码>,"message":"...","data":null}
* 2) Authorization: Bearer {token} 鉴权(前端约定,FastAdmin 原生只认 HTTP_TOKEN)
* 3) 分页结构:{list,page,size,total,hasMore}
* 4) 业务配置读写(fa_fc_config)
*
* 契约见 docs/03-接口文档.md
*/
class V1 extends Api
{
/** 全部方法自行鉴权,不走 FastAdmin 的 uri 权限匹配 */
protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*'];
/** @var \app\common\model\User|null 当前登录用户 */
protected $user = null;
/** @var bool 是否已尝试解析登录态 */
protected $resolved = false;
/* ==================== 响应输出 ==================== */
/**
* 成功响应
* @param mixed $data
* @param string $message
*/
protected function ok($data = null, $message = 'ok')
{
$this->emit(['code' => 0, 'message' => $message, 'data' => $data], 200);
}
/**
* 业务失败响应(HTTP 默认 200,前端按 code 判定)
* @param string $message
* @param int $code
* @param int $httpStatus
*/
protected function fail($message, $code = 1, $httpStatus = 200)
{
$this->emit(['code' => $code, 'message' => (string)$message, 'data' => null], $httpStatus);
}
/** 输出 JSON 并终止 */
protected function emit(array $payload, $httpStatus = 200)
{
$response = Response::create($payload, 'json', $httpStatus)
->header(['Content-Type' => 'application/json;charset=utf-8']);
throw new HttpResponseException($response);
}
/* ==================== 鉴权 ==================== */
/** 从 Authorization: Bearer xxx 提取 token */
protected function bearerToken()
{
$auth = $this->request->header('authorization', '');
if ($auth && stripos($auth, 'bearer ') === 0) {
return trim(substr($auth, 7));
}
return '';
}
/** 解析当前用户(不强制登录) */
protected function user()
{
if ($this->resolved) {
return $this->user;
}
$this->resolved = true;
$token = $this->bearerToken();
if (!$token && !($token = $this->request->request('token'))) {
return $this->user = null;
}
$row = Db::name('user_token')->where('token', $token)->find();
if (!$row) {
return $this->user = null;
}
if ($row['expiretime'] && $row['expiretime'] < time()) {
return $this->user = null;
}
$user = \app\common\model\User::get($row['user_id']);
if (!$user || $user->status != 'normal') {
return $this->user = null;
}
return $this->user = $user;
}
/** 强制登录:未登录直接 401 */
protected function auth()
{
$user = $this->user();
if (!$user) {
$this->fail('登录已过期,请重新登录', 401, 401);
}
return $user;
}
/** 当前用户 ID */
protected function userId()
{
return (int)$this->auth()->id;
}
/** 签发 token 并写入 fa_user_token */
protected function issueToken($userId, $days = 30)
{
$token = md5(mt_rand() . $userId . microtime(true) . uniqid('', true));
Db::name('user_token')->insert([
'token' => $token,
'user_id' => $userId,
'createtime' => time(),
'expiretime' => time() + $days * 86400,
]);
return $token;
}
/* ==================== 入参 ==================== */
/** 读取单个入参(POST 优先,其次 GET) */
protected function input($key, $default = null)
{
$val = $this->request->post($key, null);
if ($val === null || $val === '') {
$val = $this->request->get($key, $default);
}
return $val === null ? $default : $val;
}
/** 全部入参 */
protected function inputs()
{
return array_merge((array)$this->request->get(), (array)$this->request->post());
}
/** 必填校验,失败直接返回业务错误 */
protected function require2($fields, $data = null)
{
$data = $data === null ? $this->inputs() : $data;
foreach ((array)$fields as $f => $label) {
if (is_int($f)) {
$f = $label;
$label = $f;
}
if (!isset($data[$f]) || $data[$f] === '' || $data[$f] === null) {
$this->fail($label . '不能为空');
}
}
return true;
}
/* ==================== 分页 ==================== */
/** 解析分页参数 -> [page, size] */
protected function pager($defaultSize = 10, $maxSize = 50)
{
$page = max(1, (int)$this->input('page', 1));
$size = (int)$this->input('size', $defaultSize);
if ($size < 1) {
$size = $defaultSize;
}
if ($size > $maxSize) {
$size = $maxSize;
}
return [$page, $size];
}
/** 组装分页结构 {list,page,size,total,hasMore} */
protected function paginate($list, $total, $page, $size)
{
if (is_object($list) && method_exists($list, 'all')) {
$list = $list->all();
}
$list = array_values(is_array($list) ? $list : (array)$list);
return [
'list' => $list,
'page' => (int)$page,
'size' => (int)$size,
'total' => (int)$total,
'hasMore' => $page * $size < $total,
];
}
/** 对数组集合做内存分页(小数据集用) */
protected function paginateArray(array $items, $page, $size)
{
$total = count($items);
return $this->paginate(array_slice($items, ($page - 1) * $size, $size), $total, $page, $size);
}
/* ==================== 业务配置(fa_fc_config) ==================== */
/**
* 读取配置,key 形如 fee.singlePost / ui.logo / base.appName
* 数组/对象值以 JSON 存取
*/
protected function cfg($key, $default = null)
{
static $cache = null;
if ($cache === null) {
$cache = [];
foreach (Db::name('fc_config')->select() as $row) {
$cache[$row['key']] = $row['value'];
}
}
if (!array_key_exists($key, $cache)) {
return $default;
}
$val = $cache[$key];
$decoded = json_decode($val, true);
if (json_last_error() === JSON_ERROR_NONE && (is_array($decoded) || $decoded === null)) {
return $decoded;
}
return $val;
}
/** 写入配置 */
protected function setCfg($key, $value)
{
$val = (is_scalar($value) || $value === null) ? (string)$value : json_encode($value, JSON_UNESCAPED_UNICODE);
if (Db::name('fc_config')->where('key', $key)->find()) {
Db::name('fc_config')->where('key', $key)->update(['value' => $val, 'updatetime' => time()]);
} else {
Db::name('fc_config')->insert([
'key' => $key, 'value' => $val, 'createtime' => time(), 'updatetime' => time(),
]);
}
return true;
}
/* ==================== 工具 ==================== */
/** 时间戳 -> ISO8601(前端 new Date() 可直接解析) */
protected function iso($timestamp)
{
if (!$timestamp) {
return null;
}
if (!is_numeric($timestamp)) {
$timestamp = strtotime($timestamp);
}
return date('c', (int)$timestamp);
}
/** 手机号脱敏 */
protected function maskPhone($phone)
{
$phone = (string)$phone;
return strlen($phone) === 11 ? substr($phone, 0, 3) . '****' . substr($phone, 7) : $phone;
}
/** 生成业务单号 */
protected function orderNo($prefix)
{
return $prefix . date('YmdHis') . mt_rand(1000, 9999);
}
/* ==================== 业务公共 ==================== */
/**
* 读取用户业务扩展(不存在则初始化)
* @return array
*/
protected function ext($userId)
{
$ext = Db::name('fc_user_ext')->where('user_id', $userId)->find();
if (!$ext) {
$inviteCode = strtoupper(substr(md5('fc' . $userId . mt_rand()), 0, 6));
Db::name('fc_user_ext')->insert([
'user_id' => $userId, 'openid' => '', 'user_type' => 1, 'realname_status' => 0,
'is_member' => 0, 'member_level' => '', 'member_expiretime' => null,
'invite_code' => $inviteCode, 'inviter_id' => 0,
'free_view_date' => date('Y-m-d'), 'free_view_used' => 0,
'createtime' => time(), 'updatetime' => time(),
]);
$ext = Db::name('fc_user_ext')->where('user_id', $userId)->find();
}
return $ext;
}
/**
* 组装用户信息(与前端 common/mock/data.js 的 datasets.user 字段一致)
*/
protected function userInfo($user = null, $phone = null)
{
$user = $user ?: $this->auth();
$ext = $this->ext($user['id']);
$isMember = (int)$ext['is_member'] === 1
&& (!$ext['member_expiretime'] || $ext['member_expiretime'] > time());
return [
'id' => (int)$user['id'],
'nickname' => (string)$user['nickname'],
'avatar' => (string)$user['avatar'],
'phone' => $phone === null ? (string)$user['mobile'] : $phone,
'userType' => (int)$ext['user_type'],
'isMember' => $isMember,
'memberLevel' => $isMember ? (string)$ext['member_level'] : '',
'memberExpireAt' => $ext['member_expiretime'] ? $this->iso($ext['member_expiretime']) : null,
'balance' => (float)$user['money'],
'realnameStatus' => (int)$ext['realname_status'],
];
}
/** 解析 JSON 字段为数组 */
protected function jsonArr($val)
{
if (is_array($val)) {
return $val;
}
if (!$val) {
return [];
}
$decoded = json_decode($val, true);
return is_array($decoded) ? $decoded : [];
}
/** 记一条资金流水 */
protected function flow($type, $scene, $amount, $balance, $relatedId = 0, $remark = '')
{
static $seq = 0;
$seq++;
Db::name('fc_finance_flow')->insert([
'flow_no' => 'F' . date('YmdHis') . mt_rand(100, 999) . $seq,
'type' => $type,
'scene' => $scene,
'amount' => $amount,
'balance' => $balance,
'related_id' => $relatedId,
'remark' => $remark,
'createtime' => time(),
]);
}
/** 发一条站内消息 */
protected function notify($userId, $type, $title, $content)
{
Db::name('fc_message')->insert([
'user_id' => $userId, 'type' => $type, 'title' => $title,
'content' => $content, 'isread' => 0, 'readtime' => null, 'createtime' => time(),
]);
}
/** 管理端操作留痕 */
protected function adminLog($action, $remark = '')
{
try {
Db::name('admin_log')->insert([
'admin_id' => 1, 'username' => 'admin', 'url' => $this->request->url(),
'title' => $action, 'content' => $remark, 'ip' => $this->request->ip(),
'useragent' => (string)$this->request->header('user-agent'),
'createtime' => time(),
]);
} catch (\Exception $e) {
// 留痕失败不影响主流程
}
}
}