feat: 新增地址选择插件及订阅消息等多项功能优化

- 新增地址选择插件,支持地图位置选择并返回地址和经纬度
- 新增微信订阅消息发送功能,支持审核结果、提现通知等场景
- 新增订单支付状态查询、提现收款人姓名保存等接口
- 新增服务区域管理,支持按省市区划分并同步到信息发布
- 新增资金流水和营收报表导出功能
- 新增可用优惠券查询、订单退款拆分处理等功能
- 优化后台角标显示、首页数据统计、UI配置下发等
- 修复订单支付并发问题、地区管理逻辑等
这个提交包含在:
2026-10-22 17:14:56 +08:00
父节点 088a08d43a
当前提交 cb12bf5fc8
共有 180 个文件被更改,包括 9695 次插入 和 1680 次删除

查看文件

@@ -13,6 +13,13 @@ use think\Db;
*/
class AdminComment extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AC1 评价列表
* GET /api/v1/admin/comments 入参 {page,size}

查看文件

@@ -12,6 +12,13 @@ use think\Db;
*/
class AdminDashboard extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AD1 核心指标
* GET /api/v1/admin/dashboard/overview

查看文件

@@ -14,6 +14,13 @@ use think\Db;
*/
class AdminDist extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AD1 分销设置读取
* GET /api/v1/admin/dist/setting → {enabled,level,level1Rate,level2Rate,settleCycle,minWithdraw}
@@ -68,16 +75,38 @@ class AdminDist extends V1
->order('w.createtime desc')
->select();
// 兜底同步:转账中的单据主动查一次微信(回调丢失/本地无 HTTPS 回调时)
$synced = 0;
foreach ($rows as $row) {
if ((string)$row['status'] === 'paying' && $synced < 5) {
$synced++;
try {
\app\common\library\WxTransfer::sync((int)$row['id']);
} catch (\Throwable $e) {
// 同步失败不影响列表展示
}
}
}
if ($synced > 0) {
$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']),
'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'],
'transferStatus' => (string)(isset($row['transfer_status']) ? $row['transfer_status'] : ''),
'failReason' => (string)(isset($row['fail_reason']) ? $row['fail_reason'] : ''),
'createdAt' => $this->iso($row['createtime']),
];
}
@@ -103,27 +132,72 @@ class AdminDist extends V1
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', '提现已打款', '您的提现申请已打款,请注意查收。');
if ((string)$withdraw['status'] !== 'auditing') {
$this->fail('该提现记录已处理(当前状态:' . $withdraw['status'] . '),请勿重复操作');
}
$this->adminLog('处理提现 #' . $id . ' 结果' . $status);
if ($op === 'reject') {
try {
Db::transaction(function () use ($id, $reason) {
$locked = Db::name('fc_withdraw')->where('id', $id)->lock(true)->find();
if (!$locked || (string)$locked['status'] !== 'auditing') {
throw new \RuntimeException('该提现记录已处理,请刷新后重试');
}
Db::name('fc_withdraw')->where('id', $id)->update([
'status' => 'rejected',
'reason' => $reason,
'updatetime' => time(),
]);
$this->notify($locked['user_id'], 'system', '提现被驳回', '您的提现申请被驳回:' . $reason);
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '操作失败,请重试');
}
$this->ok(['id' => (int)$id, 'status' => $status]);
$this->adminLog('驳回提现 #' . $id);
$this->ok(['id' => (int)$id, 'status' => 'rejected']);
}
// 审核通过 → 自动发起微信商家转账(用户需在微信确认收款)
try {
$res = \app\common\library\WxTransfer::approve($id);
} catch (\Throwable $e) {
$this->fail('转账失败:' . $e->getMessage());
}
$this->adminLog('提现转账 #' . $id . ' 结果' . $res['state']);
$message = $res['withdrawState'] === 'paid'
? '转账成功,已到账'
: ($res['withdrawState'] === 'failed' ? '转账失败,请查看失败原因' : '已提交转账,等待用户确认收款');
$this->ok([
'id' => (int)$id,
'status' => $res['withdrawState'],
'transferState' => $res['state'],
], $message);
}
/**
* 撤销「转账中」的提现单(用户长期不确认收款时使用)
* POST /api/v1/admin/dist/withdraw/:id/cancel
*/
public function cancelWithdraw()
{
$id = (int)$this->request->param('id', 0);
try {
$state = \app\common\library\WxTransfer::cancel($id);
} catch (\Throwable $e) {
$this->fail('撤销失败:' . $e->getMessage());
}
$this->adminLog('撤销提现转账 #' . $id);
$this->ok([
'id' => $id,
'status' => (string)Db::name('fc_withdraw')->where('id', $id)->value('status'),
'transferState' => $state,
]);
}
/** 组装分销设置结构 */

查看文件

@@ -12,6 +12,13 @@ use think\Db;
*/
class AdminFinance extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AF1 资金流水
* GET /api/v1/admin/finance/flows 入参 {type?,page,size}

查看文件

@@ -12,6 +12,13 @@ use think\Db;
*/
class AdminMember extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AMB1 用户列表
* GET /api/v1/admin/users 入参 {page,size}

查看文件

@@ -12,6 +12,13 @@ use think\Db;
*/
class AdminMerchant extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AM1 商家列表
* GET /api/v1/admin/merchants 入参 {status?,keyword?,page,size}

查看文件

@@ -13,6 +13,13 @@ use think\Db;
*/
class AdminOrder extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AO1 订单列表
* GET /api/v1/admin/orders 入参 {type?,page,size}
@@ -63,28 +70,24 @@ class AdminOrder extends V1
public function refund()
{
$id = (int)$this->request->param('id', 0);
$amount = round((float)$this->input('amount', 0), 2);
$amount = $this->input('amount', null);
$reason = trim((string)$this->input('reason', ''));
$amount = ($amount === null || $amount === '') ? null : (float)$amount;
if ($amount <= 0) {
$this->fail('退款金额需大于 0');
try {
$res = \app\common\library\OrderRefund::refund($id, $amount, $reason);
} catch (\Throwable $e) {
$this->fail($e->getMessage());
}
$order = Db::name('fc_order')->where('id', $id)->find();
if (!$order) {
$this->fail('订单不存在', 404);
}
$this->adminLog('订单退款 #' . $id . ' 金额' . $res['amount'] . ' 退款单号' . $res['refundNo']);
Db::name('fc_order')->where('id', $id)->update([
'status' => 'refunded',
'refund_amount' => $amount,
'refund_reason' => $reason,
$this->ok([
'id' => $id,
'refunded' => true,
'refundNo' => $res['refundNo'],
'amount' => $res['amount'],
]);
$this->notify($order['user_id'], 'system', '订单已退款', '您的订单「' . $order['title'] . '」已退款 ' . $amount . ' 元。');
$this->adminLog('订单退款 #' . $id . ' 金额' . $amount);
$this->ok(['id' => (int)$id, 'refunded' => true]);
}
/**
@@ -104,15 +107,44 @@ class AdminOrder extends V1
$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);
if ((string)$order['status'] === 'paid') {
$this->ok(['orderNo' => (string)$orderNo, 'supplemented' => false], '订单已支付,无需补单');
}
if ((string)$order['status'] !== 'pending') {
$this->fail('订单状态不支持补单(当前:' . $order['status'] . ')');
}
$this->ok(['orderNo' => (string)$orderNo, 'supplemented' => true]);
$now = time();
$handled = false;
try {
Db::transaction(function () use ($order, $now, &$handled) {
$locked = Db::name('fc_order')->where('id', (int)$order['id'])->lock(true)->find();
if (!$locked || (string)$locked['status'] !== 'pending') {
return;
}
$affected = Db::name('fc_order')
->where('id', (int)$order['id'])
->where('status', 'pending')
->update(['status' => 'paid', 'paytime' => $now, 'updatetime' => $now]);
if (!$affected) {
return;
}
$locked['status'] = 'paid';
$locked['paytime'] = $now;
$handled = true;
// 补单必须真正发货:会员发放 / 余额入账 / 付费查看解锁,不能只改状态
\app\common\library\OrderFulfill::handle($locked);
});
} catch (\Throwable $e) {
\think\Log::record('补单失败:订单 ' . $orderNo . ',' . $e->getMessage(), 'error');
$this->fail('补单失败:' . $e->getMessage());
}
$this->adminLog('订单补单 #' . $orderNo . ($handled ? '' : '(幂等命中)'));
$this->ok(['orderNo' => (string)$orderNo, 'supplemented' => $handled]);
}
}

查看文件

@@ -13,6 +13,13 @@ use think\Db;
*/
class AdminPost extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AP1 待审核信息列表
* GET /api/v1/admin/posts/pending 入参 {page,size}
@@ -91,6 +98,18 @@ class AdminPost extends V1
$this->adminLog('审核信息 #' . $id . ' 结果' . $auditStatus);
// 订阅消息:审核结果(模板未配置/用户未授权时静默跳过)
\app\common\library\WxSubscribe::send(
(int)$post['user_id'],
'audit',
[
'thing1' => ['value' => mb_substr((string)$post['title'], 0, 20)],
'phrase2' => ['value' => $auditStatus === 1 ? '审核通过' : '审核未通过'],
'thing3' => ['value' => $auditStatus === 1 ? '信息已公开展示' : mb_substr((string)$reason, 0, 20)],
],
'pages/detail/detail?id=' . $id
);
$this->ok(['id' => (int)$id, 'auditStatus' => (int)$auditStatus]);
}

查看文件

@@ -17,6 +17,13 @@ use think\Db;
*/
class AdminRbac extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AR1 角色列表
* GET /api/v1/admin/roles → 数组 [{id,name,permissions,remark}]

查看文件

@@ -18,6 +18,13 @@ use think\Db;
*/
class AdminSetting extends V1
{
/** 管理端接口必须校验管理员身份(V1 默认关闭了 URI 权限校验) */
public function _initialize()
{
parent::_initialize();
$this->adminOnly();
}
/**
* AS1 基础配置
* GET → {appName,logo,servicePhone,aboutUs,shareTitle}
@@ -30,11 +37,15 @@ class AdminSetting extends V1
if ($appName === '') {
$this->fail('小程序名称不能为空');
}
$logo = (string)$this->input('logo', $this->cfg('base.logo', ''));
$this->setCfg('base.appName', $appName);
$this->setCfg('base.logo', (string)$this->input('logo', $this->cfg('base.logo', '')));
$this->setCfg('base.logo', $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', '')));
// 兼容旧 ui.* 键,保持名称/LOGO 一致
$this->setCfg('ui.siteName', $appName);
$this->setCfg('ui.logo', $logo);
$this->adminLog('修改基础配置');
}
@@ -116,20 +127,26 @@ class AdminSetting extends V1
}
/**
* AS4 区域列表
* GET /api/v1/admin/setting/areas → 数组 [{id,name,sort,enabled}]
* AS4 服务区域列表(平铺:每条记录自带省 / 市 / 区县)
* GET /api/v1/admin/setting/areas → [{id,province,city,district,fullName,lat,lng,sort,enabled}]
* 规则:按 province asc, city asc, sort asc, id asc;返回全量(含停用)。
*/
public function areas()
{
$rows = Db::name('fc_area')->order('sort asc')->select();
$rows = Db::name('fc_area')->order('province asc, city asc, sort asc, id asc')->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'name' => (string)$row['name'],
'sort' => (int)$row['sort'],
'enabled' => (bool)$row['enabled'],
'id' => (int)$row['id'],
'province' => (string)$row['province'],
'city' => (string)$row['city'],
'district' => (string)$row['district'],
'fullName' => $row['province'] . ' / ' . $row['city'] . ' / ' . $row['district'],
'lat' => $row['lat'] !== null ? (float)$row['lat'] : null,
'lng' => $row['lng'] !== null ? (float)$row['lng'] : null,
'sort' => (int)$row['sort'],
'enabled' => (bool)$row['enabled'],
];
}
@@ -137,35 +154,82 @@ class AdminSetting extends V1
}
/**
* AS5 保存区域
* POST /api/v1/admin/setting/area 入参 {id?,name,sort,enabled} → {id,name}
* AS5 保存服务区域
* POST /api/v1/admin/setting/area 入参 {id?,province,city,district,sort,enabled,lat?,lng?} → {id,fullName}
* 规则:省 / 市 / 区县均必填;同一「省+市+区县」不允许重复。
*/
public function saveArea()
{
$id = (int)$this->input('id', 0);
$name = trim((string)$this->input('name', ''));
$province = trim((string)$this->input('province', ''));
$city = trim((string)$this->input('city', ''));
$district = trim((string)$this->input('district', ''));
$sort = (int)$this->input('sort', 0);
$enabled = (bool)$this->input('enabled', true);
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if ($name === '') {
$this->fail('区域名称不能为空');
$values = ['省份' => $province, '城市' => $city, '区县' => $district];
foreach ($values as $label => $value) {
if ($value === '') {
$this->fail($label . '不能为空');
}
if (mb_strlen($value) > 32) {
$this->fail($label . '不能超过 32 个字符');
}
}
// 同一条服务区域(省+市+区县)不允许重复
$duplicate = Db::name('fc_area')
->where('province', $province)
->where('city', $city)
->where('district', $district)
->where('id', '<>', $id)
->find();
if ($duplicate) {
$this->fail('该省市区组合已存在');
}
if ($lat !== null && $lat !== '') {
if (!is_numeric($lat) || (float)$lat < -90 || (float)$lat > 90) {
$this->fail('纬度格式不正确');
}
$lat = round((float)$lat, 6);
} else {
$lat = null;
}
if ($lng !== null && $lng !== '') {
if (!is_numeric($lng) || (float)$lng < -180 || (float)$lng > 180) {
$this->fail('经度格式不正确');
}
$lng = round((float)$lng, 6);
} else {
$lng = null;
}
$now = time();
$data = [
'name' => $name,
'sort' => $sort,
'enabled' => $enabled ? 1 : 0,
'province' => $province,
'city' => $city,
'district' => $district,
'lat' => $lat,
'lng' => $lng,
'sort' => $sort,
'enabled' => $enabled ? 1 : 0,
'updatetime' => $now,
];
if ($id && Db::name('fc_area')->where('id', $id)->find()) {
Db::name('fc_area')->where('id', $id)->update($data);
} else {
$data['createtime'] = $now;
$id = Db::name('fc_area')->insertGetId($data);
}
$this->adminLog('保存区域 #' . $id . ' ' . $name);
$fullName = $province . ' / ' . $city . ' / ' . $district;
$this->adminLog('保存服务区域 #' . $id . ' ' . $fullName);
$this->ok(['id' => (int)$id, 'name' => $name]);
$this->ok(['id' => (int)$id, 'fullName' => $fullName]);
}
/**
@@ -178,11 +242,19 @@ class AdminSetting extends V1
if ($this->request->isPost()) {
$siteName = $this->input('siteName', null);
if ($siteName !== null) {
$this->setCfg('ui.siteName', (string)$siteName);
$siteName = trim((string)$siteName);
if ($siteName === '') {
$this->fail('小程序名称不能为空');
}
$this->setCfg('base.appName', $siteName);
// 兼容旧 ui.siteName(用户端已统一优先读 base.appName)
$this->setCfg('ui.siteName', $siteName);
}
$logo = $this->input('logo', null);
if ($logo !== null) {
$this->setCfg('base.logo', (string)$logo);
// 兼容旧 ui.logo
$this->setCfg('ui.logo', (string)$logo);
}
@@ -206,7 +278,7 @@ class AdminSetting extends V1
}
$this->setCfg('ui.updatedAt', date('c'));
$this->adminLog('修改LOGO与图标配置');
$this->adminLog('修改小程序名称/LOGO/图标配置');
}
$this->ok($this->uiConfig());
@@ -218,17 +290,16 @@ class AdminSetting extends V1
*/
public function uiReset()
{
// LOGO 已统一到 base.logo,重置时两处都清空,避免旧 ui.logo 回落“复活”
$this->setCfg('base.logo', '');
$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,
]);
$config = $this->uiConfig();
$config['reset'] = true;
$this->ok($config);
}
/**
@@ -275,17 +346,29 @@ class AdminSetting extends V1
];
}
/** UI 配置结构(icons 保证为对象) */
/** UI 配置结构(名称/LOGO 以 base.* 为准,icons 保证为对象) */
protected function uiConfig()
{
$icons = $this->cfg('ui.icons', []);
$icons = is_array($icons) ? $icons : (array)$icons;
$baseName = trim((string)$this->cfg('base.appName', ''));
$siteName = $baseName !== '' ? $baseName : (string)$this->cfg('ui.siteName', '同城分类信息');
$baseLogo = (string)$this->cfg('base.logo', '');
$logo = $baseLogo !== '' ? $baseLogo : (string)$this->cfg('ui.logo', '');
$shareTitle = trim((string)$this->cfg('base.shareTitle', ''));
return [
'siteName' => (string)$this->cfg('ui.siteName', '同城分类信息'),
'logo' => (string)$this->cfg('ui.logo', ''),
'icons' => (object)$icons,
'updatedAt' => (string)$this->cfg('ui.updatedAt', date('c')),
'appName' => $siteName,
'siteName' => $siteName,
'logo' => $logo,
'servicePhone' => (string)$this->cfg('base.servicePhone', ''),
'aboutUs' => (string)$this->cfg('base.aboutUs', ''),
'shareTitle' => $shareTitle !== '' ? $shareTitle : $siteName,
'icons' => (object)$icons,
'updatedAt' => (string)$this->cfg('ui.updatedAt', date('c')),
];
}
}

查看文件

@@ -4,6 +4,7 @@ namespace app\api\controller;
use think\Db;
use app\common\library\DistributionService;
use app\common\library\WxMini;
/**
* 用户端 · 认证与登录(Module-AUTH)
@@ -31,6 +32,9 @@ class Auth extends V1
$this->fail('缺少微信授权 code');
}
// 频率限制:同一 IP 每分钟最多 30 次授权登录
$this->rateLimit('wxlogin:' . $this->request->ip(), 30, 60);
$nickname = trim((string)$this->input('nickname', ''));
$avatar = trim((string)$this->input('avatar', ''));
if (mb_strlen($nickname) > 32) {
@@ -42,7 +46,12 @@ class Auth extends V1
$manualPhone = trim((string)$this->input('phone', ''));
$phone = '';
if ($phoneCode !== '') {
$phone = $this->resolveWxPhone($phoneCode);
try {
$phone = WxMini::phoneNumber($phoneCode);
} catch (\Throwable $e) {
// 手机号属于可选增强:拿不到不阻断登录,前端可回落到手动绑定(A2 bindPhone)
$phone = '';
}
} elseif ($manualPhone !== '' && preg_match('/^1\d{10}$/', $manualPhone)) {
$phone = $manualPhone;
}
@@ -51,70 +60,86 @@ class Auth extends V1
$inviterId = (int)$this->input('inviterId', $this->input('inviter_id', 0));
$inviteCode = trim((string)$this->input('inviteCode', $this->input('invite_code', '')));
$ext = Db::name('fc_user_ext')->where('openid', $openid)->find();
$user = $ext ? Db::name('user')->where('id', $ext['user_id'])->find() : null;
// 同一 openid 串行建号:避免并发首次登录建出两个账号(usage: MySQL GET_LOCK)
$lockName = 'fc_wxlogin_' . md5($openid);
Db::query('SELECT GET_LOCK(?, 5)', [$lockName]);
if (!$user) {
// 首次登录:自动建号(有微信昵称/头像就落库,否则用占位昵称 + 字母头像)
$uid = Db::name('user')->insertGetId([
'group_id' => 1,
'username' => 'wx' . substr(md5($openid), 0, 10),
'nickname' => $nickname !== '' ? $nickname : '同城用户' . mt_rand(1000, 9999),
'password' => md5(mt_rand()),
'salt' => 'wx',
'email' => substr(md5($openid), 0, 12) . '@wx.local',
'mobile' => $phone,
'avatar' => $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(),
]);
// 首次登录:绑定分销推荐关系
DistributionService::bindRelation($uid, $inviterId, $inviteCode);
$user = Db::name('user')->where('id', $uid)->find();
} else {
// 老用户:若未绑定过推荐人,本次传入有效推荐人则尝试绑定
if ($inviterId > 0 || $inviteCode !== '') {
DistributionService::bindRelation($user['id'], $inviterId, $inviteCode);
try {
Db::startTrans();
$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' => $nickname !== '' ? $nickname : '同城用户' . mt_rand(1000, 9999),
'password' => md5(mt_rand()),
'salt' => 'wx',
'email' => substr(md5($openid), 0, 12) . '@wx.local',
'mobile' => $phone,
'avatar' => $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(),
]);
// 首次登录:绑定分销推荐关系
DistributionService::bindRelation($uid, $inviterId, $inviteCode);
$user = Db::name('user')->where('id', $uid)->find();
} else {
// 老用户:若未绑定过推荐人,本次传入有效推荐人则尝试绑定
if ($inviterId > 0 || $inviteCode !== '') {
DistributionService::bindRelation($user['id'], $inviterId, $inviteCode);
}
// 老用户:仅在本次带上了新值且确实不同时更新(不覆盖运营在后台改过的资料)
$update = [];
if ($nickname !== '' && $nickname !== (string)$user['nickname']) {
$update['nickname'] = $nickname;
}
if ($avatar !== '' && $avatar !== (string)$user['avatar']) {
$update['avatar'] = $avatar;
}
if ($phone !== '' && (string)$user['mobile'] === '') {
$update['mobile'] = $phone;
}
if ($update) {
$update['updatetime'] = time();
Db::name('user')->where('id', $user['id'])->update($update);
$user = Db::name('user')->where('id', $user['id'])->find();
}
}
// 老用户:仅在本次带上了新值且确实不同时更新(不覆盖运营在后台改过的资料)
$update = [];
if ($nickname !== '' && $nickname !== (string)$user['nickname']) {
$update['nickname'] = $nickname;
}
if ($avatar !== '' && $avatar !== (string)$user['avatar']) {
$update['avatar'] = $avatar;
}
if ($phone !== '' && (string)$user['mobile'] === '') {
$update['mobile'] = $phone;
}
if ($update) {
$update['updatetime'] = time();
Db::name('user')->where('id', $user['id'])->update($update);
$user = Db::name('user')->where('id', $user['id'])->find();
if ($user['status'] != 'normal') {
throw new \RuntimeException('账号已被禁用,请联系客服');
}
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
Db::query('SELECT RELEASE_LOCK(?)', [$lockName]);
$this->fail($e->getMessage() ?: '微信登录失败,请重试');
}
if ($user['status'] != 'normal') {
$this->fail('账号已被禁用,请联系客服');
}
Db::query('SELECT RELEASE_LOCK(?)', [$lockName]);
$token = $this->issueToken($user['id']);
$this->ok([
'token' => $token,
'refreshToken' => md5($token . 'refresh'),
'refreshToken' => $this->issueRefreshToken($user['id']),
'userInfo' => $this->userInfo($user),
]);
}
@@ -141,7 +166,7 @@ class Auth extends V1
* A5 微信手机号快捷获取
* 入参 { code }(`<button open-type="getPhoneNumber">` 回调里的 `e.detail.code`)
* → 出参 { phone }
* 规则:用小程序 access_token 调 phonenumber.getPhoneNumber 换号并写入 fa_user.mobile;
* 规则:由 EasyWeChat 的 `getuserphonenumber` 换号并写入 fa_user.mobile(见 \app\common\library\WxMini);
* 未配置微信参数 / 微信侧失败(快捷验证未开通、code 失效、用户拒绝)时返回业务失败,
* 前端据此回落到「手动输入手机号」(A2 bindPhone),保证任何情况下都能拿到号码。
*/
@@ -154,29 +179,11 @@ class Auth extends V1
$this->fail('缺少手机号授权 code');
}
$appid = (string)$this->cfg('wx.appid', '');
$secret = (string)$this->cfg('wx.secret', '');
if ($appid === '' || $secret === '') {
$this->fail('未配置小程序 AppID/AppSecret,请改用手动输入');
}
$token = $this->wxAccessToken($appid, $secret);
if ($token === '') {
$this->fail('微信 access_token 获取失败,请改用手动输入');
}
$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
$res = $this->wxCurlPost($url, ['code' => $code]);
$phone = '';
if (!empty($res['phone_info']['phoneNumber'])) {
$phone = (string)$res['phone_info']['phoneNumber'];
} elseif (!empty($res['phone_info']['purePhoneNumber'])) {
$phone = (string)$res['phone_info']['purePhoneNumber'];
}
if (!preg_match('/^1\d{10}$/', $phone)) {
try {
$phone = WxMini::phoneNumber($code);
} catch (\Throwable $e) {
// 常见原因:手机号快捷验证未开通/额度用尽、code 已失效、用户拒绝授权
$this->fail('微信手机号获取失败,请改用手动输入');
$this->fail($e->getMessage() ?: '微信手机号获取失败,请改用手动输入');
}
Db::name('user')->where('id', $user['id'])->update([
@@ -186,35 +193,6 @@ class Auth extends V1
$this->ok(['phone' => $phone]);
}
/**
* 小程序 access_token(带缓存,提前 5 分钟失效)
* 缓存写入 fc_config 的 wx.accessToken / wx.accessTokenExpire(仅服务端读取,不下发前端)
* @param string $appid
* @param string $secret
* @return string 失败返回空串
*/
protected function wxAccessToken($appid, $secret)
{
$now = time();
$cached = (string)$this->cfg('wx.accessToken', '');
$expire = (int)$this->cfg('wx.accessTokenExpire', 0);
if ($cached !== '' && $expire > $now + 300) {
return $cached;
}
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'
. '&appid=' . $appid . '&secret=' . $secret;
$res = $this->wxCurlGet($url);
if (empty($res['access_token'])) {
return '';
}
$this->setCfg('wx.accessToken', (string)$res['access_token']);
$this->setCfg('wx.accessTokenExpire', $now + (int)(!empty($res['expires_in']) ? $res['expires_in'] : 7200));
return (string)$res['access_token'];
}
/**
* A3 用户类型切换
* 入参 { userType: 1|2, license? } → 出参 { userType, needAudit }
@@ -325,58 +303,19 @@ class Auth extends V1
/**
* code -> openid
* 已配置微信参数时走 jscode2session;未配置(本地/联调)时用确定性派生,便于前后端联调。
* 由 EasyWeChat SDK 调 jscode2session(\app\common\library\WxMini)。
* 兼容:本地未配置 AppID/AppSecret 且开启 debug 时,用确定性派生便于前后端联调。
*/
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 = $this->wxCurlGet($url);
if (!empty($res['openid'])) {
return $res['openid'];
try {
return WxMini::openid($code);
} catch (\Throwable $e) {
if (!WxMini::isConfigured() && config('app_debug')) {
return strpos($code, 'openid_') === 0 ? $code : 'openid_' . md5($code);
}
$this->fail($e->getMessage() ?: '微信登录失败,请重试');
}
// 未配置微信参数:若 code 本身即为 openid 标识则直接采用,否则派生
if (strpos($code, 'openid_') === 0) {
return $code;
}
return 'openid_' . md5($code);
}
/**
* 微信手机号快捷 code 解析为真实手机号
* @param string $phoneCode 微信开放能力获取的临时凭证
* @return string 成功返回11位手机号,失败返回空字符串
*/
protected function resolveWxPhone($phoneCode)
{
if ($phoneCode === '') {
return '';
}
$appid = (string)$this->cfg('wx.appid', '');
$secret = (string)$this->cfg('wx.secret', '');
if ($appid === '' || $secret === '') {
return '';
}
$token = $this->wxAccessToken($appid, $secret);
if ($token === '') {
return '';
}
$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
$res = $this->wxCurlPost($url, ['code' => $phoneCode]);
$phone = '';
if (!empty($res['phone_info']['phoneNumber'])) {
$phone = (string)$res['phone_info']['phoneNumber'];
} elseif (!empty($res['phone_info']['purePhoneNumber'])) {
$phone = (string)$res['phone_info']['purePhoneNumber'];
}
return preg_match('/^1\d{10}$/', $phone) ? $phone : '';
}
/**
@@ -522,6 +461,66 @@ class Auth extends V1
$this->ok(['auditStatus' => 0, 'needAudit' => true], '商家资质已提交,等待平台审核');
}
/**
* A11 保存收款人真实姓名(提现用)
* POST /api/v1/auth/realname {realname}
* 规则:2-20 位中文(含 ·),需与微信实名一致,否则商家转账会校验失败
*/
public function realname()
{
$user = $this->auth();
$realname = trim((string)$this->input('realname', ''));
if (!preg_match('/^[\x{4e00}-\x{9fa5}·]{2,20}$/u', $realname)) {
$this->fail('请输入 2-20 位中文真实姓名');
}
$this->ext($user['id']);
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'realname' => $realname,
'realname_status' => 1,
'updatetime' => time(),
]);
$this->ok(['realname' => $realname]);
}
/**
* A10 刷新访问令牌
* POST /api/v1/auth/refresh { refreshToken }
* 规则:refreshToken 必须为 rf_ 前缀且未过期;换新后旧刷新令牌立即作废(轮换)
*/
public function refresh()
{
$refresh = trim((string)$this->input('refreshToken', $this->input('refresh_token', '')));
if ($refresh === '') {
$this->fail('缺少 refreshToken');
}
$this->rateLimit('refresh:' . $this->request->ip(), 20, 60);
if (strpos($refresh, 'rf_') !== 0) {
$this->fail('refreshToken 无效');
}
$row = Db::name('user_token')->where('token', $refresh)->find();
if (!$row || (int)$row['expiretime'] < time()) {
$this->fail('登录已过期,请重新登录', 401, 401);
}
$user = Db::name('user')->where('id', (int)$row['user_id'])->find();
if (!$user || $user['status'] !== 'normal') {
$this->fail('账号状态异常,请重新登录', 401, 401);
}
// 轮换:旧刷新令牌立即失效(fa_user_token 主键是 token,没有 id 列)
Db::name('user_token')->where('token', $refresh)->delete();
$this->ok([
'token' => $this->issueToken($user['id']),
'refreshToken' => $this->issueRefreshToken($user['id']),
]);
}
/**
* A9 手机号密码登录(支持 H5 / 调试环境)
* POST /api/v1/auth/password-login
@@ -543,55 +542,28 @@ class Auth extends V1
$this->fail('密码长度不能少于 6 位');
}
// 频率限制:同一手机号 + IP,1 分钟最多 5 次
$this->rateLimit('pwdlogin:' . $phone . ':' . $this->request->ip(), 5, 60);
$inviterId = (int)$this->input('inviterId', $this->input('inviter_id', 0));
$inviteCode = trim((string)$this->input('inviteCode', $this->input('invite_code', '')));
// 查用户
// 查用户:不存在直接失败,不再自动注册(防止批量造号)
$user = Db::name('user')->where('mobile', $phone)->find();
if (!$user) {
// 为方便 H5 快速调试,如果手机号不存在,则自动初始化该测试账号
$salt = substr(md5(uniqid(rand(), true)), 0, 4);
$hashPwd = md5(md5($password) . $salt);
$uid = Db::name('user')->insertGetId([
'group_id' => 1,
'username' => 'u' . $phone,
'nickname' => '同城用户' . substr($phone, -4),
'password' => $hashPwd,
'salt' => $salt,
'email' => $phone . '@local.phone',
'mobile' => $phone,
'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' => 'h5_' . md5($phone), '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(),
]);
// 首次登录:绑定分销推荐关系
DistributionService::bindRelation($uid, $inviterId, $inviteCode);
$user = Db::name('user')->where('id', $uid)->find();
} else {
// 老用户:若未绑定过推荐人,本次传入有效推荐人则尝试绑定
if ($inviterId > 0 || $inviteCode !== '') {
DistributionService::bindRelation($user['id'], $inviterId, $inviteCode);
}
// 校验密码(支持初始密码 123456 或正确加盐密码)
$salt = isset($user['salt']) ? (string)$user['salt'] : '';
$checkHash = md5(md5($password) . $salt);
$isCorrect = ($user['password'] === $checkHash) || ($password === '123456');
if (!$isCorrect) {
$this->fail('密码错误,请重新输入');
}
$this->fail('手机号未注册,请先使用微信登录');
}
// 老用户:若未绑定过推荐人,本次传入有效推荐人则尝试绑定
if ($inviterId > 0 || $inviteCode !== '') {
DistributionService::bindRelation($user['id'], $inviterId, $inviteCode);
}
// 校验密码:只认加盐哈希(已移除历史遗留的 123456 万能密码)
$salt = isset($user['salt']) ? (string)$user['salt'] : '';
$checkHash = md5(md5($password) . $salt);
if ((string)$user['password'] !== $checkHash) {
$this->fail('密码错误,请重新输入');
}
if ($user['status'] !== 'normal') {
@@ -601,59 +573,8 @@ class Auth extends V1
$token = $this->issueToken($user['id']);
$this->ok([
'token' => $token,
'refreshToken' => md5($token . 'refresh'),
'refreshToken' => $this->issueRefreshToken($user['id']),
'userInfo' => $this->userInfo($user),
]);
}
/**
* 微信官方 API 专用 cURL GET 请求
* 彻底解决 Windows 与部分 Linux 下 file_get_contents SSL 握手失败问题
*
* @param string $url 目标请求地址
* @param int $timeout 超时时间(秒)
* @return array 解析后的关联数组
*/
protected function wxCurlGet($url, $timeout = 8)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$res = curl_exec($ch);
curl_close($ch);
if (!$res) {
return [];
}
$json = @json_decode($res, true);
return is_array($json) ? $json : [];
}
/**
* 微信官方 API 专用 cURL POST 请求
*
* @param string $url 目标请求地址
* @param array $data 提交的 JSON 结构数据
* @param int $timeout 超时时间(秒)
* @return array 解析后的关联数组
*/
protected function wxCurlPost($url, array $data, $timeout = 8)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
$res = curl_exec($ch);
curl_close($ch);
if (!$res) {
return [];
}
$json = @json_decode($res, true);
return is_array($json) ? $json : [];
}
}

查看文件

@@ -114,6 +114,57 @@ class Coupon extends V1
$this->ok(['userCouponId' => $userCouponId]);
}
/**
* GET /api/v1/coupon/usable?amount=xx
* 下单可用券列表(按金额计算可抵扣金额)
*/
public function usable()
{
$this->assertEnabled();
$user = $this->auth();
$amount = round((float)$this->input('amount', 0), 2);
if ($amount <= 0) {
$this->ok([]);
}
$now = time();
$rows = Db::name('fc_user_coupon')->alias('uc')
->join('fc_coupon c', 'c.id = uc.coupon_id')
->where('uc.user_id', $user['id'])
->where('uc.status', 'unused')
->where('c.enabled', 1)
->where('c.min_amount', '<=', $amount)
->where(function ($q) use ($now) {
$q->whereNull('uc.expiretime')->whereOr('uc.expiretime', '>', $now);
})
->field('uc.id,uc.coupon_id,uc.expiretime,c.name,c.type,c.amount,c.min_amount')
->order('c.sort desc, c.id desc')
->select();
$list = [];
foreach ($rows as $row) {
try {
$p = \app\common\library\CouponService::preview($user['id'], (int)$row['id'], $amount);
} catch (\Throwable $e) {
continue;
}
$list[] = [
'userCouponId' => (int)$row['id'],
'couponId' => (int)$row['coupon_id'],
'name' => (string)$row['name'],
'type' => (string)$row['type'],
'amount' => (float)$row['amount'],
'minAmount' => (float)$row['min_amount'],
'discount' => $p['discount'],
'payable' => $p['payable'],
'expireAt' => !empty($row['expiretime']) ? $this->iso($row['expiretime']) : null,
];
}
$this->ok($list);
}
/**
* 券模板 → 列表项
* @param array $row fc_coupon 行

查看文件

@@ -23,10 +23,11 @@ class Distribution extends V1
$user = $this->auth();
$uid = (int)$user['id'];
$total = (float)Db::name('fc_commission')->where('user_id', $uid)->sum('amount');
$total = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', '<>', 2)->sum('amount');
$settled = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 1)->sum('amount');
$pending = (float)Db::name('fc_commission')->where('user_id', $uid)->where('status', 0)->sum('amount');
$applied = (float)Db::name('fc_withdraw')->where('user_id', $uid)
->where('status', 'in', ['auditing', 'paid'])->sum('amount');
->where('status', 'in', ['auditing', 'paying', 'paid'])->sum('amount');
$withdrawable = $settled - $applied;
$todayStart = strtotime(date('Y-m-d'));
@@ -38,10 +39,15 @@ class Distribution extends V1
$ext = $this->ext($uid);
// 商家转账确认收款页需要的商户号与小程序 AppID(非敏感,可下发)
$epay = (array)get_addon_config('epay');
$wx = isset($epay['wechat']) && is_array($epay['wechat']) ? $epay['wechat'] : [];
$this->ok([
'totalCommission' => round($total, 2),
'settled' => round($settled, 2),
'withdrawable' => round($withdrawable, 2),
'pendingCommission' => round($pending, 2),
'withdrawable' => round(max(0, $withdrawable), 2),
'todayCommission' => round($todayCommission, 2),
'teamCount' => $l1 + $l2,
'l1Count' => $l1,
@@ -50,6 +56,10 @@ class Distribution extends V1
'posterUrl' => '',
// 最低提现金额(后台「分销设置」下发,替代前端写死的 50)
'minWithdraw' => (float)$this->cfg('dist.minWithdraw', 50),
// 提现收款人实名(未填写时前端需先采集)
'realname' => isset($ext['realname']) ? (string)$ext['realname'] : '',
'transferMchId' => isset($wx['mch_id']) ? (string)$wx['mch_id'] : '',
'transferAppId' => isset($wx['miniapp_id']) ? (string)$wx['miniapp_id'] : '',
]);
}
@@ -107,33 +117,54 @@ class Distribution extends V1
{
$user = $this->auth();
$uid = (int)$user['id'];
$amount = (float)$this->input('amount', 0);
$this->rateLimit('withdraw:' . $uid, 3, 60);
$amount = round((float)$this->input('amount', 0), 2);
$min = (float)$this->cfg('dist.minWithdraw', 50);
if ($amount <= 0) {
$this->fail('提现金额不合法');
}
if ($amount > $this->withdrawable($uid)) {
$this->fail('提现金额超过可提现余额');
if ($min > 0 && $amount < $min) {
$this->fail('最低提现金额为 ' . $min . ' 元');
}
// 微信商家转账会校验收款人实名,未填写姓名不允许提现
$ext = $this->ext($uid);
if (trim((string)(isset($ext['realname']) ? $ext['realname'] : '')) === '') {
$this->fail('请先填写收款人真实姓名(需与微信实名一致)');
}
$channel = trim((string)$this->input('channel', ''));
if ($channel === '') {
$channel = 'wxpay';
}
$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(),
]);
try {
Db::transaction(function () use ($uid, $amount, $channel, $withdrawNo) {
// 用户扩展行加锁:同一用户的提现申请串行化,避免并发双花
Db::name('fc_user_ext')->where('user_id', $uid)->lock(true)->find();
if ($amount > $this->withdrawable($uid)) {
throw new \RuntimeException('提现金额超过可提现余额');
}
Db::name('fc_withdraw')->insert([
'withdraw_no' => $withdrawNo,
'user_id' => $uid,
'amount' => $amount,
'channel' => $channel,
'status' => 'auditing',
'reason' => '',
'paytime' => null,
'createtime' => time(),
'updatetime' => time(),
]);
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '提现申请失败,请重试');
}
$this->notify($uid, 'system', '提现申请已提交', '提现 ¥' . $amount . ' 已提交,预计 T+7 到账');
@@ -153,11 +184,14 @@ class Distribution extends V1
$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']),
'id' => (int)$row['id'],
'withdrawNo' => (string)$row['withdraw_no'],
'amount' => round((float)$row['amount'], 2),
'status' => (string)$row['status'],
'transferStatus' => (string)(isset($row['transfer_status']) ? $row['transfer_status'] : ''),
'packageInfo' => (string)(isset($row['package_info']) ? $row['package_info'] : ''),
'failReason' => (string)(isset($row['fail_reason']) ? $row['fail_reason'] : ''),
'createdAt' => $this->iso($row['createtime']),
];
}
@@ -171,7 +205,7 @@ class Distribution extends V1
{
$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');
->where('status', 'in', ['auditing', 'paying', 'paid'])->sum('amount');
return $settled - $applied;
}
}

查看文件

@@ -11,7 +11,8 @@ use think\Db;
* GET /api/v1/home/categories H2 分类导航
* GET /api/v1/home/search/hot H3 热门搜索
* GET /api/v1/home/feed H4 信息流(支持 lat/lng + sort=nearby 距离排序)
* GET /api/v1/home/areas H5 区域列表(用户端下拉筛选,读后台「区域管理」)
* GET /api/v1/home/areas H5 服务区域列表(平铺省/市/区县,区县为服务区域)
* GET /api/v1/home/locate H6 按定位坐标匹配服务区域
*/
class Home extends V1
{
@@ -90,28 +91,81 @@ class Home extends V1
}
/**
* H5 区域列表(用户端筛选用)
* GET /api/v1/home/areas → [string]
* 规则:仅 enabled=1,按 sort asc;与后台「区域管理」(fc_area) 同源,
* 前端首页/信息列表/发布页的「区域」选项均由此下发,不再前端写死。
* H5 服务区域列表(平铺:每条记录自带省 / 市 / 区县)
* GET /api/v1/home/areas → [{id,province,city,district,lat,lng}]
* 规则:仅 enabled=1;按省、市、sort、id 排序。
* 区县为最终服务区域;省 / 市由前端按 distinct 值生成级联列。
*/
public function areas()
{
$rows = Db::name('fc_area')
->where('enabled', 1)
->order('sort asc')
->order('province asc, city asc, sort asc, id asc')
->select();
$list = [];
foreach ($rows as $row) {
$list[] = (string)$row['name'];
$list[] = [
'id' => (int)$row['id'],
'province' => (string)$row['province'],
'city' => (string)$row['city'],
'district' => (string)$row['district'],
'lat' => $row['lat'] !== null ? (float)$row['lat'] : null,
'lng' => $row['lng'] !== null ? (float)$row['lng'] : null,
];
}
$this->ok($list);
}
/**
* H6 按定位坐标匹配服务区域(区县)
* GET /api/v1/home/locate?lat=&lng= → {areaId,province,city,district,distance}
* 规则:在启用的服务区域中心点中取最近的一个(Haversine),超出 300km 视为不在服务范围,返回 null。
*/
public function locate()
{
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if (!is_numeric($lat) || !is_numeric($lng)) {
$this->ok(null);
}
$lat = (float)$lat;
$lng = (float)$lng;
if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180 || ($lat == 0.0 && $lng == 0.0)) {
$this->ok(null);
}
$rows = Db::name('fc_area')
->where('enabled', 1)
->whereNotNull('lat')
->whereNotNull('lng')
->select();
$best = null;
foreach ($rows as $row) {
$distance = $this->haversine($lat, $lng, (float)$row['lat'], (float)$row['lng']);
if ($best === null || $distance < $best['distance']) {
$best = ['row' => $row, 'distance' => $distance];
}
}
if (!$best || $best['distance'] > 300) {
$this->ok(null);
}
$area = $best['row'];
$this->ok([
'areaId' => (int)$area['id'],
'province' => (string)$area['province'],
'city' => (string)$area['city'],
'district' => (string)$area['district'],
'distance' => $best['distance'],
]);
}
/**
* H4 信息流
* GET /api/v1/home/feed {categoryId?,keyword?,area?,sort?,lat?,lng?,page,size}
* GET /api/v1/home/feed {categoryId?,keyword?,areaId?,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 则回落发布时间倒序);
@@ -124,6 +178,11 @@ class Home extends V1
$categoryId = (int)$this->input('categoryId', 0);
$keyword = trim((string)$this->input('keyword', ''));
$area = trim((string)$this->input('area', ''));
// 服务区域 ID(兼容上一版的 districtId 参数)
$areaId = (int)$this->input('areaId', 0);
if (!$areaId) {
$areaId = (int)$this->input('districtId', 0);
}
$sort = (string)$this->input('sort', '');
// 容错处理:过滤前端小程序可能序列化出的 undefined 与 null 字符串
if ($area === 'undefined' || $area === 'null') {
@@ -146,9 +205,22 @@ class Home extends V1
if ($keyword !== '') {
$query->where('title', 'like', '%' . $keyword . '%');
}
if ($area !== '') {
$query->where('area', $area);
}
$applyArea = function ($q) use ($area, $areaId) {
// 服务区域 = 区县:areaId 优先,兼容旧的 area=区县名称
if ($areaId > 0) {
$row = Db::name('fc_area')->where('id', $areaId)->find();
if ($row) {
$q->where(function ($w) use ($row) {
$w->where('district_id', (int)$row['id'])->whereOr('area', (string)$row['district']);
});
}
return;
}
if ($area !== '') {
$q->where('area', $area);
}
};
$applyArea($query);
$counter = Db::name('fc_post')
->where('audit_status', 1)
@@ -160,9 +232,7 @@ class Home extends V1
if ($keyword !== '') {
$counter->where('title', 'like', '%' . $keyword . '%');
}
if ($area !== '') {
$counter->where('area', $area);
}
$applyArea($counter);
$total = $counter->count();
// 「附近」:距离在 PHP 内用 Haversine 计算后排序(不用 SQL 距离函数,避免 MySQL 兼容问题);
@@ -306,6 +376,7 @@ class Home extends V1
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'address' => (string)$row['address'],
'contact' => $this->maskPhone($row['phone']),
'views' => (int)$row['views'],

查看文件

@@ -103,54 +103,97 @@ class Member extends V1
$this->fail('套餐不存在');
}
$amount = round((float)$plan['price'], 2);
$originAmount = round((float)$plan['price'], 2);
$userCouponId = (int)$this->input('userCouponId', 0);
// 优惠券:先试算(事务外只校验,真正锁定在事务内)
$couponAmount = 0;
$hasCoupon = false;
if ($userCouponId > 0) {
try {
$couponInfo = \app\common\library\CouponService::preview($user['id'], $userCouponId, $originAmount);
} catch (\Throwable $e) {
$this->fail($e->getMessage());
}
$couponAmount = $couponInfo['discount'];
$hasCoupon = true;
}
$amount = round($originAmount - $couponAmount, 2);
$now = time();
$isBalance = $payType === 'balance';
// 余额校验必须在落订单之前:否则余额不足时已插入一条 status=paid 的假订单
$balance = (float)$user['money'];
if ($isBalance && $balance < $amount) {
if ($isBalance && (float)$user['money'] < $amount) {
$this->fail('余额不足');
}
$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' => $isBalance ? 'paid' : 'pending',
'paytime' => $isBalance ? $now : null,
// related_id 存套餐主键:支付回调 /pay/notify 据此复用 grantMembership(),回调可独立完成
'related_id' => (int)$plan['id'],
'createtime' => $now,
'updatetime' => $now,
]);
$grant = null;
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;
try {
// 扣款 + 落订单 + 发放会员 同一事务:任一步失败整体回滚
Db::transaction(function () use (&$grant, $isBalance, $amount, $originAmount, $couponAmount, $hasCoupon, $userCouponId, $user, $plan, $payType, $orderNo, $now) {
// 锁券(与订单同事务,失败则整体回滚)
if ($hasCoupon) {
\app\common\library\CouponService::lock($user['id'], $userCouponId, $originAmount, $orderNo);
}
if ($isBalance) {
// 条件扣款:并发下不会扣成负数
$affected = Db::name('user')
->where('id', (int)$user['id'])
->where('money', '>=', $amount)
->setDec('money', $amount);
if (!$affected) {
throw new \RuntimeException('余额不足');
}
}
$orderId = Db::name('fc_order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'member',
'title' => (string)$plan['name'],
'amount' => $amount,
'origin_amount' => $originAmount,
'coupon_amount' => $couponAmount,
'coupon_id' => $hasCoupon ? $userCouponId : 0,
'pay_type' => $payType,
'status' => $isBalance ? 'paid' : 'pending',
'paytime' => $isBalance ? $now : null,
// related_id 存套餐主键:支付回调 /pay/notify 据此复用 grantMembership(),回调可独立完成
'related_id' => (int)$plan['id'],
'createtime' => $now,
'updatetime' => $now,
]);
if ($isBalance) {
// 余额支付:立即发放会员(微信支付等待回调发放)
$grant = $this->grantMembership(Db::name('fc_order')->where('id', $orderId)->find());
// 券核销(微信支付在 OrderFulfill 里核销)
\app\common\library\CouponService::markUsed($orderNo);
}
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '开通失败,请重试');
}
$quota = isset($plan['post_quota']) ? max(0, (int)$plan['post_quota']) : 0;
$this->ok([
'orderNo' => $orderNo,
'status' => $isBalance ? 'paid' : 'pending',
'amount' => $amount,
'originAmount' => $originAmount,
'couponAmount' => $couponAmount,
// 微信支付:前端拿到 orderNo 后调 /pay/prepay;余额支付无需再支付(order=null)
'order' => $isBalance ? null : [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => 'wxpay',
'status' => 'pending',
'orderNo' => $orderNo,
'amount' => $amount,
'originAmount' => $originAmount,
'couponAmount' => $couponAmount,
'payType' => 'wxpay',
'status' => 'pending',
],
'expireAt' => $grant ? $this->iso($grant['expireAt']) : null,
'postQuota' => $quota,

查看文件

@@ -91,11 +91,11 @@ class Order extends V1
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,
]);
// 原子自增:并发回调/重复入账时不会丢更新(幂等由订单状态保证)
Db::name('user')->where('id', $userId)->setInc('money', $amount);
$balance = round((float)Db::name('user')->where('id', $userId)->value('money'), 2);
Db::name('user')->where('id', $userId)->update(['updatetime' => $now]);
$this->flow('income', '余额充值', $amount, $balance, $orderId, '余额充值');
$this->notify(

查看文件

@@ -4,7 +4,7 @@ namespace app\api\controller;
use addons\epay\library\Service as EpayService;
use think\Db;
use app\common\library\DistributionService;
use app\common\library\OrderFulfill;
/**
* 用户端 · 微信支付(Module-PAY)
@@ -48,19 +48,48 @@ class Pay extends V1
/**
* 插件是否已具备「小程序支付」所需的最小配置
*
* 说明:小程序支付由 yansongda 的 MiniappGateway 负责,它固定使用配置里的 miniapp_id 作为 appid,
* 因此「公众号 appid」填了也**不生效**,必须填 miniapp_id;服务商模式(mode=service)另需子商户参数。
* 说明:小程序支付由 yansongda 的 Mini 网关负责,它固定使用配置里的 miniapp_id 作为 appid,
* 因此「公众号 appid」填了也**不生效**,必须填 miniapp_id。
* V2:miniapp_id + mch_id + key(APIv2 密钥)
* V3:miniapp_id + mch_id + key_v3(APIv3 密钥)+ public_key_id + 商户证书 + 微信支付公钥
*/
protected function epayReady()
{
$wx = $this->epayWechat();
$mode = isset($wx['mode']) ? (string)$wx['mode'] : 'normal';
$cfg = (array)get_addon_config('epay');
$wx = $this->epayWechat();
$mode = isset($wx['mode']) ? (string)$wx['mode'] : 'normal';
$isV3 = (isset($cfg['version']) ? (string)$cfg['version'] : 'v2') === EpayService::SDK_VERSION_V3;
if ($mode === 'service') {
return !empty($wx['sub_mch_id']) && !empty($wx['key']) && !empty($wx['sub_miniapp_id']);
$baseReady = !empty($wx['sub_mch_id']) && !empty($wx['key']) && !empty($wx['sub_miniapp_id']);
} else {
$baseReady = !empty($wx['miniapp_id']) && !empty($wx['mch_id']);
}
return !empty($wx['miniapp_id']) && !empty($wx['mch_id']) && !empty($wx['key']);
if (!$baseReady) {
return false;
}
if (!$isV3) {
return !empty($wx['key']);
}
// V3:证书 + 公钥缺一不可,否则下单会抛 SDK 异常而不是清晰的「未配置」提示
if (empty($wx['key_v3']) || empty($wx['public_key_id'])) {
return false;
}
foreach (['cert_client', 'cert_key', 'public_key'] as $field) {
$path = isset($wx[$field]) ? trim((string)$wx[$field]) : '';
// 与 Service::processAddonsPath() 同口径:/addons/... 相对项目根目录
$file = strpos($path, '/addons/') === 0
? ROOT_PATH . str_replace('/', DIRECTORY_SEPARATOR, substr($path, 1))
: $path;
if ($file === '' || !is_file($file) || filesize($file) === 0) {
return false;
}
}
return true;
}
/** 本店铺的支付回调地址(供微信服务端回调,指向本控制器 notifyCallback) */
@@ -86,6 +115,7 @@ class Pay extends V1
public function prepay()
{
$user = $this->auth();
$this->rateLimit('prepay:' . $user['id'], 10, 60);
$orderNo = trim((string)$this->input('orderNo', ''));
if ($orderNo === '') {
@@ -108,6 +138,15 @@ class Pay extends V1
if ((string)$order['pay_type'] !== 'wxpay') {
$this->fail('该订单不是微信支付');
}
// 超时未支付自动关闭(24 小时),避免 pending 订单无限堆积
if (!empty($order['createtime']) && (int)$order['createtime'] < time() - 86400) {
Db::name('fc_order')->where('id', (int)$order['id'])->where('status', 'pending')->update([
'status' => 'closed',
'updatetime' => time(),
]);
\app\common\library\CouponService::release((string)$order['order_no']);
$this->fail('订单已超时关闭,请重新下单');
}
if (!$this->epayReady()) {
$this->fail('微信支付未配置');
@@ -157,6 +196,36 @@ class Pay extends V1
]);
}
/**
* GET /api/v1/pay/status?orderNo=xxx
* 查询订单支付状态(供前端支付后轮询:客户端支付成功 ≠ 服务端回调已到账)
*/
public function status()
{
$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);
}
$this->ok([
'orderNo' => (string)$order['order_no'],
'status' => (string)$order['status'],
'paid' => (string)$order['status'] === 'paid',
'amount' => (float)$order['amount'],
'paytime' => !empty($order['paytime']) ? $this->iso($order['paytime']) : null,
]);
}
/* ==================== 回调 ==================== */
/**
@@ -189,14 +258,18 @@ class Pay extends V1
*/
public function notifyCallback()
{
// 未配置支付参数:返回 SUCCESS 但不处理(避免微信重试风暴)
$isV3 = EpayService::isVersionV3();
// 未配置:记录错误并返回 FAIL(微信会按策略重试),避免“静默丢单”
if (!$this->epayReady()) {
$this->replyXml('SUCCESS', 'OK');
\think\Log::record('微信支付回调:插件配置不完整(证书/密钥缺失),无法验签处理', 'error');
$this->replyFail('支付未配置');
}
try {
$pay = EpayService::checkNotify('wechat');
} catch (\Throwable $e) {
\think\Log::record('微信支付回调验签异常:' . $e->getMessage(), 'error');
$pay = false;
}
if (!$pay) {
@@ -205,25 +278,60 @@ class Pay extends V1
}
try {
$data = EpayService::isVersionV3() ? $pay->callback() : $pay->verify();
$data = $isV3 ? $pay->callback() : $pay->verify();
// V3 回调为加密报文,需取 resource.ciphertext(插件 controller/Index.php 同款处理)
if (EpayService::isVersionV3() && isset($data['resource']['ciphertext'])) {
if ($isV3) {
if (!isset($data['resource']['ciphertext'])) {
$this->replyFail('回调报文异常');
}
$data = $data['resource']['ciphertext'];
$data['total_fee'] = $data['amount']['total'];
}
} catch (\Throwable $e) {
\think\Log::record('微信支付回调报文解析失败:' . $e->getMessage(), 'error');
$this->replyFail('回调报文解析失败');
}
$data = $data instanceof \Yansongda\Supports\Collection ? $data->all() : (array)$data;
// 状态判定:V2 用 return_code/result_code,V3 用 trade_state(两者字段完全不同)
if ($isV3) {
$succeeded = isset($data['trade_state']) && (string)$data['trade_state'] === 'SUCCESS';
$paidFee = isset($data['amount']['total']) ? (int)$data['amount']['total'] : 0;
$currency = isset($data['amount']['currency']) ? (string)$data['amount']['currency'] : '';
$cbMchId = isset($data['mchid']) ? (string)$data['mchid'] : '';
$cbAppId = isset($data['appid']) ? (string)$data['appid'] : '';
} else {
$succeeded = (isset($data['return_code']) && (string)$data['return_code'] === 'SUCCESS')
&& (isset($data['result_code']) && (string)$data['result_code'] === 'SUCCESS');
$paidFee = isset($data['total_fee']) ? (int)$data['total_fee'] : 0;
$currency = 'CNY';
$cbMchId = isset($data['mch_id']) ? (string)$data['mch_id'] : '';
$cbAppId = isset($data['appid']) ? (string)$data['appid'] : '';
}
// 支付未成功(用户取消/支付失败/订单关闭):不处理,仍回 SUCCESS 避免微信持续重试
if (!isset($data['return_code']) || (string)$data['return_code'] !== 'SUCCESS'
|| !isset($data['result_code']) || (string)$data['result_code'] !== 'SUCCESS') {
$this->replyXml('SUCCESS', 'OK');
if (!$succeeded) {
$this->replyOk();
}
// 商户号 / 小程序 appid / 币种校验(防串单、防跨商户重放)
$wx = $this->epayWechat();
$expectMch = (string)(isset($wx['mch_id']) ? $wx['mch_id'] : '');
$expectApp = (string)(isset($wx['miniapp_id']) ? $wx['miniapp_id'] : '');
if (($expectMch !== '' && $cbMchId !== '' && $cbMchId !== $expectMch)
|| ($expectApp !== '' && $cbAppId !== '' && $cbAppId !== $expectApp)) {
\think\Log::record('微信支付回调商户/应用不匹配:mchid=' . $cbMchId . ' appid=' . $cbAppId, 'error');
$this->replyFail('商户信息不匹配');
}
if ($currency !== '' && $currency !== 'CNY') {
\think\Log::record('微信支付回调币种异常:' . $currency, 'error');
$this->replyFail('币种不支持');
}
$orderNo = isset($data['out_trade_no']) ? (string)$data['out_trade_no'] : '';
$order = $orderNo !== '' ? Db::name('fc_order')->where('order_no', $orderNo)->find() : null;
if ($orderNo === '') {
$this->replyFail('回调缺少订单号');
}
$order = Db::name('fc_order')->where('order_no', $orderNo)->find();
if (!$order) {
// 返回 FAIL:微信会重试,给订单落库/同步留出重放机会
$this->replyFail('订单不存在');
@@ -231,11 +339,14 @@ class Pay extends V1
// 幂等:已支付直接回 SUCCESS(微信可能重复通知)
if ((string)$order['status'] === 'paid') {
$this->replyXml('SUCCESS', 'OK');
$this->replyOk();
}
if ((string)$order['status'] !== 'pending') {
\think\Log::record('微信支付回调:订单 ' . $orderNo . ' 状态为 ' . $order['status'] . ',不处理', 'error');
$this->replyOk();
}
// 金额核对:回调金额(分)必须等于订单金额(元 ×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');
@@ -243,54 +354,34 @@ class Pay extends V1
}
$now = time();
$handled = false;
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,
]);
}
}
// 事务 + 行锁:并发/重复回调只会成功处理一次,避免重复发放会员/余额/佣金
Db::transaction(function () use ($order, $now, &$handled) {
$locked = Db::name('fc_order')->where('id', (int)$order['id'])->lock(true)->find();
if (!$locked || (string)$locked['status'] !== 'pending') {
return;
}
// type=post:信息已在待审,无需额外动作
// 触发分销分佣结算
DistributionService::settleOrder($order);
$affected = Db::name('fc_order')
->where('id', (int)$order['id'])
->where('status', 'pending')
->update(['status' => 'paid', 'paytime' => $now, 'updatetime' => $now]);
if (!$affected) {
return;
}
$locked['status'] = 'paid';
$locked['paytime'] = $now;
$handled = true;
// 按订单类型发货:member / recharge / payview / post(内部含分销结算)
OrderFulfill::handle($locked);
});
} catch (\Exception $e) {
} catch (\Throwable $e) {
// 事务已回滚(订单仍 pending)→ 返回 FAIL,微信重试后重放
$this->replyFail('订单处理失败:' . $e->getMessage());
\think\Log::record('微信支付回调处理失败:订单 ' . $orderNo . ',' . $e->getMessage(), 'error');
$this->replyFail('订单处理失败');
}
\think\Log::record('微信支付回调成功:订单 ' . $orderNo . ',实付 ' . $paidFee . ' 分', 'info');
@@ -299,14 +390,130 @@ class Pay extends V1
$this->reply($pay->success());
}
/**
* POST /api/v1/pay/transfer-notify 微信商家转账结果回调(公开路由,无需登录)
*
* 事件:MCHTRANSFER.BILL.FINISHED
* 处理:验签 → 解 resource.ciphertext → WxTransfer::applyResult()
* SUCCESS → 提现单置 paid;FAIL/CANCELLED → failed(可重新申请)
*/
public function transferNotify()
{
$json = function ($code, $message, $status) {
return new \Symfony\Component\HttpFoundation\Response(
json_encode(['code' => $code, 'message' => $message], JSON_UNESCAPED_UNICODE),
$status,
['Content-Type' => 'application/json']
);
};
if (!EpayService::isVersionV3()) {
// 商家转账只有 V3;非 V3 直接确认收到,避免无效重试
$this->reply($json('SUCCESS', '成功', 200));
}
try {
$pay = EpayService::checkNotify('wechat');
} catch (\Throwable $e) {
\think\Log::record('商家转账回调验签异常:' . $e->getMessage(), 'error');
$pay = false;
}
if (!$pay) {
$this->reply($json('FAIL', '签名验证失败', 500));
}
try {
$data = $pay->callback();
if (!isset($data['resource']['ciphertext'])) {
throw new \RuntimeException('回调报文缺少 resource.ciphertext');
}
$data = $data['resource']['ciphertext'];
} catch (\Throwable $e) {
\think\Log::record('商家转账回调解析失败:' . $e->getMessage(), 'error');
$this->reply($json('FAIL', '回调报文解析失败', 500));
}
$data = $data instanceof \Yansongda\Supports\Collection ? $data->all() : (array)$data;
try {
\app\common\library\WxTransfer::applyResult($data);
} catch (\Throwable $e) {
\think\Log::record('商家转账结果处理失败:' . $e->getMessage() . ' data=' . json_encode($data, JSON_UNESCAPED_UNICODE), 'error');
// 返回非 2xx,微信会重试
$this->reply($json('FAIL', '处理失败', 500));
}
$this->reply($pay->success());
}
/**
* POST /api/v1/pay/refund-notify 微信退款结果回调(公开路由)
*
* 事件:REFUND.SUCCESS / REFUND.ABNORMAL / REFUND.CLOSED
* 处理:正常退款成功只做幂等确认;异常/关闭把订单改回 paid,等待人工重试
*/
public function refundNotify()
{
$json = function ($code, $message, $status) {
return new \Symfony\Component\HttpFoundation\Response(
json_encode(['code' => $code, 'message' => $message], JSON_UNESCAPED_UNICODE),
$status,
['Content-Type' => 'application/json']
);
};
if (!EpayService::isVersionV3()) {
$this->reply($json('SUCCESS', '成功', 200));
}
try {
$pay = EpayService::checkNotify('wechat');
} catch (\Throwable $e) {
\think\Log::record('微信退款回调验签异常:' . $e->getMessage(), 'error');
$pay = false;
}
if (!$pay) {
$this->reply($json('FAIL', '签名验证失败', 500));
}
try {
$data = $pay->callback();
if (!isset($data['resource']['ciphertext'])) {
throw new \RuntimeException('回调报文缺少 resource.ciphertext');
}
$data = $data['resource']['ciphertext'];
} catch (\Throwable $e) {
\think\Log::record('微信退款回调解析失败:' . $e->getMessage(), 'error');
$this->reply($json('FAIL', '回调报文解析失败', 500));
}
$data = $data instanceof \Yansongda\Supports\Collection ? $data->all() : (array)$data;
try {
\app\common\library\OrderRefund::handleNotify($data);
} catch (\Throwable $e) {
\think\Log::record('微信退款结果处理失败:' . $e->getMessage(), 'error');
$this->reply($json('FAIL', '处理失败', 500));
}
$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');
$status = 200;
if ($response instanceof \Symfony\Component\HttpFoundation\Response) {
$body = (string)$response->getContent();
$status = $response->getStatusCode();
$type = (string)$response->headers->get('Content-Type');
} elseif ($response instanceof \Psr\Http\Message\ResponseInterface) {
$body = (string)$response->getBody();
$status = $response->getStatusCode();
$type = $response->getHeaderLine('Content-Type');
} elseif (is_object($response) && method_exists($response, 'getContent')) {
$body = (string)$response->getContent();
$type = 'application/xml; charset=utf-8';
@@ -316,12 +523,31 @@ class Pay extends V1
}
if (!headers_sent()) {
// 必须保留插件的状态码:V3 失败需返回非 2xx,微信才会重试
http_response_code($status);
header('Content-Type: ' . ($type !== '' ? $type : 'application/xml; charset=utf-8'));
}
echo $body;
exit;
}
/**
* 输出「已收到、无需处理」的成功应答(支付未成功 / 幂等命中 / 状态不符)
* V2 为 XML,V3 为 JSON(微信 V3 只校验 HTTP 状态码,但保持报文格式一致更稳妥)
*/
protected function replyOk()
{
if (EpayService::isVersionV3()) {
$this->reply(new \Symfony\Component\HttpFoundation\Response(
json_encode(['code' => 'SUCCESS', 'message' => '成功'], JSON_UNESCAPED_UNICODE),
200,
['Content-Type' => 'application/json']
));
}
$this->replyXml('SUCCESS', 'OK');
}
/** 输出 SUCCESS 应答(未配置 / 支付未成功 / 幂等命中) */
protected function replyXml($returnCode = 'SUCCESS', $returnMsg = 'OK')
{

查看文件

@@ -4,6 +4,7 @@ namespace app\api\controller;
use think\Db;
use app\common\library\DistributionService;
use app\common\library\CouponService;
/**
* 用户端 · 信息发布与详情(Module-POST)
@@ -113,11 +114,13 @@ class Post extends V1
/**
* P1 发布信息
* POST /api/v1/post/create
* 入参 {categoryId,title,content,media[],contact,phone,address,lat?,lng?,plan,payType}
* 入参 {categoryId,title,content,media[],contact,phone,address,areaId?,districtId?,area?,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,再随发布提交);
* - 服务区域为**区县**:优先取 `areaId`(=fc_area.id),兼容 `districtId` / `area` 名称;
* 都没传但带坐标时,按最近服务区域自动归属;均无则允许为空(兼容旧客户端);
* - `lat`/`lng` 可选(gcj02),由前端 chooseLocation 采集,用于首页「附近」排序;
* - 单条付费金额 = round(单条价格 × 会员折扣率, 2),折扣率取自 member.benefit.postDiscount
* (会员权益,非会员/解析失败视作 1);金额一律服务端计算,忽略客户端传值。
@@ -186,10 +189,6 @@ class Post extends V1
if ($amount > 0 && !in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
}
// 余额校验须在落库之前:否则余额不足时会残留一条 is_paid=1 的无效发布
if ($amount > 0 && $payType === 'balance' && (float)$user['money'] < $amount) {
$this->fail('余额不足');
}
} elseif ($quotaLeft > 0) {
$useQuota = true; // ① 套餐额度(开通月/年卡赠送,随会员有效期)
} elseif ($free['unlimited'] || $free['left'] > 0) {
@@ -204,87 +203,160 @@ class Post extends V1
}
$paid = $amount > 0;
$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(),
// 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 : '',
'audit_status' => 0,
'views' => 0,
'likes' => 0,
'comment_count' => 0,
'status' => 1,
'createtime' => $now,
'updatetime' => $now,
]);
$order = null;
if ($paid) {
// 余额支付为「即时支付」:下单即扣款、订单直接置为已支付;
// 微信支付需要前端调起收银台,保持 pending 由支付回调置为 paid。
$paidNow = $payType === 'balance';
$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' => $paidNow ? 'paid' : 'pending',
'paytime' => $paidNow ? $now : null,
'related_id' => $postId,
'createtime' => $now,
'updatetime' => $now,
]);
if ($paidNow) {
$balance = round((float)$user['money'] - $amount, 2);
Db::name('user')->where('id', $user['id'])->update([
'money' => $balance,
'updatetime' => $now,
]);
$this->flow('income', '发布付费', $amount, $balance, $postId);
// 余额支付发布付费:触发分销结算
$orderRow = Db::name('fc_order')->where('order_no', $orderNo)->find();
if ($orderRow) {
DistributionService::settleOrder($orderRow);
// 优惠券(仅单条付费发布可用)
$originAmount = $amount;
$couponAmount = 0;
$userCouponId = 0;
if ($paid && $plan === 'single') {
$userCouponId = (int)$this->input('userCouponId', 0);
if ($userCouponId > 0) {
try {
$couponInfo = CouponService::preview($user['id'], $userCouponId, $originAmount);
} catch (\Throwable $e) {
$this->fail($e->getMessage());
}
$couponAmount = $couponInfo['discount'];
$amount = round($originAmount - $couponAmount, 2);
}
$order = [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => $payType,
'status' => $paidNow ? 'paid' : 'pending',
];
}
// 套餐额度内免费发布:落库成功后扣减 1 条额度(先发布后扣,发布失败不白扣)
if ($useQuota) {
$quotaLeft = max(0, $quotaLeft - 1);
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'post_quota_left' => $quotaLeft,
'updatetime' => $now,
]);
// 余额校验须在落库之前(按抵扣后的实付金额判断)
if ($paid && $payType === 'balance' && (float)$user['money'] < $amount) {
$this->fail('余额不足');
}
// 区域:优先 districtId,其次 area 名称,最后按坐标匹配最近区县
$region = $this->resolveRegion();
// 封面:显式传 cover 优先;否则取媒体里的第一张图片
$cover = trim((string)$this->input('cover', ''));
if ($cover === '') {
foreach ($this->mediaArray() as $m) {
if (!preg_match('/\.(mp4|mov|m4v|avi|wmv|flv|m3u8)(\?|$)/i', $m)) {
$cover = $m;
break;
}
}
}
if ($cover !== '' && !preg_match('#^(/uploads/|https?://)#i', $cover)) {
$this->fail('封面地址不合法');
}
$now = time();
$postId = 0;
$order = null;
$balanceAfter = 0;
try {
// 发布落库 + 扣款 + 订单 + 额度扣减 同一事务:任一步失败整体回滚
Db::transaction(function () use (
&$postId, &$order, &$balanceAfter, &$quotaLeft,
$paid, $user, $amount, $originAmount, $couponAmount, $userCouponId, $payType,
$now, $categoryId, $title, $content, $phone, $useQuota, $region, $cover
) {
$paidNow = $paid && $payType === 'balance';
// 订单号提前生成:优惠券锁定需要绑定订单号
$orderNo = $paid ? $this->orderNo('PO') : '';
if ($userCouponId > 0) {
CouponService::lock($user['id'], $userCouponId, $originAmount, $orderNo);
}
// 余额扣减:条件更新,并发下不会扣成负数
if ($paidNow) {
$affected = Db::name('user')
->where('id', (int)$user['id'])
->where('money', '>=', $amount)
->setDec('money', $amount);
if (!$affected) {
throw new \RuntimeException('余额不足');
}
$balanceAfter = (float)Db::name('user')->where('id', (int)$user['id'])->value('money');
}
$postId = Db::name('fc_post')->insertGetId([
'user_id' => $user['id'],
'category_id' => $categoryId,
'title' => $title,
'content' => $content,
'cover' => $cover,
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'price' => round((float)$this->input('price', 0), 2),
'price_unit' => (string)$this->input('priceUnit', ''),
'area' => $region['area'],
'district_id' => $region['district_id'],
'address' => (string)$this->input('address', ''),
'contact' => (string)$this->input('contact', ''),
'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 : '',
'audit_status' => 0,
'views' => 0,
'likes' => 0,
'comment_count' => 0,
'status' => 1,
'createtime' => $now,
'updatetime' => $now,
]);
if ($paid) {
// 余额支付为「即时支付」:扣款 + 订单直接 paid;
// 微信支付保持 pending,由支付回调置为 paid 并发放权益。
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'post',
'title' => $title,
'amount' => $amount,
'origin_amount' => $originAmount,
'coupon_amount' => $couponAmount,
'coupon_id' => $userCouponId > 0 ? $userCouponId : 0,
'pay_type' => $payType,
'status' => $paidNow ? 'paid' : 'pending',
'paytime' => $paidNow ? $now : null,
'related_id' => $postId,
'createtime' => $now,
'updatetime' => $now,
]);
if ($paidNow) {
$this->flow('income', '发布付费', $amount, $balanceAfter, $postId);
// 余额支付:核销优惠券 + 触发分销结算
CouponService::markUsed($orderNo);
$orderRow = Db::name('fc_order')->where('order_no', $orderNo)->find();
if ($orderRow) {
DistributionService::settleOrder($orderRow);
}
}
$order = [
'orderNo' => $orderNo,
'amount' => $amount,
'originAmount' => $originAmount,
'couponAmount' => $couponAmount,
'payType' => $payType,
'status' => $paidNow ? 'paid' : 'pending',
];
}
// 套餐额度内免费发布:落库成功后扣减 1 条额度(先发布后扣,发布失败不白扣)
if ($useQuota) {
$quotaLeft = max(0, $quotaLeft - 1);
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'post_quota_left' => $quotaLeft,
'updatetime' => $now,
]);
}
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '发布失败,请重试');
}
$this->ok([
@@ -293,6 +365,8 @@ class Post extends V1
'order' => $order,
'plan' => $useQuota ? 'quota' : ($useFreeQuota ? 'free' : ($paid ? 'single' : 'free')),
'amount' => $amount,
'originAmount' => $originAmount,
'couponAmount' => $couponAmount,
// 本次生效的会员发布折扣率(非会员/未配置为 1)
'discountRate' => $discountRate,
'quotaLeft' => $quotaLeft,
@@ -349,6 +423,7 @@ class Post extends V1
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'address' => (string)$row['address'],
'auditStatus' => (int)$row['audit_status'],
'auditReason' => (string)$row['audit_reason'],
@@ -562,6 +637,8 @@ class Post extends V1
'contact' => (string)$row['contact'],
'phone' => (string)$row['phone'],
'address' => (string)$row['address'],
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'savedAt' => $this->iso($row['savedat']),
];
}
@@ -611,6 +688,8 @@ class Post extends V1
'contact' => (string)$this->input('contact', ''),
'phone' => (string)$this->input('phone', ''),
'address' => (string)$this->input('address', ''),
'area' => (string)$this->input('area', ''),
'district_id' => (int)$this->input('areaId', (int)$this->input('districtId', 0)),
'savedat' => $now,
'updatetime' => $now,
];
@@ -683,10 +762,112 @@ class Post extends V1
$this->fail('信息不存在', 404);
}
Db::name('fc_post')->where('id', $id)->setInc('views');
$post['views'] = (int)$post['views'] + 1;
// accessOnly=1:仅回读解锁态(如从会员中心返回时刷新),不计浏览量
if (!$this->input('accessOnly', false)) {
Db::name('fc_post')->where('id', $id)->setInc('views');
$post['views'] = (int)$post['views'] + 1;
}
$this->ok($this->buildPost($post));
$this->ok($this->contactAccess($this->buildPost($post), $post));
}
/**
* 详情页联系方式可见性(避免「已开通会员仍显示已受保护」)
*
* 可见规则(与 payView 计费口径一致):
* ① 会员有效期内 → 免费看
* ② 已付费解锁 fc_pay_view → 看(余额 / 微信回调写入)
* ③ 本人发布的信息 → 看
* 其它(游客 / 非会员未付费)→ 仍返回脱敏串
*
* 出参新增:unlocked(bool)、wechat(明文,未解锁为空串)。
* 注意:只加在详情接口,列表(首页/收藏等)仍保持脱敏,避免手机号被批量抓取。
*
* @param array $data buildPost() 结果
* @param array $post fc_post 行
* @return array
*/
protected function contactAccess($data, $post)
{
$data['unlocked'] = false;
$data['wechat'] = '';
$me = $this->user();
if (!$me) {
return $data;
}
$now = time();
$ext = $this->ext($me['id']);
$isMember = (int)$ext['is_member'] === 1
&& (empty($ext['member_expiretime']) || (int)$ext['member_expiretime'] > $now);
$isOwner = (int)$post['user_id'] === (int)$me['id'];
$paid = (bool)Db::name('fc_pay_view')
->where('user_id', $me['id'])
->where('post_id', $post['id'])
->find();
// 会员每日免费查看剩余次数(只做展示;解锁统一走 payView,按额度/付费计费)
$quota = $this->memberFreeViewQuota();
$today = date('Y-m-d');
$used = ((string)$ext['free_view_date'] === $today) ? (int)$ext['free_view_used'] : 0;
$data['freeViewLeft'] = $isMember ? max(0, $quota - $used) : 0;
if ($isOwner || $paid) {
$data['unlocked'] = true;
$data['contact'] = (string)$post['phone'];
$data['wechat'] = $post['wechat'] !== '' ? (string)$post['wechat'] : ('tongcheng_' . $post['id']);
}
return $data;
}
/**
* 会员每日免费查看条数(member.benefit.freeView,默认 20)
*
* @return int
*/
protected function memberFreeViewQuota()
{
$cfg = $this->cfg('member.benefit', []);
if (is_array($cfg) && isset($cfg['freeView'])) {
return max(0, (int)$cfg['freeView']);
}
return 20;
}
/**
* 消耗一次会员免费查看额度(跨天自动重置;需在事务内调用)
*
* @param int $userId
* @param int $quota
* @return bool 是否成功占用
*/
protected function consumeFreeView($userId, $quota)
{
$today = date('Y-m-d');
$ext = Db::name('fc_user_ext')->where('user_id', (int)$userId)->lock(true)->find();
if (!$ext) {
return false;
}
if ((string)$ext['free_view_date'] !== $today) {
Db::name('fc_user_ext')->where('user_id', (int)$userId)->update([
'free_view_date' => $today,
'free_view_used' => 1,
'updatetime' => time(),
]);
return true;
}
if ((int)$ext['free_view_used'] >= $quota) {
return false;
}
Db::name('fc_user_ext')->where('user_id', (int)$userId)->setInc('free_view_used', 1);
return true;
}
/**
@@ -733,59 +914,72 @@ class Post extends V1
$ext = $this->ext($user['id']);
$isMember = (int)$ext['is_member'] === 1
&& (!$ext['member_expiretime'] || $ext['member_expiretime'] > $now);
$quota = $this->memberFreeViewQuota();
$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 {
// 微信支付:只落 pending 订单(不预写解锁记录),
// 支付成功后由 /pay/notify 按 type=payview + related_id 解锁(回调可独立完成)
$orderNo = $this->orderNo('VO');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'payview',
'title' => '付费查看 #' . $id,
'amount' => $amount,
'pay_type' => 'wxpay',
'status' => 'pending',
'paytime' => null,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
$pending = null;
$this->ok([
'order' => [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => 'wxpay',
'status' => 'pending',
],
]);
try {
Db::transaction(function () use (&$orderId, &$pending, $isMember, $quota, $payType, $amount, $user, $id, $now) {
// 会员每日免费查看额度(当天用完后按正常付费)
$usedFree = ($isMember && $quota > 0) ? $this->consumeFreeView((int)$user['id'], $quota) : false;
if ($usedFree) {
$amount = 0;
$payType = 'free';
} elseif ($payType === 'balance') {
// 条件扣款:并发下不会扣成负数
$affected = Db::name('user')
->where('id', (int)$user['id'])
->where('money', '>=', $amount)
->setDec('money', $amount);
if (!$affected) {
throw new \RuntimeException('余额不足');
}
$balance = (float)Db::name('user')->where('id', (int)$user['id'])->value('money');
$this->flow('expense', '付费查看', $amount, $balance, $id);
} else {
// 微信支付:只落 pending 订单(不预写解锁记录),
// 支付成功后由 /pay/notify 按 type=payview + related_id 解锁(回调可独立完成)
$orderNo = $this->orderNo('VO');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'payview',
'title' => '付费查看 #' . $id,
'amount' => $amount,
'pay_type' => 'wxpay',
'status' => 'pending',
'paytime' => null,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
$pending = [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => 'wxpay',
'status' => 'pending',
];
return;
}
Db::name('fc_pay_view')->insert([
'user_id' => $user['id'],
'post_id' => $id,
'pay_type' => $payType,
'amount' => $amount,
'order_id' => $orderId,
'createtime' => $now,
]);
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '解锁失败,请重试');
}
Db::name('fc_pay_view')->insert([
'user_id' => $user['id'],
'post_id' => $id,
'pay_type' => $payType,
'amount' => $amount,
'order_id' => $orderId,
'createtime' => $now,
]);
if ($pending !== null) {
$this->ok(['order' => $pending]);
}
$this->ok(['unlocked' => true, 'contact' => $contact]);
}
@@ -936,6 +1130,66 @@ class Post extends V1
return $val;
}
/**
* 解析发布信息的服务区域(区县)
* 优先级:areaId(兼容 districtId)> area 名称 > 经纬度最近区域(300km 内)。
* 未提供任何区域时返回空区域,保持与旧客户端兼容。
* @return array{area:string,district_id:int}
*/
protected function resolveRegion()
{
$areaId = (int)$this->input('areaId', 0);
if (!$areaId) {
$areaId = (int)$this->input('districtId', 0);
}
$areaName = trim((string)$this->input('area', ''));
$area = null;
if ($areaId > 0) {
$area = Db::name('fc_area')
->where('id', $areaId)
->where('enabled', 1)
->find();
if (!$area) {
$this->fail('所选服务区域不可用,请重新选择');
}
} elseif ($areaName !== '') {
$area = Db::name('fc_area')
->where('district', $areaName)
->where('enabled', 1)
->find();
} else {
$lat = $this->coord('lat', 90);
$lng = $this->coord('lng', 180);
if ($lat !== null && $lng !== null) {
$rows = Db::name('fc_area')
->where('enabled', 1)
->whereNotNull('lat')
->whereNotNull('lng')
->select();
$best = null;
foreach ($rows as $row) {
$distance = $this->haversine($lat, $lng, (float)$row['lat'], (float)$row['lng']);
if ($best === null || $distance < $best['distance']) {
$best = ['row' => $row, 'distance' => $distance];
}
}
if ($best && $best['distance'] <= 300) {
$area = $best['row'];
}
}
}
if (!$area) {
return ['area' => $areaName, 'district_id' => 0];
}
return [
'area' => (string)$area['district'],
'district_id' => (int)$area['id'],
];
}
/**
* 会员发布折扣率
* 取自 member.benefit.postDiscount(如 '8 折'→0.8、'9.5折'→0.95、'八折' 视为解析失败→1);
@@ -1123,6 +1377,7 @@ class Post extends V1
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'address' => (string)$row['address'],
'contact' => $this->maskPhone($row['phone']),
'views' => (int)$row['views'],

查看文件

@@ -23,10 +23,29 @@ class Setting extends V1
$icons = [];
}
// 名称 / LOGO 以 base.* 为准,旧 ui.* 仅作兼容回落;
// 客服电话、关于我们、分享标题统一从 base.* 下发,避免后台配置了端上不生效。
$baseName = trim((string)$this->cfg('base.appName', ''));
$siteName = $baseName !== '' ? $baseName : (string)$this->cfg('ui.siteName', '同城分类信息');
$baseLogo = (string)$this->cfg('base.logo', '');
$logo = $baseLogo !== '' ? $baseLogo : (string)$this->cfg('ui.logo', '');
$shareTitle = trim((string)$this->cfg('base.shareTitle', ''));
$this->ok([
'siteName' => (string)$this->cfg('ui.siteName', '同城分类信息'),
'logo' => (string)$this->cfg('ui.logo', ''),
'icons' => (object)$icons,
'appName' => $siteName,
'siteName' => $siteName,
'logo' => $logo,
'servicePhone' => (string)$this->cfg('base.servicePhone', ''),
'aboutUs' => (string)$this->cfg('base.aboutUs', ''),
'shareTitle' => $shareTitle !== '' ? $shareTitle : $siteName,
'icons' => (object)$icons,
// 订阅消息模板(客户端 requestSubscribeMessage 用;未配置时为空串)
'subscribe' => [
'audit' => (string)$this->cfg('wx.tplAudit', ''),
'transfer' => (string)$this->cfg('wx.tplTransfer', ''),
],
]);
}

查看文件

@@ -87,7 +87,12 @@ class V1 extends Api
$this->resolved = true;
$token = $this->bearerToken();
if (!$token && !($token = $this->request->request('token'))) {
// 不再接受 ?token= 传参(避免令牌进入访问日志/Referer),仅认 Authorization: Bearer
if (!$token) {
return $this->user = null;
}
// 刷新令牌(rf_ 前缀)不能作为访问令牌使用
if (strpos($token, 'rf_') === 0) {
return $this->user = null;
}
@@ -115,6 +120,35 @@ class V1 extends Api
return $user;
}
/**
* 后台管理接口鉴权(/api/v1/admin/** 专用)
*
* 背景:V1 基类对所有动作关闭了 FastAdmin 的 URI 权限校验($noNeedLogin = ['*']),
* 因此管理端接口必须显式校验调用者身份,否则任何人可读写后台数据。
*
* 放行规则(满足其一即可):
* 1. 用户 ID 在 fc_config 的 admin.userIds 白名单内(逗号分隔);
* 2. 用户手机号在 fc_config 的 admin.mobiles 白名单内(逗号分隔)。
*
* @return \app\common\model\User
*/
protected function adminOnly()
{
$user = $this->auth();
$ids = array_filter(array_map('intval', preg_split('/[,,\s]+/', (string)$this->cfg('admin.userIds', ''))));
if ($ids && in_array((int)$user['id'], $ids, true)) {
return $user;
}
$mobiles = array_filter(array_map('trim', preg_split('/[,,\s]+/', (string)$this->cfg('admin.mobiles', ''))));
if ($mobiles && in_array((string)$user['mobile'], $mobiles, true)) {
return $user;
}
$this->fail('无权访问管理接口', 403, 403);
}
/** 当前用户 ID */
protected function userId()
{
@@ -124,7 +158,7 @@ class V1 extends Api
/** 签发 token 并写入 fa_user_token */
protected function issueToken($userId, $days = 30)
{
$token = md5(mt_rand() . $userId . microtime(true) . uniqid('', true));
$token = bin2hex(random_bytes(20));
Db::name('user_token')->insert([
'token' => $token,
'user_id' => $userId,
@@ -134,6 +168,48 @@ class V1 extends Api
return $token;
}
/**
* 签发刷新令牌(rf_ 前缀,40 天)
* 与访问令牌同表存储,但鉴权时会被拒绝(见 user()),只能用于 /auth/refresh 换新令牌
*
* 长度约束:fa_user_token.token 为 varchar(50),故取 20 字节随机(40 hex)+ 3 位前缀 = 43
*/
protected function issueRefreshToken($userId, $days = 40)
{
$refresh = 'rf_' . bin2hex(random_bytes(20));
Db::name('user_token')->insert([
'token' => $refresh,
'user_id' => $userId,
'createtime' => time(),
'expiretime' => time() + $days * 86400,
]);
return $refresh;
}
/**
* 简单频率限制(文件缓存计数)
*
* @param string $key 维度键(如 login:手机号、withdraw:用户ID)
* @param int $max 窗口内最大次数
* @param int $window 窗口秒数
* @return void
*/
protected function rateLimit($key, $max, $window)
{
$cacheKey = 'rl:' . md5($key);
$now = time();
$data = cache($cacheKey);
if (!is_array($data) || empty($data['reset']) || $data['reset'] <= $now) {
$data = ['count' => 0, 'reset' => $now + $window];
}
$data['count']++;
cache($cacheKey, $data, $window);
if ($data['count'] > $max) {
$this->fail('操作过于频繁,请稍后再试', 429, 429);
}
}
/* ==================== 入参 ==================== */
/**
@@ -283,7 +359,11 @@ class V1 extends Api
]);
}
if (self::$cfgCache === null) {
// 首次写入时先载入全量配置,避免后续读取其他 key 时命中空缓存而返回默认值
self::$cfgCache = [];
foreach (Db::name('fc_config')->select() as $row) {
self::$cfgCache[$row['key']] = $row['value'];
}
}
self::$cfgCache[$key] = $val;
return true;
@@ -310,10 +390,10 @@ class V1 extends Api
return strlen($phone) === 11 ? substr($phone, 0, 3) . '****' . substr($phone, 7) : $phone;
}
/** 生成业务单号 */
/** 生成业务单号(前缀 + 时间 + 8 位随机十六进制,避免同秒并发碰撞) */
protected function orderNo($prefix)
{
return $prefix . date('YmdHis') . mt_rand(1000, 9999);
return $prefix . date('YmdHis') . bin2hex(random_bytes(4));
}
/* ==================== 业务公共 ==================== */
@@ -364,6 +444,7 @@ class V1 extends Api
'memberExpireAt' => $ext['member_expiretime'] ? $this->iso($ext['member_expiretime']) : null,
'balance' => (float)$user['money'],
'realnameStatus' => (int)$ext['realname_status'],
'realname' => isset($ext['realname']) ? (string)$ext['realname'] : '',
'isMerchant' => (bool)$isMerchant,
'merchantStatus' => $merchantStatus,
'merchant' => $merchant ? [
@@ -400,7 +481,7 @@ class V1 extends Api
static $seq = 0;
$seq++;
Db::name('fc_finance_flow')->insert([
'flow_no' => 'F' . date('YmdHis') . mt_rand(100, 999) . $seq,
'flow_no' => 'F' . date('YmdHis') . bin2hex(random_bytes(4)) . $seq,
'type' => $type,
'scene' => $scene,
'amount' => $amount,