feat(v1.1.0): 支付改由 epay 插件承载、插件纳入版本库,补齐媒体上传/LBS/互动/优惠券/后台看板,并修复余额充值资损

## 一、支付:改由已安装的 epay 插件承载(不再自研签名)
- 下单:\addons\epay\library\Service::submitOrder($amount 元, $orderNo, 'wechat', $body, $notifyUrl, null, 'miniapp', $openid)
- 验签:Service::checkNotify('wechat')(内部 $pay->verify());应答:$pay->success()(v2 = XML)
- 业务编排仍在 application/api/controller/Pay.php,不改插件源码:
  POST /pay/prepay(取调起参数,下发前剔除 appId);POST /pay/notify(公开路由:插件验签 → 金额核对 → 幂等分派)
- 配置真源 = addons/epay/config.php(后台「插件管理 → 微信支付宝整合插件 → 配置」);
  fc_config 的 wx.mchId / wx.apiKey / wx.payNotifyUrl 废弃;后台「系统设置」支付表单改只读并跳插件配置页
- 插件 API 保持 version=v2(PHP 7.4 可跑);certs/* 为 0 字节占位,不含任何真实密钥
- 修复 BUG-015:Pay::notify() 与基类站内信同名且签名不兼容导致 /pay/* 全 500,动作改名 notifyCallback()

## 二、插件纳入 Git 版本管理
- .gitignore 移除 /addons/* 与 /public/assets/addons/*(保留 .gitkeep 占位)
- 入库 addons/epay、addons/wechat、public/assets/addons/*、addons/.htaccess(deny from all)
- config.php 入库为空白模板;服务器请在填好密钥后执行
  git update-index --skip-worktree addons/epay/config.php,避免真实密钥回传仓库

## 三、安全修复:余额充值资损(高危,已实测复现)
- 现象:POST /order/recharge {payType:'balance'} 只加余额不扣款(余额 134.50 → 1022.50),等于凭空增发余额,
  可再去买会员 / 付费发布 / 解锁联系方式
- 修复:/order/recharge 仅接受 payType=wxpay,balance → 「余额充值仅支持微信支付」,其它 → 「支付方式不支持」;
  订单恒为 status=pending、pay_type=wxpay、paytime=null;入账只发生在 /pay/notify 回调(Order::creditRecharge)
  或后台「会员管理 → 余额充值」(fc/userext/recharge)
- 小程序充值页同步为「仅微信支付」+ 防重复提交 + onShow 刷新资产;mock / 用例 / 文档同步

## 四、其他 v1.1.0 能力
- 媒体上传:POST /post/upload(图片 ≤10MB / 视频 ≤50MB,真落盘),发布页 uni.uploadFile 真上传
- LBS:fc_post.lat/lng、首页 sort=nearby(距离升序、无坐标排最后)、卡片 distance、详情页地图
- 互动:举报 POST /report(原因字典)、收藏 / 关注(fc_favorite / fc_follow、/favorite/*、/follow/toggle)
- 交易:余额充值 POST /order/recharge、优惠券 /coupon/list|receive(fc_coupon / fc_user_coupon、我的资产券)
- 发布计费:会员发布折扣(discountRate/discountText)+ 免费发布条数(freeQuota*)
- 后台新增:数据总览 fc/dashboard、系统设置 fc/setting、优惠券管理 fc/coupon(含菜单与权限节点)

## 五、本批审核修复
- 详情页:游客不再请求登录态接口(避免 401 被清 token 踢去登录);微信付费查看改为支付后轮询解锁,
  不再读取 wxpay 分支未返回的 contact;加防重复提交
- 发布页:freeLeftToday → freeQuotaLeft / freeQuotaCycle / freeUnlimited(对齐后端出参);
  上传图预览拼后端域名(新增 format.js#assetUrl,后端返回相对路径)
- 收藏空态「去首页」:switchTab → reLaunch(项目用自绘 fc-tabbar,无 tabBar,switchTab 必然失败)
- 会员券 days=0 显示「永久有效」;manifest.json 补 requiredPrivateInfos(getLocation / chooseLocation)
- 后端:publishConfig 补 discountRate/discountText 与 memberPostDiscountText();优惠券总开关 coupon.enabled
  真生效(关闭后 list/receive 拒绝);后台 fc/Coupon 的 add/edit 补 strip_tags 过滤(防存储型 XSS)、
  补 searchFields='name',列表 name 列再做一次 HTML 转义
- FcInstall:补清理后台菜单缓存 __menu__(否则新菜单要等缓存过期才显示),并同步 README 说明
- 后台语言包 fc/setting.php 按「支付只读 + 跳插件配置」的新页面重写
- 文档同步:uniapp/docs/{01,03,04}、uniapp/README.md、docs/05-后端实现规范.md、后台 README 上线步骤

## 六、校验结果(全部通过)
- 后端端到端:tools/verify-api.mjs 226/226(含新增「拒绝余额充值(资损防护)」用例)
- 小程序:uniapp/tests/run.mjs 167/167;validate.mjs 0 错 0 警;check-scss 19/19
- 后台:check-admin-i18n 0 错 0 警;check-theme 0 错 0 警;9 个页面 HTTP 200 全中文
- php -l 改动/新增 PHP 文件 0 语法错误;探针复测:余额不再增长、epay 插件下单/验签链路通
这个提交包含在:
2026-10-19 10:03:13 +08:00
父节点 592c5af931
当前提交 63fdfe87d7
共有 1086 个文件被更改,包括 68849 次插入 和 276 次删除

查看文件

@@ -44,6 +44,12 @@ class AdminSetting extends V1
/**
* AS2 微信支付配置
* POST /api/v1/admin/setting/pay 入参 {mchId,apiKey} → {configured:true}
*
* 【写入目标:epay 插件配置】支付能力已改由 epay 插件承载,商户号/密钥的真源是插件配置
* (后台「插件管理 → 微信支付宝整合插件 → 配置」,持久化在 addons/epay/config.php)。
* 因此本接口把 mchId/apiKey 合并写入插件的 wechat.mch_id / wechat.key,而不再写 fc_config 的 pay.*
* (历史键 pay.mchId/pay.apiKey 保留在库中仅为兼容,代码已不读取)。
* 小程序 AppID(wechat.miniapp_id)与回调地址不在此维护:前者请到插件配置页填写,后者由服务端按请求域名动态生成。
*/
public function pay()
{
@@ -57,10 +63,22 @@ class AdminSetting extends V1
$this->fail('支付密钥不能为空');
}
$this->setCfg('pay.mchId', $mchId);
$this->setCfg('pay.apiKey', $apiKey);
$this->adminLog('修改微信支付配置');
$addonConfig = (array)get_addon_config('epay');
$wechat = (isset($addonConfig['wechat']) && is_array($addonConfig['wechat'])) ? $addonConfig['wechat'] : [];
$wechat['mch_id'] = $mchId;
$wechat['key'] = $apiKey;
try {
// 与后台 Addon::config 同一套写入逻辑(VarExporter 导出回 addons/epay/config.php)
set_addon_config('epay', ['wechat' => $wechat]);
} catch (\Exception $e) {
$this->fail('支付配置写入插件失败:' . $e->getMessage());
}
$this->adminLog('修改微信支付配置(写入 epay 插件)');
// 返回体保持原契约({configured:true});是否已具备小程序支付条件(miniapp_id 是否填写)
// 请看后台「插件管理 → 微信支付宝整合插件 → 配置」或 /pay/prepay 的返回提示。
$this->ok(['configured' => true]);
}

查看文件

@@ -0,0 +1,144 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 优惠券(Module-COUPON)
* 路由:
* GET /api/v1/coupon/list 可领取优惠券分页列表(带 received 已领取标记)
* POST /api/v1/coupon/receive 领取优惠券
*
* 数据表:fa_fc_coupon(券模板)/ fa_fc_user_coupon(领取记录)。
* 说明:本轮仅做「领取 + 我的资产展示」,**不含下单抵扣**(下单抵扣在后续版本接入)。
*/
class Coupon extends V1
{
/**
* 优惠券功能总开关(后台「系统设置」写入 fc_config 的 coupon.enabled,默认开启)
* 关闭后用户端列表/领取一律拒绝,避免「后台关了前端还能领」。
*/
protected function assertEnabled()
{
if (!(int)$this->cfg('coupon.enabled', 1)) {
$this->fail('优惠券功能暂未开放');
}
}
/**
* GET /api/v1/coupon/list {page,size}
* → 分页 {list,page,size,total,hasMore}
* 列表项:{id,couponId,name,type,amount,minAmount,total,receivedCount,left,days,received,createdAt}
* 规则:仅 enabled=1(停用券不下发);received 表示「当前用户是否已领取」;
* left = 剩余可领数量(-1 表示不限量);total=0 表示不限量。
*/
public function list()
{
$this->assertEnabled();
$user = $this->auth();
list($rows, $total, $page, $size) = $this->pageQuery(function ($forCount) {
$q = Db::name('fc_coupon')->where('enabled', 1);
if ($forCount) {
return $q;
}
return $q->order('sort desc, id desc');
});
$list = [];
foreach ($rows as $row) {
$received = (bool)Db::name('fc_user_coupon')
->where('user_id', $user['id'])
->where('coupon_id', $row['id'])
->find();
$list[] = $this->couponItem($row, $received);
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* POST /api/v1/coupon/receive {couponId}
* → {userCouponId}
* 规则:券必须存在且 enabled=1;领完 → fail('优惠券已领完');
* 同一用户同一张券只能领一次 → fail('您已领取过该优惠券');
* days>0 时按「领取时间 + days 天」写过期时间,days=0 表示永久有效。
*/
public function receive()
{
$this->assertEnabled();
$user = $this->auth();
$couponId = (int)$this->input('couponId', 0);
$coupon = $couponId > 0 ? Db::name('fc_coupon')->where('id', $couponId)->find() : null;
if (!$coupon || (int)$coupon['enabled'] !== 1) {
$this->fail('优惠券不存在');
}
$total = (int)$coupon['total'];
$receivedCount = (int)$coupon['received'];
if ($total > 0 && $receivedCount >= $total) {
$this->fail('优惠券已领完');
}
$exist = Db::name('fc_user_coupon')
->where('user_id', $user['id'])
->where('coupon_id', $couponId)
->find();
if ($exist) {
$this->fail('您已领取过该优惠券');
}
$now = time();
$days = max(0, (int)$coupon['days']);
try {
$userCouponId = Db::name('fc_user_coupon')->insertGetId([
'user_id' => $user['id'],
'coupon_id' => $couponId,
'status' => 'unused',
'order_no' => '',
'usetime' => null,
'expiretime' => $days > 0 ? $now + $days * 86400 : null,
'createtime' => $now,
]);
} catch (\Exception $e) {
// 并发重复领取兜底
$this->fail('您已领取过该优惠券');
}
// 已领取数 +1(setInc 自增,避免并发覆盖)
Db::name('fc_coupon')->where('id', $couponId)->setInc('received', 1);
$this->ok(['userCouponId' => $userCouponId]);
}
/**
* 券模板 → 列表项
* @param array $row fc_coupon 行
* @param bool $received 当前用户是否已领取
* @return array
*/
protected function couponItem($row, $received)
{
$total = (int)$row['total'];
$receivedCount = (int)$row['received'];
return [
'id' => (int)$row['id'],
'couponId' => (int)$row['id'],
'name' => (string)$row['name'],
'type' => (string)$row['type'],
'amount' => (float)$row['amount'],
'minAmount' => (float)$row['min_amount'],
'total' => $total,
'receivedCount' => $receivedCount,
// -1 表示不限量(total=0)
'left' => $total > 0 ? max(0, $total - $receivedCount) : -1,
'days' => (int)$row['days'],
'received' => (bool)$received,
'createdAt' => $this->iso($row['createtime']),
];
}
}

查看文件

@@ -0,0 +1,204 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 收藏与关注(Module-FAVORITE)
* 路由:
* GET /api/v1/favorite/list 收藏的信息分页列表
* POST /api/v1/favorite/toggle 收藏/取消收藏信息
* POST /api/v1/follow/toggle 关注/取消关注用户
* POST /api/v1/favorite/status 批量查询收藏/关注状态
*
* 数据表:fa_fc_favorite(user_id,post_id,createtime) / fa_fc_follow(user_id,target_user_id,createtime)
* 两表均有唯一索引,所有写入「先查后写 + catch 兜底」,保证并发下**幂等**。
*/
class Favorite extends V1
{
/**
* GET /api/v1/favorite/list {page,size}
* → 分页 {list,page,size,total,hasMore}(list 项为 Post 结构,与信息流同构)
* 规则:仅本人收藏;只返回 audit_status=1 且 status=1 且未软删的信息;按收藏时间倒序。
*/
public function list()
{
$user = $this->auth();
// 闭包重建查询:TP5.0 的 count() 会清空 Query::options,不能复用同一对象
list($rows, $total, $page, $size) = $this->pageQuery(function ($forCount) use ($user) {
$q = Db::name('fc_favorite')->alias('f')
->join('fc_post p', 'p.id = f.post_id')
->where('f.user_id', $user['id'])
->where('p.audit_status', 1)
->where('p.status', 1)
->whereNull('p.deletetime');
if ($forCount) {
return $q;
}
return $q->field('p.*')->order('f.createtime desc, f.id desc');
});
$builder = new Post();
$list = [];
foreach ($rows as $row) {
// 复用 Post 的信息结构,保证「我的收藏」与首页信息流字段完全一致
$list[] = $builder->buildPost($row);
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* POST /api/v1/favorite/toggle {postId}
* → {faved,count}
* faved=true 表示本次操作后为「已收藏」;count 为该信息当前收藏总数。
*/
public function toggle()
{
$user = $this->auth();
$postId = (int)$this->input('postId', 0);
$post = $postId > 0 ? Db::name('fc_post')->where('id', $postId)->whereNull('deletetime')->find() : null;
if (!$post) {
$this->fail('信息不存在', 404);
}
$exist = Db::name('fc_favorite')->where('user_id', $user['id'])->where('post_id', $postId)->find();
$faved = false;
if ($exist) {
Db::name('fc_favorite')->where('id', $exist['id'])->delete();
} else {
try {
Db::name('fc_favorite')->insert([
'user_id' => $user['id'],
'post_id' => $postId,
'createtime' => time(),
]);
$faved = true;
} catch (\Exception $e) {
// 并发下唯一索引冲突:视为已收藏(幂等)
$faved = true;
}
}
$count = (int)Db::name('fc_favorite')->where('post_id', $postId)->count();
$this->ok(['faved' => $faved, 'count' => $count]);
}
/**
* POST /api/v1/follow/toggle {userId}
* → {followed}
* 规则:不能关注自己 → fail('不能关注自己');目标用户必须存在。
*/
public function follow()
{
$user = $this->auth();
$targetUserId = (int)$this->input('userId', 0);
if ($targetUserId <= 0) {
$this->fail('用户不存在', 404);
}
if ($targetUserId === (int)$user['id']) {
$this->fail('不能关注自己');
}
$target = Db::name('user')->where('id', $targetUserId)->find();
if (!$target) {
$this->fail('用户不存在', 404);
}
$exist = Db::name('fc_follow')
->where('user_id', $user['id'])
->where('target_user_id', $targetUserId)
->find();
$followed = false;
if ($exist) {
Db::name('fc_follow')->where('id', $exist['id'])->delete();
} else {
try {
Db::name('fc_follow')->insert([
'user_id' => $user['id'],
'target_user_id' => $targetUserId,
'createtime' => time(),
]);
$followed = true;
} catch (\Exception $e) {
// 并发下唯一索引冲突:视为已关注(幂等)
$followed = true;
}
}
$this->ok(['followed' => $followed]);
}
/**
* POST /api/v1/favorite/status {postIds:[],userIds:[]}
* → {faved:{postId:true|false},followed:{userId:true|false}}
* 说明:批量查询(参照「详情页进入时一次性拿状态」);
* 入参为空数组时返回**空对象** {}((object) 强转,避免 PHP 空数组被序列化成 []);
* 查询结果按请求的 id 全量回填(未收藏/未关注为 false)。
*/
public function status()
{
$user = $this->auth();
$faved = [];
foreach ($this->idArray('postIds') as $postId) {
$faved[(string)$postId] = false;
}
if ($faved) {
$rows = Db::name('fc_favorite')
->where('user_id', $user['id'])
->where('post_id', 'in', array_keys($faved))
->column('post_id');
foreach ($rows as $postId) {
$faved[(string)$postId] = true;
}
}
$followed = [];
foreach ($this->idArray('userIds') as $userId) {
$followed[(string)$userId] = false;
}
if ($followed) {
$rows = Db::name('fc_follow')
->where('user_id', $user['id'])
->where('target_user_id', 'in', array_keys($followed))
->column('target_user_id');
foreach ($rows as $userId) {
$followed[(string)$userId] = true;
}
}
$this->ok([
'faved' => (object)$faved,
'followed' => (object)$followed,
]);
}
/**
* 入参 ID 数组归一化(支持数组 / JSON 字符串 / 逗号串)
* @param string $key
* @return array 去重后的正整数 ID 列表(上限 200,避免超长 IN)
*/
protected function idArray($key)
{
$val = $this->input($key, []);
if (is_string($val)) {
$decoded = json_decode($val, true);
$val = is_array($decoded) ? $decoded : explode(',', $val);
}
if (!is_array($val)) {
return [];
}
$ids = [];
foreach ($val as $item) {
$item = (int)$item;
if ($item > 0) {
$ids[] = $item;
}
}
return array_slice(array_values(array_unique($ids)), 0, 200);
}
}

查看文件

@@ -10,7 +10,7 @@ use think\Db;
* 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 信息流
* GET /api/v1/home/feed H4 信息流(支持 lat/lng + sort=nearby 距离排序)
*/
class Home extends V1
{
@@ -83,9 +83,11 @@ class Home extends V1
/**
* H4 信息流
* GET /api/v1/home/feed {categoryId?,keyword?,area?,sort?,page,size}
* GET /api/v1/home/feed {categoryId?,keyword?,area?,sort?,lat?,lng?,page,size}
* → {list,page,size,total,hasMore}
* 规则:仅 audit_status=1 AND status=1 AND deletetime IS NULL
* - sort=nearby 时按距离升序(无坐标的信息排最后;请求未带 lat/lng 则回落发布时间倒序);
* - 列表项 distance 为 km(一位小数),请求未带坐标 / 信息未定位时为 null。
*/
public function feed()
{
@@ -109,14 +111,6 @@ class Home extends V1
if ($area !== '') {
$query->where('area', $area);
}
if ($sort === 'price') {
$query->order('is_top desc, price asc');
} elseif ($sort === 'hot') {
$query->order('is_top desc, views desc');
} else {
// 后台「置顶」优先展示,其余按发布时间倒序
$query->order('is_top desc, createtime desc');
}
$counter = Db::name('fc_post')
->where('audit_status', 1)
@@ -133,6 +127,45 @@ class Home extends V1
}
$total = $counter->count();
// 「附近」:距离在 PHP 内用 Haversine 计算后排序(不用 SQL 距离函数,避免 MySQL 兼容问题);
// 因排序依赖计算结果,这里取全量匹配行排序后再做**内存分页**,保证 page/size/total 一致。
if ($sort === 'nearby') {
$rows = $query->order('createtime desc')->select();
$items = [];
foreach ($rows as $row) {
$items[] = [
'item' => $this->buildPost($row),
'distance' => $this->postDistance($row),
'ct' => (int)$row['createtime'],
];
}
usort($items, function ($a, $b) {
$na = $a['distance'] === null;
$nb = $b['distance'] === null;
if ($na !== $nb) {
return $na ? 1 : -1; // 无坐标的排最后
}
if (!$na && $a['distance'] != $b['distance']) {
return $a['distance'] < $b['distance'] ? -1 : 1;
}
return $b['ct'] - $a['ct']; // 距离相同(或都无坐标):新的在前
});
$list = [];
foreach ($items as $it) {
$list[] = $it['item'];
}
$this->ok($this->paginateArray($list, $page, $size));
}
if ($sort === 'price') {
$query->order('is_top desc, price asc');
} elseif ($sort === 'hot') {
$query->order('is_top desc, views desc');
} else {
// 后台「置顶」优先展示,其余按发布时间倒序
$query->order('is_top desc, createtime desc');
}
$rows = $query->page($page, $size)->select();
$list = [];
@@ -143,6 +176,47 @@ class Home extends V1
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* Haversine 距离(km,一位小数)—— 与 Post 控制器同一算法
* @return float
*/
protected function haversine($lat1, $lng1, $lat2, $lng2)
{
$earth = 6371.0;
$rad = M_PI / 180;
$dLat = ($lat2 - $lat1) * $rad;
$dLng = ($lng2 - $lng1) * $rad;
$a = sin($dLat / 2) * sin($dLat / 2)
+ cos($lat1 * $rad) * cos($lat2 * $rad) * sin($dLng / 2) * sin($dLng / 2);
$c = 2 * asin(min(1.0, sqrt($a)));
return round($earth * $c, 1);
}
/**
* 列表项距离(km,一位小数;请求未带坐标 / 信息未定位 = null)
* @param array $row fc_post 行
* @return float|null
*/
protected function postDistance($row)
{
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if (!is_numeric($lat) || !is_numeric($lng)) {
return null;
}
$lat = (float)$lat;
$lng = (float)$lng;
if ($lat == 0.0 && $lng == 0.0) {
return null;
}
$plat = isset($row['lat']) && $row['lat'] !== null ? (float)$row['lat'] : 0.0;
$plng = isset($row['lng']) && $row['lng'] !== null ? (float)$row['lng'] : 0.0;
if ($plat == 0.0 && $plng == 0.0) {
return null;
}
return $this->haversine($lat, $lng, $plat, $plng);
}
/**
* 组装 Post 结构(与前端 mock 数据字段严格对齐)
* @param array $row fc_post 行
@@ -205,7 +279,7 @@ class Home extends V1
'tags' => $tags,
'publisher' => $publisher,
'commentCount' => (int)$row['comment_count'],
'distance' => (int)$row['distance'],
'distance' => $this->postDistance($row),
];
}

查看文件

@@ -76,8 +76,12 @@ class Member extends V1
/**
* M3 开通会员
* POST /api/v1/member/open {planId,payType} → {orderNo,status,expireAt}
* 规则 BR-07;套餐按 plan_code 查;余额支付扣 fa_user.money
* POST /api/v1/member/open {planId,payType}
* → {orderNo,status,order,expireAt,postQuota,quotaLeft,quotaExpireAt}
* - balance:余额支付,下单即扣款并**立即发放会员**(status=paid,order=null)
* - wxpay :订单 pending(order={orderNo,amount,payType,status:'pending'}),
* 前端拿 orderNo 调 POST /pay/prepay 调起收银台,支付成功后由 /pay/notify 发放会员
* 规则 BR-07;套餐按 plan_code 查;金额取 fc_plan.price(服务端计算,忽略客户端传值)
*/
public function open()
{
@@ -100,10 +104,11 @@ class Member extends V1
$amount = round((float)$plan['price'], 2);
$now = time();
$isBalance = $payType === 'balance';
// 余额校验必须在落订单之前:否则余额不足时已插入一条 status=paid 的假订单
$balance = (float)$user['money'];
if ($payType === 'balance' && $balance < $amount) {
if ($isBalance && $balance < $amount) {
$this->fail('余额不足');
}
@@ -115,30 +120,80 @@ class Member extends V1
'title' => (string)$plan['name'],
'amount' => $amount,
'pay_type' => $payType,
'status' => 'paid',
'paytime' => $now,
'related_id' => 0,
'status' => $isBalance ? 'paid' : 'pending',
'paytime' => $isBalance ? $now : null,
// related_id 存套餐主键:支付回调 /pay/notify 据此复用 grantMembership(),回调可独立完成
'related_id' => (int)$plan['id'],
'createtime' => $now,
'updatetime' => $now,
]);
if ($payType === 'balance') {
if ($isBalance) {
$balance = round($balance - $amount, 2);
Db::name('user')->where('id', $user['id'])->update([
'money' => $balance,
'updatetime' => $now,
]);
// 余额支付:立即发放会员(微信支付等待回调发放)
$grant = $this->grantMembership(Db::name('fc_order')->where('id', $orderId)->find());
} else {
$grant = null;
}
$ext = $this->ext($user['id']);
$quota = isset($plan['post_quota']) ? max(0, (int)$plan['post_quota']) : 0;
$this->ok([
'orderNo' => $orderNo,
'status' => $isBalance ? 'paid' : 'pending',
// 微信支付:前端拿到 orderNo 后调 /pay/prepay;余额支付无需再支付(order=null)
'order' => $isBalance ? null : [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => 'wxpay',
'status' => 'pending',
],
'expireAt' => $grant ? $this->iso($grant['expireAt']) : null,
'postQuota' => $quota,
'quotaLeft' => $grant ? $grant['quotaLeft'] : $this->quotaLeft($this->ext($user['id'])),
'quotaExpireAt' => $grant ? $this->iso($grant['expireAt']) : null,
]);
}
/**
* 会员发放(**可复用**:余额支付即时发放 / 微信支付回调 /pay/notify 发放)
* 说明:以 fc_order.related_id(套餐主键)反查 fc_plan 取天数与赠送发布条数;
* 老订单(related_id=0)按订单标题(套餐名)反查,仍失败则按默认 30 天、0 条额度发放;
* 发放同时记「会员开通」资金流水并发站内信。
* @param array $order fc_order 行(需含 user_id / related_id / amount / id / title)
* @return array{expireAt:int,postQuota:int,quotaLeft:int}
*/
public function grantMembership(array $order)
{
$userId = (int)$order['user_id'];
$now = time();
$plan = null;
$planId = (int)(isset($order['related_id']) ? $order['related_id'] : 0);
if ($planId > 0) {
$plan = Db::name('fc_plan')->where('id', $planId)->find();
}
if (!$plan) {
$title = isset($order['title']) ? (string)$order['title'] : '';
if ($title !== '') {
$plan = Db::name('fc_plan')->where('name', $title)->find();
}
}
$days = $plan ? max(0, (int)$plan['days']) : 30;
$quota = $plan && isset($plan['post_quota']) ? max(0, (int)$plan['post_quota']) : 0;
$level = $plan ? (string)$plan['name'] : '会员';
$ext = $this->ext($userId);
$base = (int)$ext['member_expiretime'];
if ($base < $now) {
$base = $now;
}
$expire = $base + (int)$plan['days'] * 86400;
$expire = $base + $days * 86400;
// 发布套餐额度:月/年卡赠送「含发布条数」,额度随会员有效期(过期后由发布接口自动清零)
$quota = isset($plan['post_quota']) ? max(0, (int)$plan['post_quota']) : 0;
$left = (int)(isset($ext['post_quota_left']) ? $ext['post_quota_left'] : 0);
$quotaExpire = (int)(isset($ext['post_quota_expire']) ? $ext['post_quota_expire'] : 0);
if ($quotaExpire > 0 && $quotaExpire < $now) {
@@ -146,25 +201,41 @@ class Member extends V1
}
$left += $quota;
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'is_member' => 1,
'member_level' => (string)$plan['name'],
Db::name('fc_user_ext')->where('user_id', $userId)->update([
'is_member' => 1,
'member_level' => $level,
'member_expiretime' => $expire,
'post_quota_left' => $left,
'post_quota_expire' => $expire,
'updatetime' => $now,
'updatetime' => $now,
]);
$amount = round((float)(isset($order['amount']) ? $order['amount'] : 0), 2);
$orderId = (int)(isset($order['id']) ? $order['id'] : 0);
$this->flow('income', '会员开通', $amount, 0, $orderId);
$this->notify(
$userId,
'system',
'会员开通成功',
'您已开通「' . $level . '」,有效期至 ' . date('Y-m-d', $expire) . ',赠送发布条数 ' . $quota . ' 条。'
);
$this->ok([
'orderNo' => $orderNo,
'status' => 'paid',
'expireAt' => $this->iso($expire),
'postQuota' => $quota,
'quotaLeft' => $left,
'quotaExpireAt' => $this->iso($expire),
]);
return ['expireAt' => $expire, 'postQuota' => $quota, 'quotaLeft' => $left];
}
/**
* 剩余发布条数(供未开通时回显)
* @param array $ext
* @return int
*/
protected function quotaLeft($ext)
{
$left = (int)(isset($ext['post_quota_left']) ? $ext['post_quota_left'] : 0);
$expire = (int)(isset($ext['post_quota_expire']) ? $ext['post_quota_expire'] : 0);
if ($left > 0 && $expire > 0 && $expire < time()) {
return 0;
}
return $left;
}
/**
@@ -204,16 +275,48 @@ class Member extends V1
/**
* M5 我的资产
* GET /api/v1/member/assets → {balance,coupons:[],points}
* GET /api/v1/member/assets
* → {balance,coupons:[{id,couponId,name,type,amount,minAmount,status,expireAt}],couponCount,points}
* 说明:coupons 来自 fc_user_coupon LEFT JOIN fc_coupon(真实数据);
* status:unused 未使用 / used 已使用 / expired 已过期(有效期为 0 表示永久;
* status=unused 但已过期时**动态判定**为 expired,无需定时任务)。
*/
public function assets()
{
$user = $this->auth();
$now = time();
$rows = Db::name('fc_user_coupon')->alias('uc')
->join('fc_coupon c', 'c.id = uc.coupon_id', 'LEFT')
->where('uc.user_id', $user['id'])
->field('uc.id,uc.coupon_id,uc.status,uc.expiretime,uc.createtime,c.name,c.type,c.amount,c.min_amount')
->order('uc.id desc')
->select();
$coupons = [];
foreach ($rows as $row) {
$status = (string)$row['status'];
$expire = !empty($row['expiretime']) ? (int)$row['expiretime'] : 0;
if ($status === 'unused' && $expire > 0 && $expire < $now) {
$status = 'expired';
}
$coupons[] = [
'id' => (int)$row['id'],
'couponId' => (int)$row['coupon_id'],
'name' => isset($row['name']) ? (string)$row['name'] : '',
'type' => isset($row['type']) ? (string)$row['type'] : '',
'amount' => isset($row['amount']) ? (float)$row['amount'] : 0,
'minAmount' => isset($row['min_amount']) ? (float)$row['min_amount'] : 0,
'status' => $status,
'expireAt' => $expire > 0 ? $this->iso($expire) : null,
];
}
$this->ok([
'balance' => (float)$user['money'],
'coupons' => [],
'points' => (int)$user['score'],
'balance' => (float)$user['money'],
'coupons' => $coupons,
'couponCount' => count($coupons),
'points' => (int)$user['score'],
]);
}
}

查看文件

@@ -0,0 +1,110 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 订单(Module-ORDER)
* 路由:
* POST /api/v1/order/recharge 余额充值下单
*
* 说明:充值金额一律由客户端传入后**服务端再次校验**(>0 且 ≤100000),并按 round(...,2) 归一;
* **交易只允许微信支付**:订单落 status=pending,前端调 POST /pay/prepay 调起收银台,
* 支付成功后由 /pay/notify 复用 creditRecharge() 入账(幂等由回调侧 status=paid 保证)。
*
* 【为什么不允许 payType=balance】「用余额充值余额」在本模型里没有任何收款方:余额只会 +amount、
* 不会扣减,等于给用户凭空增发余额(可用余额去买会员/付费发布/解锁联系方式,直接造成资损)。
* v1.1.0 初版曾把它当作「余额即时到账」的演示通道,**已移除**;给用户加余额只应来自
* ① 微信支付回调 creditRecharge(),② 后台「会员管理 → 余额充值」(`fc/userext/recharge`)。
*/
class Order extends V1
{
/**
* POST /api/v1/order/recharge {amount,payType}
* → {orderNo,amount,status:'pending',payType:'wxpay'}
* 规则:金额 >0 且 ≤100000 → 否则 fail('充值金额不合法');
* payType=balance → fail('余额充值仅支持微信支付')(资损防护,见类注释);
* payType 非 wxpay → fail('支付方式不支持')。
*/
public function recharge()
{
$user = $this->auth();
$amount = round((float)$this->input('amount', 0), 2);
if ($amount <= 0 || $amount > 100000) {
$this->fail('充值金额不合法');
}
$payType = (string)$this->input('payType', '');
// 余额「充值」= 用余额给余额加钱(无收款方、余额不扣减)→ 直接拒绝,防资损
if ($payType === 'balance') {
$this->fail('余额充值仅支持微信支付');
}
if ($payType !== 'wxpay') {
$this->fail('支付方式不支持');
}
$now = time();
$orderNo = $this->orderNo('RC');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'recharge',
'title' => '余额充值',
'amount' => $amount,
'pay_type' => 'wxpay',
'status' => 'pending',
'paytime' => null,
'related_id' => 0,
'createtime' => $now,
'updatetime' => $now,
]);
// 入账只在「微信支付回调 /pay/notify」里发生(Order::creditRecharge),本接口不触碰 fa_user.money
$this->ok([
'orderNo' => $orderNo,
'amount' => $amount,
'status' => 'pending',
'payType' => 'wxpay',
]);
}
/**
* 充值入账(**可复用**:微信支付回调 /pay/notify 入账时调用)
* 动作:fa_user.money 加款 + fc_finance_flow 资金流水 + fc_message 站内信。
* 幂等:调用方需保证「订单未入账」(回调侧以 fc_order.status=paid 做幂等判定)。
* 注意:**不要**在充值下单接口里调用它 —— 未真实收款就加余额属于凭空增发(资损)。
* @param array $order fc_order 行
* @return array{balance:float,amount:float}
*/
public function creditRecharge(array $order)
{
$userId = (int)$order['user_id'];
$amount = round((float)(isset($order['amount']) ? $order['amount'] : 0), 2);
$orderId = (int)(isset($order['id']) ? $order['id'] : 0);
$now = time();
$row = Db::name('user')->where('id', $userId)->find();
if (!$row) {
return ['balance' => 0, 'amount' => $amount];
}
$balance = round((float)$row['money'] + $amount, 2);
Db::name('user')->where('id', $userId)->update([
'money' => $balance,
'updatetime' => $now,
]);
$this->flow('income', '余额充值', $amount, $balance, $orderId, '余额充值');
$this->notify(
$userId,
'system',
'充值成功',
'您已成功充值 ' . number_format($amount, 2) . ' 元,当前余额 ' . number_format($balance, 2) . ' 元。'
);
return ['balance' => $balance, 'amount' => $amount];
}
}

查看文件

@@ -0,0 +1,353 @@
<?php
namespace app\api\controller;
use addons\epay\library\Service as EpayService;
use think\Db;
/**
* 用户端 · 微信支付(Module-PAY)
* 路由:
* POST /api/v1/pay/prepay 微信支付统一下单(需登录)
* POST /api/v1/pay/notify 微信支付结果回调(**公开路由、无需登录**;应答为纯 XML / JSON)
*
* 【支付能力由 epay 插件(addons/epay)承载,本控制器只做业务编排】
* 下单:\addons\epay\library\Service::submitOrder(..., 'miniapp', $openid)
* —— 插件内部按「API 版本 + 支付方式」拼装参数、签名、请求微信、并把结果包装成 Collection;
* 小程序(miniapp)走 JSAPI 分支,返回 appId/timeStamp/nonceStr/package/signType/paySign。
* 验签:\addons\epay\library\Service::checkNotify('wechat') → $pay->verify()
* —— 插件负责 XML 解析与签名校验(V2 = MD5 / XML,V3 = 证书 / JSON),失败返回 false;
* 应答体由 $pay->success() 生成,避免自行拼装报文与插件版本不一致。
*
* 【配置真源】插件配置:后台「插件管理 → 微信支付宝整合插件 → 配置」
* (持久化在 addons/epay/config.php,键 wechat.miniapp_id / wechat.mch_id / wechat.key / wechat.mode 等)。
* 本控制器**不**读取 fc_config 的支付键,避免出现「两份配置、改了一份不生效」。
*
* 【支付闭环】前端下单(/post/:id/pay-view、/member/open、/order/recharge)
* → /pay/prepay 拿 payParams → uni.requestPayment 调起收银台
* → 微信服务端回调 /pay/notify(验签 + 幂等 + 置 paid + 按订单类型触发后续动作)。
*
* 未配置插件商户参数时:/pay/prepay fail('微信支付未配置');/pay/notify 回 SUCCESS 但不处理
* (避免微信重试风暴;余额支付不受影响)。
*/
class Pay extends V1
{
/** 微信支付异步通知路由(注册在 application/route.php) */
const NOTIFY_PATH = '/api/v1/pay/notify';
/* ==================== 插件配置 ==================== */
/** 插件微信配置数组(插件未安装/未配置时返回空数组) */
protected function epayWechat()
{
$cfg = (array)get_addon_config('epay');
return (isset($cfg['wechat']) && is_array($cfg['wechat'])) ? $cfg['wechat'] : [];
}
/**
* 插件是否已具备「小程序支付」所需的最小配置
*
* 说明:小程序支付由 yansongda 的 MiniappGateway 负责,它固定使用配置里的 miniapp_id 作为 appid,
* 因此「公众号 appid」填了也**不生效**,必须填 miniapp_id;服务商模式(mode=service)另需子商户参数。
*/
protected function epayReady()
{
$wx = $this->epayWechat();
$mode = isset($wx['mode']) ? (string)$wx['mode'] : 'normal';
if ($mode === 'service') {
return !empty($wx['sub_mch_id']) && !empty($wx['key']) && !empty($wx['sub_miniapp_id']);
}
return !empty($wx['miniapp_id']) && !empty($wx['mch_id']) && !empty($wx['key']);
}
/** 本店铺的支付回调地址(供微信服务端回调,指向本控制器 notifyCallback) */
protected function notifyUrl()
{
$base = rtrim((string)$this->request->root(true), '/');
// FastAdmin 常见部署下 root(true) 会带入口文件(…/index.php、后台 …/s.php),微信回调地址要去掉更干净
$base = preg_replace('#/[a-zA-Z0-9_\-]+\.php$#i', '', $base);
return ($base !== '' ? $base : rtrim((string)$this->request->domain(), '/')) . self::NOTIFY_PATH;
}
/* ==================== 下单 ==================== */
/**
* POST /api/v1/pay/prepay {orderNo}
* → {orderNo,payType:'wxpay',payParams:{timeStamp,nonceStr,package,signType,paySign}}
* 校验:订单必须属于当前登录用户、status=pending、pay_type=wxpay,否则 fail;
* 取 fc_user_ext.openid 作为 JSAPI 支付者;
* 插件商户参数未配置 → fail('微信支付未配置')。
* 注意:金额只用**服务端订单金额**(round 到分)下发,绝不采信客户端传值。
*/
public function prepay()
{
$user = $this->auth();
$orderNo = trim((string)$this->input('orderNo', ''));
if ($orderNo === '') {
$this->fail('订单号不能为空');
}
$order = Db::name('fc_order')
->where('order_no', $orderNo)
->where('user_id', $user['id'])
->find();
if (!$order) {
$this->fail('订单不存在', 404);
}
if ((string)$order['status'] === 'paid') {
$this->fail('订单已支付,请勿重复支付');
}
if ((string)$order['status'] !== 'pending') {
$this->fail('订单状态不支持支付');
}
if ((string)$order['pay_type'] !== 'wxpay') {
$this->fail('该订单不是微信支付');
}
if (!$this->epayReady()) {
$this->fail('微信支付未配置');
}
$ext = $this->ext($user['id']);
$openid = isset($ext['openid']) ? trim((string)$ext['openid']) : '';
if ($openid === '') {
$this->fail('未获取到微信 openid,请重新登录后再试');
}
$amount = round((float)$order['amount'], 2);
if ($amount <= 0) {
$this->fail('订单金额不合法');
}
$title = trim((string)$order['title']);
$body = '同城分类信息-' . ($title !== '' ? mb_substr($title, 0, 40) : '在线支付');
try {
// 插件下单:金额单位**元**(插件内部 ×100 转为分),method=miniapp 走小程序 JSAPI
$result = EpayService::submitOrder(
$amount,
(string)$order['order_no'],
'wechat',
$body,
$this->notifyUrl(),
null,
'miniapp',
$openid
);
} catch (\Throwable $e) {
$this->fail('微信支付下单失败:' . $e->getMessage());
}
$params = $result instanceof \Yansongda\Supports\Collection ? $result->all() : (array)$result;
if (empty($params['package']) || empty($params['paySign'])) {
$this->fail('微信支付下单失败:未返回小程序调起参数');
}
// 前端契约只保留小程序 uni.requestPayment 需要的 5 个字段(插件额外带的 appId 会参与签名但无需下发)
unset($params['appId']);
$this->ok([
'orderNo' => (string)$order['order_no'],
'payType' => 'wxpay',
'payParams' => $params,
]);
}
/* ==================== 回调 ==================== */
/**
* POST /api/v1/pay/notify 微信支付结果回调(公开路由,无需登录)
* → 纯 XML 应答(V3 模式下为 JSON),成功 SUCCESS / 失败 FAIL
*
* 【方法名为什么叫 notifyCallback】V1 基类已有 protected notify($userId,$type,$title,$content)(站内信),
* 若本方法沿用 notify() 会与基类签名不兼容 —— PHP 抛兼容性告警、ThinkPHP 转成 500。
* 故动作方法命名为 notifyCallback(),路由映射见 application/route.php。
*
* 处理顺序:
* ① 插件验签(Service::checkNotify + $pay->verify(),签名错误直接 FAIL)
* → ② return_code/result_code 判定(未成功直接 SUCCESS,不处理)
* → ③ 按 out_trade_no 找订单 → ④ **幂等**(已 paid 直接 SUCCESS)
* → ⑤ 金额核对(回调金额必须等于订单金额,防篡改/串单)
* → ⑥ 事务内「置 paid + 按 type 分派后续动作」
* → ⑦ 用插件 $pay->success() 输出微信要求的成功应答
*
* 【为什么本方法允许直接 echo(全项目唯一例外)】
* 微信支付回调的应答体必须是**纯 XML**(V3 为 JSON),
* 而 V1 基类的 $this->ok()/$this->fail() 输出的是 JSON 契约({"code":0,...}),微信无法识别 → 判定回调失败并持续重试。
* 因此这里 echo 出插件生成的应答后立即 exit:既绕开 JSON 响应体,也避免 TP5 追加调试/HTML 内容污染报文。
* 其余所有动作**必须**继续使用 $this->ok()/$this->fail()。
*
* 后续动作按 fc_order.type 分派(下单时已把所需信息写进 related_id / title,回调可独立完成):
* member → 复用 Member::grantMembership() 发放会员
* recharge → 复用 Order::creditRecharge() 加余额 + 流水 + 站内信
* payview → 写 fc_pay_view 解锁记录(related_id = 信息 ID)
* post → 无需额外动作(信息已在待审,等后台审核)
*/
public function notifyCallback()
{
// 未配置支付参数:返回 SUCCESS 但不处理(避免微信重试风暴)
if (!$this->epayReady()) {
$this->replyXml('SUCCESS', 'OK');
}
try {
$pay = EpayService::checkNotify('wechat');
} catch (\Throwable $e) {
$pay = false;
}
if (!$pay) {
// 验签失败/报文非法:FAIL 让微信按策略重试(也可能是攻击流量,微信会自然退避)
$this->replyFail('签名验证失败');
}
try {
$data = EpayService::isVersionV3() ? $pay->callback() : $pay->verify();
// V3 回调为加密报文,需取 resource.ciphertext(插件 controller/Index.php 同款处理)
if (EpayService::isVersionV3() && isset($data['resource']['ciphertext'])) {
$data = $data['resource']['ciphertext'];
$data['total_fee'] = $data['amount']['total'];
}
} catch (\Throwable $e) {
$this->replyFail('回调报文解析失败');
}
$data = $data instanceof \Yansongda\Supports\Collection ? $data->all() : (array)$data;
// 支付未成功(用户取消/支付失败/订单关闭):不处理,仍回 SUCCESS 避免微信持续重试
if (!isset($data['return_code']) || (string)$data['return_code'] !== 'SUCCESS'
|| !isset($data['result_code']) || (string)$data['result_code'] !== 'SUCCESS') {
$this->replyXml('SUCCESS', 'OK');
}
$orderNo = isset($data['out_trade_no']) ? (string)$data['out_trade_no'] : '';
$order = $orderNo !== '' ? Db::name('fc_order')->where('order_no', $orderNo)->find() : null;
if (!$order) {
// 返回 FAIL:微信会重试,给订单落库/同步留出重放机会
$this->replyFail('订单不存在');
}
// 幂等:已支付直接回 SUCCESS(微信可能重复通知)
if ((string)$order['status'] === 'paid') {
$this->replyXml('SUCCESS', 'OK');
}
// 金额核对:回调金额(分)必须等于订单金额(元 ×100),不一致说明串单或伪造
$paidFee = isset($data['total_fee']) ? (int)$data['total_fee'] : 0;
$orderFee = (int)round((float)$order['amount'] * 100);
if ($paidFee !== $orderFee) {
\think\Log::record('微信支付回调金额不一致:订单 ' . $orderNo . ' 应付 ' . $orderFee . ' 分,实付 ' . $paidFee . ' 分', 'error');
$this->replyFail('订单金额不一致');
}
$now = time();
try {
// 事务内「置 paid + 后续动作」:任一步失败则整体回滚(订单保持 pending),
// 微信重试时可完整重放,避免「订单已 paid 但会员/余额没发」的不可恢复状态。
Db::transaction(function () use ($order, $now) {
Db::name('fc_order')->where('id', $order['id'])->update([
'status' => 'paid',
'paytime' => $now,
'updatetime' => $now,
]);
$order['status'] = 'paid';
$order['paytime'] = $now;
$type = (string)$order['type'];
if ($type === 'member') {
// 会员发放(与余额支付共用同一逻辑)
(new Member())->grantMembership($order);
} elseif ($type === 'recharge') {
// 余额入账 + 资金流水 + 站内信
(new Order())->creditRecharge($order);
} elseif ($type === 'payview') {
// 付费查看:写解锁记录(related_id 即信息 ID;user_id+post_id 唯一索引保证幂等)
$postId = (int)$order['related_id'];
if ($postId > 0) {
$exist = Db::name('fc_pay_view')
->where('user_id', $order['user_id'])
->where('post_id', $postId)
->find();
if (!$exist) {
Db::name('fc_pay_view')->insert([
'user_id' => $order['user_id'],
'post_id' => $postId,
'pay_type' => 'wxpay',
'amount' => round((float)$order['amount'], 2),
'order_id' => (int)$order['id'],
'createtime' => $now,
]);
}
}
}
// type=post:信息已在待审,无需额外动作
});
} catch (\Exception $e) {
// 事务已回滚(订单仍 pending)→ 返回 FAIL,微信重试后重放
$this->replyFail('订单处理失败:' . $e->getMessage());
}
\think\Log::record('微信支付回调成功:订单 ' . $orderNo . ',实付 ' . $paidFee . ' 分', 'info');
// 成功应答由插件生成(V2 为 XML / V3 为 JSON,Content-Type 与报文格式随版本变化)
$this->reply($pay->success());
}
/* ==================== 应答输出(纯报文,绕开 JSON 契约) ==================== */
/** 输出插件生成的应答对象(Symfony Response / PSR-7 Response / 字符串) */
protected function reply($response)
{
if ($response instanceof \Psr\Http\Message\ResponseInterface) {
$body = (string)$response->getBody();
$type = $response->getHeaderLine('Content-Type');
} elseif (is_object($response) && method_exists($response, 'getContent')) {
$body = (string)$response->getContent();
$type = 'application/xml; charset=utf-8';
} else {
$body = (string)$response;
$type = 'application/xml; charset=utf-8';
}
if (!headers_sent()) {
header('Content-Type: ' . ($type !== '' ? $type : 'application/xml; charset=utf-8'));
}
echo $body;
exit;
}
/** 输出 SUCCESS 应答(未配置 / 支付未成功 / 幂等命中) */
protected function replyXml($returnCode = 'SUCCESS', $returnMsg = 'OK')
{
$this->reply($this->xmlResponse($returnCode, $returnMsg));
}
/** 输出 FAIL 应答(验签失败 / 订单缺失 / 金额不一致 / 处理异常,微信会按策略重试) */
protected function replyFail($message)
{
if (EpayService::isVersionV3()) {
$this->reply(new \Symfony\Component\HttpFoundation\Response(
json_encode(['code' => 'FAIL', 'message' => (string)$message], JSON_UNESCAPED_UNICODE),
500,
['Content-Type' => 'application/json']
));
}
$this->reply($this->xmlResponse('FAIL', $message));
}
/** 构造 v2 回调应答 XML(CDATA 内不允许出现 ]]>) */
protected function xmlResponse($returnCode, $returnMsg)
{
$safe = str_replace(']]>', ']]&gt;', (string)$returnMsg);
return new \Symfony\Component\HttpFoundation\Response(
'<xml><return_code><![CDATA[' . $returnCode . ']]></return_code>'
. '<return_msg><![CDATA[' . $safe . ']]></return_msg></xml>',
200,
['Content-Type' => 'application/xml']
);
}
}

查看文件

@@ -7,6 +7,7 @@ use think\Db;
/**
* 用户端 · 信息发布与详情(Module-POST)
* 路由:
* POST /api/v1/post/upload P0 发布媒体上传(图片/视频)
* POST /api/v1/post/create P1 发布信息(服务端定价)
* GET /api/v1/post/mine P8 我的发布(含审核状态与计数)
* GET /api/v1/post/publish-config P9 发布配置(发布模式/价格/我的剩余额度)
@@ -28,12 +29,96 @@ use think\Db;
*/
class Post extends V1
{
/**
* P0 发布媒体上传
* POST /api/v1/post/upload multipart: file(+ 可选 type=image|video)
* → {url,type,size,name}
* 白名单:图片 jpg/jpeg/png/gif/webp(≤10MB)、视频 mp4/mov(≤50MB);
* 按「扩展名 + 真实 MIME(finfo)」双重校验(防改后缀绕过);
* 落盘 public/uploads/YYYYMMDD/<md5>.<ext>,返回相对 URL(形如 /uploads/20261017/xxx.jpg),
* 与 fa_user.avatar 存储口径一致(相对路径入库、前端自行拼域名)。
*/
public function uploadMedia()
{
$this->auth();
$file = $this->request->file('file');
if (!$file) {
$this->fail('未接收到上传文件');
}
$info = $file->getInfo();
$name = isset($info['name']) ? (string)$info['name'] : '';
$size = isset($info['size']) ? (int)$info['size'] : 0;
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
// 扩展名白名单:[媒体类型, 体积上限(字节), 允许的真实 MIME]
$allow = [
'jpg' => ['image', 10 * 1024 * 1024, ['image/jpeg']],
'jpeg' => ['image', 10 * 1024 * 1024, ['image/jpeg']],
'png' => ['image', 10 * 1024 * 1024, ['image/png']],
'gif' => ['image', 10 * 1024 * 1024, ['image/gif']],
'webp' => ['image', 10 * 1024 * 1024, ['image/webp']],
'mp4' => ['video', 50 * 1024 * 1024, ['video/mp4']],
'mov' => ['video', 50 * 1024 * 1024, ['video/quicktime']],
];
if (!isset($allow[$ext])) {
$this->fail('文件类型不支持');
}
list($type, $maxSize, $mimes) = $allow[$ext];
// 客户端可选声明 type:与扩展名推导出的类型不一致时按非法类型拒绝
$wantType = strtolower(trim((string)$this->input('type', '')));
if ($wantType !== '' && $wantType !== $type) {
$this->fail('文件类型不支持');
}
if ($size <= 0) {
$this->fail('文件大小超出限制');
}
if ($size > $maxSize) {
$this->fail('文件大小超出限制');
}
// 真实 MIME 双重校验(读临时文件头,图片/视频都必须命中白名单);
// 服务器未启用 finfo 时跳过(退化为扩展名 + makeUpload 的 checkImg 兜底)
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = $finfo ? (string)finfo_file($finfo, $file->getPathname()) : '';
if ($finfo) {
finfo_close($finfo);
}
if ($mime === '' || !in_array($mime, $mimes, true)) {
$this->fail('文件类型不支持');
}
}
$dirName = date('Ymd');
$saveName = $file->hash('md5') . '.' . $ext; // md5 命名:同内容文件天然去重
$destDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . $dirName . DS;
$moved = $file->move($destDir, $saveName, true);
if (!$moved) {
$this->fail('文件上传失败,请稍后重试');
}
$this->ok([
'url' => '/uploads/' . $dirName . '/' . $saveName,
'type' => $type,
'size' => $size,
'name' => $name,
]);
}
/**
* P1 发布信息
* POST /api/v1/post/create
* 入参 {categoryId,title,content,media[],contact,phone,address,plan,payType}
* → {postId,auditStatus,order,plan,amount,quotaLeft,freeQuotaLeft}
* 入参 {categoryId,title,content,media[],contact,phone,address,lat?,lng?,plan,payType}
* → {postId,auditStatus,order,plan,amount,discountRate,quotaLeft,freeQuotaLeft}
* 规则 BR-03/BR-04/BR-02/BR-13(计费顺序:套餐额度 → 免费发布条数 → 单条付费)
* 说明:
* - `media` 接收**上传后的 URL 数组**(先调 POST /post/upload 拿 url,再随发布提交);
* - `lat`/`lng` 可选(gcj02),由前端 chooseLocation 采集,用于首页「附近」排序;
* - 单条付费金额 = round(单条价格 × 会员折扣率, 2),折扣率取自 member.benefit.postDiscount
* (会员权益,非会员/解析失败视作 1);金额一律服务端计算,忽略客户端传值。
*/
public function create()
{
@@ -83,13 +168,18 @@ class Post extends V1
$quotaLeft = $this->quotaLeft($ext);
$free = $this->freeQuotaState($user['id']);
// 会员发布折扣:member.benefit.postDiscount(如 '8 折'→0.8、'9.5折'→0.95);
// 折扣属**会员权益**,非会员 / 解析失败 / 不含折扣时视作 1(原价)。
$discountRate = $this->memberPostDiscount($ext);
$unitPrice = round($rule['singlePrice'] * $discountRate, 2);
$amount = 0;
$payType = '';
$useQuota = false; // 套餐额度内免费
$useFreeQuota = false; // 免费发布条数内免费
if ($plan === 'single') {
// 单条付费 = 付费发布标准(免费发布条数用完后即按此计费)
$amount = $rule['singlePrice'];
// 单条付费 = 付费发布标准(免费发布条数用完后即按此计费);会员按折扣率计价
$amount = $unitPrice;
$payType = trim((string)$this->input('payType', ''));
if ($amount > 0 && !in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
@@ -106,7 +196,7 @@ class Post extends V1
// 免费发布模式下免费条数已用完 → 按「付费发布」标准计费:
// 需要客户端切到「会员单条」(plan=single)并选支付方式后重新提交,
// 服务端不主动扣款(避免未经用户确认就产生订单)
$this->fail('免费额度已用完,请按 ' . number_format((float)$rule['singlePrice'], 2) . ' 元/条付费发布');
$this->fail('免费额度已用完,请按 ' . number_format((float)$unitPrice, 2) . ' 元/条付费发布');
} else {
$this->fail('请选择发布方式');
}
@@ -128,6 +218,9 @@ class Post extends V1
'phone' => $phone,
'wechat' => '',
'tags' => $this->tagsString(),
// LBS 坐标(gcj02;未定位/为 0 时存 NULL,首页「附近」不参与距离排序)
'lat' => $this->coord('lat', 90),
'lng' => $this->coord('lng', 180),
'is_paid' => $paid ? 1 : 0,
'amount' => $paid ? $amount : 0,
'pay_type' => $paid ? $payType : '',
@@ -192,6 +285,8 @@ class Post extends V1
'order' => $order,
'plan' => $useQuota ? 'quota' : ($useFreeQuota ? 'free' : ($paid ? 'single' : 'free')),
'amount' => $amount,
// 本次生效的会员发布折扣率(非会员/未配置为 1)
'discountRate' => $discountRate,
'quotaLeft' => $quotaLeft,
// -1 = 不限制(免费发布模式且未设置免费条数)
'freeQuotaLeft' => $free['unlimited'] ? -1 : max(0, $free['left'] - ($useFreeQuota ? 1 : 0)),
@@ -291,9 +386,15 @@ class Post extends V1
// 免费发布条数(post.freeQuota / post.freeQuotaCycle):超出即按付费发布标准计费
$free = $this->freeQuotaState($user['id']);
// 会员发布折扣:与发布接口 create() 同一口径(非会员 / 解析失败一律 1 = 原价)
$discountRate = $this->memberPostDiscount($ext);
$this->ok([
'mode' => $rule['mode'],
'singlePrice' => $rule['singlePrice'],
// 会员折扣:前端按 singlePrice × discountRate 展示折后价,discountText 用于文案(如「8 折」)
'discountRate' => $discountRate,
'discountText' => $this->memberPostDiscountText($discountRate),
'monthPrice' => $rule['monthPrice'],
'monthQuota' => $rule['monthQuota'],
'yearPrice' => $rule['yearPrice'],
@@ -531,6 +632,8 @@ class Post extends V1
/**
* P5 信息详情
* GET /api/v1/post/:id → Post 结构(contact 为脱敏串,绝不返回完整手机号)
* 出参新增:lat / lng(gcj02,未定位为 null)、faved(我是否已收藏)、
* followed(我是否已关注发布者)、favoriteCount(该信息收藏数)
* 规则:允许游客;不存在 fail('信息不存在',404);每次浏览 views+1
*/
public function detail()
@@ -557,8 +660,11 @@ class Post extends V1
/**
* P6 付费查看联系方式
* POST /api/v1/post/:id/pay-view {payType}
* → {unlocked:true,contact:{phone,wechat}}
* → {unlocked:true,contact:{phone,wechat}}(余额/会员免费:立即解锁)
* → {order:{orderNo,amount,payType,status:'pending'}}(微信支付:前端再调 POST /pay/prepay 调起收银台)
* 规则 BR-05;金额取 fee.payView;会员或已解锁免费
* 说明:微信支付改为**真实闭环** —— 下单只落 pending 订单(type=payview、related_id=信息ID),
* 解锁记录 fc_pay_view 由支付回调 /pay/notify 独立写入(回调无需前端参与)。
*/
public function payView()
{
@@ -613,20 +719,31 @@ class Post extends V1
]);
$this->flow('expense', '付费查看', $amount, $balance, $id);
} else {
// 微信支付:创建已支付订单
$orderId = Db::name('fc_order')->insertGetId([
'order_no' => $this->orderNo('VO'),
// 微信支付:只落 pending 订单(不预写解锁记录),
// 支付成功后由 /pay/notify 按 type=payview + related_id 解锁(回调可独立完成)
$orderNo = $this->orderNo('VO');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'post',
'type' => 'payview',
'title' => '付费查看 #' . $id,
'amount' => $amount,
'pay_type' => $payType,
'status' => 'paid',
'paytime' => $now,
'pay_type' => 'wxpay',
'status' => 'pending',
'paytime' => null,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
$this->ok([
'order' => [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => 'wxpay',
'status' => 'pending',
],
]);
}
Db::name('fc_pay_view')->insert([
@@ -706,7 +823,9 @@ class Post extends V1
}
/**
* media 入参归一化为数组
* media 入参归一化为字符串数组
* 约定:接收 **上传后的 URL 数组**(POST /post/upload 返回的 url),
* 兼容 JSON 字符串(老客户端 media='["/uploads/.."]')与逗号分隔串。
* @return array
*/
protected function mediaArray()
@@ -714,9 +833,127 @@ class Post extends V1
$media = $this->input('media', []);
if (is_string($media)) {
$decoded = json_decode($media, true);
$media = is_array($decoded) ? $decoded : [];
$media = is_array($decoded) ? $decoded : explode(',', $media);
}
return is_array($media) ? array_values($media) : [];
if (!is_array($media)) {
return [];
}
$list = [];
foreach ($media as $item) {
$item = trim((string)$item);
if ($item !== '') {
$list[] = $item;
}
}
return array_values(array_unique($list));
}
/**
* 发布纬度/经度入参(可选 float,gcj02)
* 未传 / 非数字 / 越界 / 为 0(视为未定位)时返回 null,落库为 NULL。
* @param string $key lat|lng
* @param float $limit 绝对值上限(纬度 90 / 经度 180)
* @return float|null
*/
protected function coord($key, $limit)
{
$val = $this->input($key, null);
if ($val === null || $val === '' || !is_numeric($val)) {
return null;
}
$val = round((float)$val, 6);
if ($val == 0.0 || $val < -$limit || $val > $limit) {
return null;
}
return $val;
}
/**
* 会员发布折扣率
* 取自 member.benefit.postDiscount(如 '8 折'→0.8、'9.5折'→0.95、'八折' 视为解析失败→1);
* 折扣属会员权益:非会员、解析失败、不含折扣时一律返回 1(原价)。
* @param array $ext fc_user_ext 行
* @return float
*/
protected function memberPostDiscount($ext)
{
$now = time();
$isMember = (int)$ext['is_member'] === 1
&& (empty($ext['member_expiretime']) || (int)$ext['member_expiretime'] > $now);
if (!$isMember) {
return 1.0;
}
$cfg = $this->cfg('member.benefit', null);
$text = is_array($cfg) && isset($cfg['postDiscount']) ? (string)$cfg['postDiscount'] : '8 折';
if (!preg_match('/(\d+(?:\.\d+)?)/', $text, $m)) {
return 1.0;
}
$rate = (float)$m[1] / 10; // 「8 折」= 0.8;「9.5 折」= 0.95
if ($rate <= 0 || $rate > 1) {
return 1.0;
}
return round($rate, 2);
}
/**
* 会员发布折扣文案(与 memberPostDiscount 同源;无折扣返回空串)
* @param float $rate memberPostDiscount() 的返回值
* @return string
*/
protected function memberPostDiscountText($rate)
{
if ($rate >= 1) {
return '';
}
$cfg = $this->cfg('member.benefit', null);
return is_array($cfg) && isset($cfg['postDiscount']) ? (string)$cfg['postDiscount'] : '8 折';
}
/**
* Haversine 距离(km,保留一位小数)
* 自实现而不用 SQL 复杂函数,避免不同 MySQL 版本/字符集下的兼容问题。
* @param float $lat1
* @param float $lng1
* @param float $lat2
* @param float $lng2
* @return float
*/
protected function haversine($lat1, $lng1, $lat2, $lng2)
{
$earth = 6371.0; // 地球平均半径(km)
$rad = M_PI / 180;
$dLat = ($lat2 - $lat1) * $rad;
$dLng = ($lng2 - $lng1) * $rad;
$a = sin($dLat / 2) * sin($dLat / 2)
+ cos($lat1 * $rad) * cos($lat2 * $rad) * sin($dLng / 2) * sin($dLng / 2);
$c = 2 * asin(min(1.0, sqrt($a)));
return round($earth * $c, 1);
}
/**
* 列表项距离(km,一位小数)
* 请求未带 lat/lng 或信息未定位时返回 null(前端显示「未知距离」)。
* @param array $row fc_post 行
* @return float|null
*/
protected function postDistance($row)
{
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if (!is_numeric($lat) || !is_numeric($lng)) {
return null;
}
$lat = (float)$lat;
$lng = (float)$lng;
if ($lat == 0.0 && $lng == 0.0) {
return null;
}
$plat = isset($row['lat']) && $row['lat'] !== null ? (float)$row['lat'] : 0.0;
$plng = isset($row['lng']) && $row['lng'] !== null ? (float)$row['lng'] : 0.0;
if ($plat == 0.0 && $plng == 0.0) {
return null;
}
return $this->haversine($lat, $lng, $plat, $plng);
}
/**
@@ -734,10 +971,12 @@ class Post extends V1
/**
* 组装 Post 结构(与前端 mock 数据字段严格对齐)
* @param array $row fc_post 行
* public:供 Favorite 等其它用户端控制器复用(保证「我的收藏」列表项与信息流同构)。
* @param array $row fc_post 行
* @param bool $withInteract 是否附带「我是否收藏/关注」等登录态字段
* @return array
*/
protected function buildPost($row)
public function buildPost($row, $withInteract = true)
{
$categoryName = '';
if (!empty($row['category_id'])) {
@@ -773,27 +1012,65 @@ class Post extends V1
}
}
// LBS:坐标与距离(未定位 = null)
$lat = isset($row['lat']) && $row['lat'] !== null && $row['lat'] !== '' ? round((float)$row['lat'], 6) : null;
$lng = isset($row['lng']) && $row['lng'] !== null && $row['lng'] !== '' ? round((float)$row['lng'], 6) : null;
if ($lat === 0.0) {
$lat = null;
}
if ($lng === 0.0) {
$lng = null;
}
// 收藏数(公开)+ 我的收藏/关注状态(需登录)
$postId = (int)$row['id'];
$favoriteCount = (int)Db::name('fc_favorite')->where('post_id', $postId)->count();
$faved = false;
$followed = false;
if ($withInteract) {
$me = $this->user();
if ($me) {
$faved = (bool)Db::name('fc_favorite')
->where('user_id', $me['id'])
->where('post_id', $postId)
->find();
$pubId = (int)$row['user_id'];
if ($pubId > 0 && $pubId !== (int)$me['id']) {
$followed = (bool)Db::name('fc_follow')
->where('user_id', $me['id'])
->where('target_user_id', $pubId)
->find();
}
}
}
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' => $postId,
'categoryId' => (int)$row['category_id'],
'categoryName' => $categoryName,
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'cover' => (string)$row['cover'],
'media' => $this->jsonArr(isset($row['media']) ? $row['media'] : ''),
'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'],
'lat' => $lat,
'lng' => $lng,
'distance' => $this->postDistance($row),
'faved' => $faved,
'followed' => $followed,
'favoriteCount' => $favoriteCount,
];
}
}

查看文件

@@ -0,0 +1,75 @@
<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 举报(Module-REPORT)
* 路由:
* POST /api/v1/report 举报信息/评价
*
* 说明:举报原因字典由后台配置 fc_config 的 report.reasons(JSON 数组)维护,
* 小程序端从站点配置读取;本接口只做「必填 + 类型合法 + 对象存在」校验,
* 允许举报原因使用字典外的自定义文案(前端传字典项,`detail` 传补充说明)。
*/
class Report extends V1
{
/**
* POST /api/v1/report {targetType:'post'|'comment',targetId,reason,detail?}
* → {reportId}
* 规则:targetType 仅 post/comment(否则 fail('举报类型不支持'));
* reason 必填(否则 fail('请选择举报原因'));被举报对象必须存在;
* detail 作为补充说明写入 fc_report.remark,状态默认 pending(待后台处理)。
*/
public function create()
{
$user = $this->auth();
$targetType = strtolower(trim((string)$this->input('targetType', '')));
if (!in_array($targetType, ['post', 'comment'], true)) {
$this->fail('举报类型不支持');
}
$reason = trim((string)$this->input('reason', ''));
if ($reason === '') {
$this->fail('请选择举报原因');
}
if (mb_strlen($reason) > 60) {
$reason = mb_substr($reason, 0, 60);
}
$targetId = (int)$this->input('targetId', 0);
if ($targetId <= 0) {
$this->fail('举报对象不存在');
}
if ($targetType === 'post') {
$target = Db::name('fc_post')->where('id', $targetId)->whereNull('deletetime')->find();
if (!$target) {
$this->fail('信息不存在', 404);
}
} else {
$target = Db::name('fc_comment')->where('id', $targetId)->find();
if (!$target) {
$this->fail('评价不存在', 404);
}
}
$detail = trim((string)$this->input('detail', ''));
$now = time();
$reportId = Db::name('fc_report')->insertGetId([
'target_type' => $targetType,
'target_id' => $targetId,
'reason' => $reason,
'reporter_id' => (int)$user['id'],
'status' => 'pending',
'remark' => mb_substr($detail, 0, 200),
'createtime' => $now,
'updatetime' => $now,
]);
$this->ok(['reportId' => $reportId]);
}
}