feat: 新增地址选择插件及订阅消息等多项功能优化
- 新增地址选择插件,支持地图位置选择并返回地址和经纬度 - 新增微信订阅消息发送功能,支持审核结果、提现通知等场景 - 新增订单支付状态查询、提现收款人姓名保存等接口 - 新增服务区域管理,支持按省市区划分并同步到信息发布 - 新增资金流水和营收报表导出功能 - 新增可用优惠券查询、订单退款拆分处理等功能 - 优化后台角标显示、首页数据统计、UI配置下发等 - 修复订单支付并发问题、地区管理逻辑等
这个提交包含在:
@@ -50,7 +50,7 @@ class FcAssets
|
||||
|
||||
/**
|
||||
* 后台静态资源指纹(纯数字串)
|
||||
* 覆盖范围:后台语言包(文案来源)+ 后台模块 JS(表格列、枚举 formatter 等)
|
||||
* 覆盖范围:后台语言包(文案来源)+ 后台模块 JS(表格列、枚举 formatter 等)+ 后台主题 CSS
|
||||
* @return string
|
||||
*/
|
||||
protected static function fingerprint()
|
||||
@@ -63,6 +63,7 @@ class FcAssets
|
||||
$dirs = [
|
||||
APP_PATH . 'admin' . DS . 'lang' . DS . 'zh-cn',
|
||||
ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend',
|
||||
ROOT_PATH . 'public' . DS . 'assets' . DS . 'css',
|
||||
];
|
||||
|
||||
$mtime = 0;
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 优惠券抵扣(下单锁定 → 支付成功核销 → 退款/关闭退回)
|
||||
*
|
||||
* 券类型(fc_coupon.type):
|
||||
* fixed 满减券:amount = 抵扣金额(元)
|
||||
* discount 折扣券:amount = 折扣数(如 8.50 表示 8.5 折)
|
||||
*
|
||||
* 状态(fc_user_coupon.status):
|
||||
* unused 未使用 · locked 已锁定(下单未支付)· used 已使用 · expired 已过期
|
||||
*
|
||||
* 规则:
|
||||
* - 支付金额最低 0.01 元(抵扣后不会为 0);
|
||||
* - 满减券抵扣不超过订单金额 - 0.01;
|
||||
* - 锁定时使用条件更新,避免同一张券被并发使用。
|
||||
*/
|
||||
class CouponService
|
||||
{
|
||||
/**
|
||||
* 计算券对指定金额的抵扣
|
||||
*
|
||||
* @param int $userId
|
||||
* @param int $userCouponId fc_user_coupon.id
|
||||
* @param float $amount 优惠前金额(元)
|
||||
* @return array{discount:float,payable:float,userCouponId:int,couponId:int,name:string}
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function preview($userId, $userCouponId, $amount)
|
||||
{
|
||||
$amount = round((float)$amount, 2);
|
||||
$userCouponId = (int)$userCouponId;
|
||||
if ($userCouponId <= 0) {
|
||||
throw new \RuntimeException('请选择优惠券');
|
||||
}
|
||||
|
||||
$uc = Db::name('fc_user_coupon')->where('id', $userCouponId)->where('user_id', (int)$userId)->find();
|
||||
if (!$uc) {
|
||||
throw new \RuntimeException('优惠券不存在');
|
||||
}
|
||||
if ((string)$uc['status'] !== 'unused') {
|
||||
throw new \RuntimeException('优惠券已使用或已失效');
|
||||
}
|
||||
if (!empty($uc['expiretime']) && (int)$uc['expiretime'] < time()) {
|
||||
throw new \RuntimeException('优惠券已过期');
|
||||
}
|
||||
|
||||
$coupon = Db::name('fc_coupon')->where('id', (int)$uc['coupon_id'])->find();
|
||||
if (!$coupon || (int)$coupon['enabled'] !== 1) {
|
||||
throw new \RuntimeException('优惠券已停用');
|
||||
}
|
||||
|
||||
$min = round((float)$coupon['min_amount'], 2);
|
||||
if ($min > 0 && $amount < $min) {
|
||||
throw new \RuntimeException('订单金额未满 ' . $min . ' 元,无法使用该券');
|
||||
}
|
||||
|
||||
$discount = self::calcDiscount($coupon, $amount);
|
||||
if ($discount <= 0) {
|
||||
throw new \RuntimeException('该优惠券不可用');
|
||||
}
|
||||
|
||||
return [
|
||||
'discount' => $discount,
|
||||
'payable' => round($amount - $discount, 2),
|
||||
'userCouponId' => $userCouponId,
|
||||
'couponId' => (int)$coupon['id'],
|
||||
'name' => (string)$coupon['name'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 下单锁券(必须在创建订单的同一事务内调用)
|
||||
*
|
||||
* @param int $userId
|
||||
* @param int $userCouponId
|
||||
* @param float $amount
|
||||
* @param string $orderNo
|
||||
* @return array 同 preview()
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function lock($userId, $userCouponId, $amount, $orderNo)
|
||||
{
|
||||
$info = self::preview($userId, $userCouponId, $amount);
|
||||
|
||||
$affected = Db::name('fc_user_coupon')
|
||||
->where('id', (int)$userCouponId)
|
||||
->where('user_id', (int)$userId)
|
||||
->where('status', 'unused')
|
||||
->update([
|
||||
'status' => 'locked',
|
||||
'order_no' => (string)$orderNo,
|
||||
]);
|
||||
if (!$affected) {
|
||||
throw new \RuntimeException('优惠券已被使用,请重新选择');
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付成功核销(幂等:只处理 locked)
|
||||
*
|
||||
* @param string $orderNo
|
||||
* @return void
|
||||
*/
|
||||
public static function markUsed($orderNo)
|
||||
{
|
||||
if ((string)$orderNo === '') {
|
||||
return;
|
||||
}
|
||||
Db::name('fc_user_coupon')
|
||||
->where('order_no', (string)$orderNo)
|
||||
->where('status', 'locked')
|
||||
->update([
|
||||
'status' => 'used',
|
||||
'usetime' => time(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 退回优惠券(订单关闭 / 退款)
|
||||
*
|
||||
* @param string $orderNo
|
||||
* @return void
|
||||
*/
|
||||
public static function release($orderNo)
|
||||
{
|
||||
if ((string)$orderNo === '') {
|
||||
return;
|
||||
}
|
||||
Db::name('fc_user_coupon')
|
||||
->where('order_no', (string)$orderNo)
|
||||
->where('status', 'in', ['locked', 'used'])
|
||||
->update([
|
||||
'status' => 'unused',
|
||||
'order_no' => '',
|
||||
'usetime' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 抵扣金额计算
|
||||
*
|
||||
* @param array $coupon
|
||||
* @param float $amount
|
||||
* @return float
|
||||
*/
|
||||
protected static function calcDiscount(array $coupon, $amount)
|
||||
{
|
||||
$type = (string)$coupon['type'];
|
||||
$value = round((float)$coupon['amount'], 2);
|
||||
|
||||
if ($type === 'discount') {
|
||||
// amount = 折扣数(8.5 表示 8.5 折),折扣率 = amount / 10
|
||||
$rate = $value / 10;
|
||||
if ($rate <= 0 || $rate >= 1) {
|
||||
return 0;
|
||||
}
|
||||
$discount = round($amount * (1 - $rate), 2);
|
||||
} else {
|
||||
// 满减
|
||||
$discount = $value;
|
||||
}
|
||||
|
||||
// 抵扣后至少支付 0.01 元
|
||||
$maxDiscount = round($amount - 0.01, 2);
|
||||
if ($discount > $maxDiscount) {
|
||||
$discount = max(0, $maxDiscount);
|
||||
}
|
||||
|
||||
return round($discount, 2);
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,7 @@ class DistributionService
|
||||
$maxLevel = (int)self::getConfig('dist.level', 2);
|
||||
$rate1 = (float)self::getConfig('dist.level1Rate', 20); // 默认 20%
|
||||
$rate2 = (float)self::getConfig('dist.level2Rate', 10); // 默认 10%
|
||||
$settleDays = self::settleDays();
|
||||
|
||||
// 查询该付款用户的所有上级推广员(按层级正序)
|
||||
$relations = Db::name('fc_dist_relation')
|
||||
@@ -168,7 +169,7 @@ class DistributionService
|
||||
continue;
|
||||
}
|
||||
|
||||
// 写入分销佣金明细表(status=1 已结算)
|
||||
// 写入分销佣金明细表(结算周期内为「未结算」,到期由 fc:settle 置为已结算)
|
||||
$commId = Db::name('fc_commission')->insertGetId([
|
||||
'user_id' => $parentId,
|
||||
'from_user_id' => $payerId,
|
||||
@@ -178,8 +179,9 @@ class DistributionService
|
||||
'amount' => $commissionAmount,
|
||||
'rate' => $rate,
|
||||
'level' => $level,
|
||||
'status' => 1,
|
||||
'settletime' => $now,
|
||||
'status' => $settleDays > 0 ? 0 : 1,
|
||||
'settle_due' => $now + $settleDays * 86400,
|
||||
'settletime' => $settleDays > 0 ? null : $now,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
|
||||
@@ -206,6 +208,21 @@ class DistributionService
|
||||
return $settledList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 结算周期天数:解析 dist.settleCycle(T+7 / T+1 / T+0),默认 7 天
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function settleDays()
|
||||
{
|
||||
$cycle = (string)self::getConfig('dist.settleCycle', 'T+7');
|
||||
if (preg_match('/T\s*\+\s*(\d+)/i', $cycle, $m)) {
|
||||
return max(0, (int)$m[1]);
|
||||
}
|
||||
|
||||
return 7;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取业务配置项
|
||||
*
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 业务配置分组(系统配置页扩展)
|
||||
*
|
||||
* 背景:
|
||||
* - 小程序、发布、分销三组配置的真源是 fa_fc_config,供小程序接口 / 分销服务直接读取;
|
||||
* - FastAdmin 的「系统设置 → 系统配置」页面按 fa_config 分组渲染,原本无法展示 fc_config;
|
||||
* - 本类把三组配置以「虚拟分组」的形式并入系统配置页,复用同一套表单与保存逻辑,
|
||||
* 值仍写入 fa_fc_config,不复制、不双写。
|
||||
*
|
||||
* 命名约定:表单字段统一以 fc_ 前缀,保存时映射回 fc_config 的原始 key。
|
||||
*/
|
||||
class FcConfig
|
||||
{
|
||||
/**
|
||||
* 系统配置页的业务分组
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function groups()
|
||||
{
|
||||
$cfg = self::values();
|
||||
$pick = function ($key, $default = '') use ($cfg) {
|
||||
return (isset($cfg[$key]) && $cfg[$key] !== '') ? $cfg[$key] : $default;
|
||||
};
|
||||
|
||||
return [
|
||||
'fc_miniapp' => [
|
||||
'name' => 'fc_miniapp',
|
||||
'title' => '小程序配置',
|
||||
'active' => false,
|
||||
'list' => [
|
||||
self::item('fc_base_appName', '小程序名称', 'string', $pick('base.appName', ''), '显示在小程序首页与分享卡片', 'required'),
|
||||
self::item('fc_base_logo', '小程序LOGO', 'image', $pick('base.logo', ''), '留空时使用默认 LOGO'),
|
||||
self::item('fc_base_servicePhone', '客服电话', 'string', $pick('base.servicePhone', ''), '展示在小程序「联系客服」入口'),
|
||||
self::item('fc_base_shareTitle', '分享标题', 'string', $pick('base.shareTitle', ''), '留空则默认使用小程序名称'),
|
||||
self::item('fc_base_aboutUs', '关于我们', 'text', $pick('base.aboutUs', ''), '展示在小程序「关于我们」页面'),
|
||||
self::item('fc_wx_appid', '小程序 AppID', 'string', $pick('wx.appid', ''), '微信公众平台 → 开发管理 → 开发设置 → AppID(微信登录用)'),
|
||||
self::item('fc_wx_secret', 'AppSecret', 'password', '', '仅服务端保存与调用;已配置时留空表示不修改(微信登录用)'),
|
||||
self::item('fc_wx_tplAudit', '审核结果模板 ID', 'string', $pick('wx.tplAudit', ''), '小程序订阅消息:审核结果通知(公众平台 → 订阅消息)'),
|
||||
self::item('fc_wx_tplTransfer', '提现到账模板 ID', 'string', $pick('wx.tplTransfer', ''), '小程序订阅消息:提现到账通知'),
|
||||
self::item('fc_admin_userIds', '后台接口管理员 ID', 'string', $pick('admin.userIds', ''), '允许调用 /api/v1/admin/** 的用户 ID,多个用逗号分隔(留空 = 全部禁止)'),
|
||||
self::item('fc_admin_mobiles', '后台接口管理员手机号', 'string', $pick('admin.mobiles', ''), '允许调用管理接口的手机号,多个用逗号分隔'),
|
||||
],
|
||||
],
|
||||
'fc_publish' => [
|
||||
'name' => 'fc_publish',
|
||||
'title' => '发布配置',
|
||||
'active' => false,
|
||||
'list' => [
|
||||
self::item('fc_post_mode', '发布模式', 'radio', $pick('post.mode', 'free'), '免费发布不收费;付费发布按价格计费', 'required', [
|
||||
'free' => '免费发布',
|
||||
'paid' => '付费发布',
|
||||
]),
|
||||
self::item('fc_post_freeQuota', '免费条数', 'number', $pick('post.freeQuota', '0'), '付费模式下免费发布的条数,0 = 不限制', 'required;number'),
|
||||
self::item('fc_post_freeQuotaCycle', '统计周期', 'select', $pick('post.freeQuotaCycle', 'day'), '免费条数的统计周期', 'required', [
|
||||
'day' => '每日',
|
||||
'month' => '每月',
|
||||
'total' => '累计',
|
||||
]),
|
||||
self::item('fc_post_singlePrice', '单条价格', 'number', $pick('post.singlePrice', '5'), '未开通套餐时的单条发布价格(元)', 'required;number'),
|
||||
self::item('fc_post_monthPrice', '月卡价格', 'number', $pick('post.monthPrice', '19.9'), '会员月卡价格(元),保存后同步会员套餐', 'required;number'),
|
||||
self::item('fc_post_monthQuota', '月卡条数', 'number', $pick('post.monthQuota', '30'), '月卡包含的发布条数', 'required;number'),
|
||||
self::item('fc_post_yearPrice', '年卡价格', 'number', $pick('post.yearPrice', '168'), '会员年卡价格(元),保存后同步会员套餐', 'required;number'),
|
||||
self::item('fc_post_yearQuota', '年卡条数', 'number', $pick('post.yearQuota', '500'), '年卡包含的发布条数', 'required;number'),
|
||||
],
|
||||
],
|
||||
'fc_dist' => [
|
||||
'name' => 'fc_dist',
|
||||
'title' => '分销配置',
|
||||
'active' => false,
|
||||
'list' => [
|
||||
self::item('fc_dist_enabled', '开启分销', 'switch', $pick('dist.enabled', '1'), '关闭后不再产生新的分销佣金'),
|
||||
self::item('fc_dist_level', '分佣层级', 'select', $pick('dist.level', '2'), '最多计算到第几级上级', 'required', [
|
||||
'1' => '一级',
|
||||
'2' => '二级',
|
||||
]),
|
||||
self::item('fc_dist_level1Rate', '一级比例', 'number', $pick('dist.level1Rate', '20'), '一级上级分佣比例(%)', 'required;number'),
|
||||
self::item('fc_dist_level2Rate', '二级比例', 'number', $pick('dist.level2Rate', '10'), '二级上级分佣比例(%)', 'required;number'),
|
||||
self::item('fc_dist_settleCycle', '结算周期', 'string', $pick('dist.settleCycle', 'T+7'), '如 T+7,展示给分销员'),
|
||||
self::item('fc_dist_minWithdraw', '最低提现', 'number', $pick('dist.minWithdraw', '50'), '最低提现金额(元)', 'required;number'),
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存业务配置(由系统配置页提交)
|
||||
*
|
||||
* @param array $row 系统配置页提交的 row 数组
|
||||
* @return void
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function save(array $row)
|
||||
{
|
||||
$has = function ($prefix) use ($row) {
|
||||
foreach ($row as $key => $value) {
|
||||
if (strpos($key, $prefix) === 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
if ($has('fc_base_')) {
|
||||
self::saveBase($row);
|
||||
}
|
||||
if ($has('fc_post_')) {
|
||||
self::savePublish($row);
|
||||
}
|
||||
if ($has('fc_dist_')) {
|
||||
self::saveDistribution($row);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序基础信息
|
||||
*
|
||||
* @param array $row
|
||||
* @return void
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected static function saveBase(array $row)
|
||||
{
|
||||
$appName = isset($row['fc_base_appName']) ? trim((string)$row['fc_base_appName']) : '';
|
||||
if ($appName === '') {
|
||||
throw new \Exception('小程序名称不能为空');
|
||||
}
|
||||
|
||||
$values = [
|
||||
'base.appName' => $appName,
|
||||
'base.logo' => isset($row['fc_base_logo']) ? trim((string)$row['fc_base_logo']) : '',
|
||||
'base.servicePhone' => isset($row['fc_base_servicePhone']) ? trim((string)$row['fc_base_servicePhone']) : '',
|
||||
'base.shareTitle' => isset($row['fc_base_shareTitle']) ? trim((string)$row['fc_base_shareTitle']) : '',
|
||||
'base.aboutUs' => isset($row['fc_base_aboutUs']) ? trim((string)$row['fc_base_aboutUs']) : '',
|
||||
];
|
||||
foreach ($values as $key => $value) {
|
||||
self::put($key, $value, 'base', '小程序配置');
|
||||
}
|
||||
|
||||
// 兼容旧 ui.* 键:名称/LOGO 同步一份,避免旧数据在用户端回落时“复活”
|
||||
self::put('ui.siteName', $appName, 'ui', '站点名称');
|
||||
self::put('ui.logo', $values['base.logo'], 'ui', '自定义LOGO');
|
||||
|
||||
// 微信登录参数(真源同为 fa_fc_config,由 WxMini 读取):
|
||||
// AppSecret 不回显、留空表示不修改,避免表单提交把已保存的密钥冲成空串
|
||||
$wxAppid = isset($row['fc_wx_appid']) ? trim((string)$row['fc_wx_appid']) : '';
|
||||
if ($wxAppid !== '') {
|
||||
self::put('wx.appid', $wxAppid, 'wx', '小程序AppID(微信登录用)');
|
||||
}
|
||||
$wxSecret = isset($row['fc_wx_secret']) ? trim((string)$row['fc_wx_secret']) : '';
|
||||
if ($wxSecret !== '') {
|
||||
self::put('wx.secret', $wxSecret, 'wx', '小程序AppSecret(仅服务端持有,不下发前端)');
|
||||
}
|
||||
|
||||
// 管理接口白名单(/api/v1/admin/**):留空表示不允许任何小程序端账号调用
|
||||
if (array_key_exists('fc_admin_userIds', $row)) {
|
||||
self::put('admin.userIds', trim((string)$row['fc_admin_userIds']), 'admin', '管理接口允许的用户ID(逗号分隔)');
|
||||
}
|
||||
if (array_key_exists('fc_admin_mobiles', $row)) {
|
||||
self::put('admin.mobiles', trim((string)$row['fc_admin_mobiles']), 'admin', '管理接口允许的手机号(逗号分隔)');
|
||||
}
|
||||
|
||||
// 订阅消息模板 ID
|
||||
if (array_key_exists('fc_wx_tplAudit', $row)) {
|
||||
self::put('wx.tplAudit', trim((string)$row['fc_wx_tplAudit']), 'wx', '审核结果订阅消息模板ID');
|
||||
}
|
||||
if (array_key_exists('fc_wx_tplTransfer', $row)) {
|
||||
self::put('wx.tplTransfer', trim((string)$row['fc_wx_tplTransfer']), 'wx', '提现到账订阅消息模板ID');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布模式与价格(同时同步会员套餐 M1/M12)
|
||||
*
|
||||
* @param array $row
|
||||
* @return void
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected static function savePublish(array $row)
|
||||
{
|
||||
$mode = isset($row['fc_post_mode']) ? trim((string)$row['fc_post_mode']) : 'free';
|
||||
if (!in_array($mode, ['free', 'paid'], true)) {
|
||||
throw new \Exception('发布模式只支持「免费发布」或「付费发布」');
|
||||
}
|
||||
|
||||
$cycle = isset($row['fc_post_freeQuotaCycle']) ? trim((string)$row['fc_post_freeQuotaCycle']) : 'day';
|
||||
if (!in_array($cycle, ['day', 'month', 'total'], true)) {
|
||||
throw new \Exception('免费条数统计周期只支持「每日 / 每月 / 累计」');
|
||||
}
|
||||
|
||||
$num = function ($key, $default) use ($row) {
|
||||
if (!isset($row[$key]) || $row[$key] === '') {
|
||||
return $default;
|
||||
}
|
||||
return round((float)$row[$key], 2);
|
||||
};
|
||||
$int = function ($key, $default) use ($row) {
|
||||
if (!isset($row[$key]) || $row[$key] === '') {
|
||||
return $default;
|
||||
}
|
||||
return (int)$row[$key];
|
||||
};
|
||||
|
||||
$single = $num('fc_post_singlePrice', 5);
|
||||
$monthPrice = $num('fc_post_monthPrice', 19.9);
|
||||
$yearPrice = $num('fc_post_yearPrice', 168);
|
||||
$monthQuota = $int('fc_post_monthQuota', 30);
|
||||
$yearQuota = $int('fc_post_yearQuota', 500);
|
||||
$freeQuota = $int('fc_post_freeQuota', 0);
|
||||
|
||||
foreach (['单条发布价格' => $single, '月卡价格' => $monthPrice, '年卡价格' => $yearPrice] as $label => $value) {
|
||||
if ($value < 0) {
|
||||
throw new \Exception($label . '不能为负');
|
||||
}
|
||||
}
|
||||
if ($monthQuota < 0 || $yearQuota < 0) {
|
||||
throw new \Exception('含发布条数不能为负');
|
||||
}
|
||||
if ($freeQuota < 0) {
|
||||
throw new \Exception('免费发布条数不能为负(0 表示不限制)');
|
||||
}
|
||||
|
||||
$values = [
|
||||
'post.mode' => $mode,
|
||||
'post.singlePrice' => $single,
|
||||
'post.freeQuota' => $freeQuota,
|
||||
'post.freeQuotaCycle' => $cycle,
|
||||
'post.monthPrice' => $monthPrice,
|
||||
'post.monthQuota' => $monthQuota,
|
||||
'post.yearPrice' => $yearPrice,
|
||||
'post.yearQuota' => $yearQuota,
|
||||
];
|
||||
foreach ($values as $key => $value) {
|
||||
self::put($key, $value, 'post', '发布配置');
|
||||
}
|
||||
|
||||
// 与会员套餐保持一致(后台「运营推广 → 会员套餐」仍可单独维护,但价格/条数以本页为准)
|
||||
$now = time();
|
||||
Db::name('fc_plan')->where('plan_code', 'M1')->update([
|
||||
'price' => $monthPrice,
|
||||
'post_quota' => $monthQuota,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
Db::name('fc_plan')->where('plan_code', 'M12')->update([
|
||||
'price' => $yearPrice,
|
||||
'post_quota' => $yearQuota,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分销参数
|
||||
*
|
||||
* @param array $row
|
||||
* @return void
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected static function saveDistribution(array $row)
|
||||
{
|
||||
$enabled = isset($row['fc_dist_enabled']) ? (int)$row['fc_dist_enabled'] : 1;
|
||||
$level = isset($row['fc_dist_level']) ? (int)$row['fc_dist_level'] : 2;
|
||||
$rate1 = isset($row['fc_dist_level1Rate']) ? round((float)$row['fc_dist_level1Rate'], 2) : 20;
|
||||
$rate2 = isset($row['fc_dist_level2Rate']) ? round((float)$row['fc_dist_level2Rate'], 2) : 10;
|
||||
$settle = isset($row['fc_dist_settleCycle']) ? trim((string)$row['fc_dist_settleCycle']) : 'T+7';
|
||||
$minWithdraw = isset($row['fc_dist_minWithdraw']) ? round((float)$row['fc_dist_minWithdraw'], 2) : 50;
|
||||
|
||||
if (!in_array($level, [1, 2], true)) {
|
||||
throw new \Exception('分佣层级只支持一级或二级');
|
||||
}
|
||||
if ($rate1 < 0 || $rate1 > 100 || $rate2 < 0 || $rate2 > 100) {
|
||||
throw new \Exception('分佣比例必须在 0-100 之间');
|
||||
}
|
||||
if ($minWithdraw < 0) {
|
||||
throw new \Exception('最低提现金额不能为负');
|
||||
}
|
||||
if ($settle === '') {
|
||||
$settle = 'T+7';
|
||||
}
|
||||
|
||||
$values = [
|
||||
'dist.enabled' => $enabled ? 1 : 0,
|
||||
'dist.level' => $level,
|
||||
'dist.level1Rate' => $rate1,
|
||||
'dist.level2Rate' => $rate2,
|
||||
'dist.settleCycle' => $settle,
|
||||
'dist.minWithdraw' => $minWithdraw,
|
||||
];
|
||||
foreach ($values as $key => $value) {
|
||||
self::put($key, $value, 'dist', '分销配置');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 fc_config 全部配置
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected static function values()
|
||||
{
|
||||
$result = [];
|
||||
try {
|
||||
foreach (Db::name('fc_config')->select() as $row) {
|
||||
$result[$row['key']] = $row['value'];
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// 业务表尚未初始化时,系统配置页仍可正常打开(使用默认值)
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入单项配置
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @param string $group
|
||||
* @param string $remark
|
||||
* @return void
|
||||
*/
|
||||
protected static function put($key, $value, $group, $remark)
|
||||
{
|
||||
$now = time();
|
||||
$value = is_scalar($value) || $value === null ? (string)$value : json_encode($value, JSON_UNESCAPED_UNICODE);
|
||||
$exist = Db::name('fc_config')->where('key', $key)->find();
|
||||
if ($exist) {
|
||||
Db::name('fc_config')->where('key', $key)->update([
|
||||
'value' => $value,
|
||||
'group_key' => $group,
|
||||
'remark' => $remark,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
} else {
|
||||
Db::name('fc_config')->insert([
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
'group_key' => $group,
|
||||
'remark' => $remark,
|
||||
'createtime' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造系统配置页的单个配置项
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $title
|
||||
* @param string $type
|
||||
* @param mixed $value
|
||||
* @param string $tip
|
||||
* @param string $rule
|
||||
* @param array $content
|
||||
* @return array
|
||||
*/
|
||||
protected static function item($name, $title, $type, $value, $tip = '', $rule = '', array $content = [])
|
||||
{
|
||||
return [
|
||||
'name' => $name,
|
||||
'title' => $title,
|
||||
'type' => $type,
|
||||
'value' => $value,
|
||||
'content' => $content,
|
||||
'tip' => $tip,
|
||||
'rule' => $rule,
|
||||
'extend' => '',
|
||||
'extend_html' => '',
|
||||
'setting' => [],
|
||||
'visible' => '',
|
||||
'id' => 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 订单发货(支付成功后的权益发放)
|
||||
*
|
||||
* 统一入口,避免「微信回调」和「后台补单」两处逻辑不一致:
|
||||
* member → 发放会员(Member::grantMembership,内部含分销结算)
|
||||
* recharge → 余额入账(Order::creditRecharge)
|
||||
* payview → 写入付费查看解锁记录
|
||||
* post → 信息本身已落库待审,无需额外动作
|
||||
*
|
||||
* 调用方必须已保证订单是「刚由 pending 变为 paid」,本类不再做状态判断。
|
||||
*/
|
||||
class OrderFulfill
|
||||
{
|
||||
/**
|
||||
* @param array $order fc_order 行(至少含 id/order_no/user_id/type/amount/related_id)
|
||||
* @return void
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public static function handle(array $order)
|
||||
{
|
||||
// 支付成功:核销订单锁定的优惠券(余额支付在业务侧已核销,这里幂等)
|
||||
CouponService::markUsed(isset($order['order_no']) ? (string)$order['order_no'] : '');
|
||||
|
||||
$type = isset($order['type']) ? (string)$order['type'] : '';
|
||||
|
||||
if ($type === 'member') {
|
||||
// 会员发放内部已包含分销结算
|
||||
(new \app\api\controller\Member())->grantMembership($order);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($type === 'recharge') {
|
||||
// 充值订单不分佣(DistributionService 内部也会忽略 recharge)
|
||||
(new \app\api\controller\Order())->creditRecharge($order);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($type === 'payview') {
|
||||
self::unlockPayView($order);
|
||||
}
|
||||
|
||||
// post 及其它类型:信息已落库,仅需结算分销
|
||||
DistributionService::settleOrder($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* 付费查看解锁(user_id + post_id 唯一索引保证幂等)
|
||||
*
|
||||
* @param array $order
|
||||
* @return void
|
||||
*/
|
||||
protected static function unlockPayView(array $order)
|
||||
{
|
||||
$postId = (int)(isset($order['related_id']) ? $order['related_id'] : 0);
|
||||
if ($postId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$exists = Db::name('fc_pay_view')
|
||||
->where('user_id', (int)$order['user_id'])
|
||||
->where('post_id', $postId)
|
||||
->find();
|
||||
if ($exists) {
|
||||
return;
|
||||
}
|
||||
|
||||
Db::name('fc_pay_view')->insert([
|
||||
'user_id' => (int)$order['user_id'],
|
||||
'post_id' => $postId,
|
||||
'pay_type' => isset($order['pay_type']) ? (string)$order['pay_type'] : 'wxpay',
|
||||
'amount' => round((float)(isset($order['amount']) ? $order['amount'] : 0), 2),
|
||||
'order_id' => (int)$order['id'],
|
||||
'createtime' => time(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use addons\epay\library\Service as EpayService;
|
||||
use think\Db;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 订单退款(微信原路退回 / 余额退回 + 业务回滚 + 佣金冲销)
|
||||
*
|
||||
* 规则:
|
||||
* 1. 只有 status=paid 的订单可退;
|
||||
* 2. 退款金额 > 0、≤ 订单实付金额,同一订单只退一次;
|
||||
* 3. 微信订单先调微信退款接口,受理成功后才改库;余额订单直接退回余额;
|
||||
* 4. 退款后按订单类型回滚权益:
|
||||
* recharge → 扣回余额(余额不足则拒绝退款)
|
||||
* payview → 删除解锁记录
|
||||
* member → 按套餐天数/条数扣减会员权益
|
||||
* post → 信息保留(由运营决定是否下架)
|
||||
* 5. 无论哪种订单,退款都会冲销该订单产生的分销佣金(防止“退款后仍拿佣金”)。
|
||||
*/
|
||||
class OrderRefund
|
||||
{
|
||||
/**
|
||||
* @param int $orderId
|
||||
* @param float|null $amount 不传则全额退款
|
||||
* @param string $reason
|
||||
* @return array{refundNo:string,amount:float}
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function refund($orderId, $amount = null, $reason = '')
|
||||
{
|
||||
$order = Db::name('fc_order')->where('id', (int)$orderId)->find();
|
||||
if (!$order) {
|
||||
throw new \Exception('订单不存在');
|
||||
}
|
||||
if ((string)$order['status'] !== 'paid') {
|
||||
throw new \Exception('只有已支付订单可以退款');
|
||||
}
|
||||
|
||||
$paid = round((float)$order['amount'], 2);
|
||||
$amount = $amount === null ? $paid : round((float)$amount, 2);
|
||||
if ($amount <= 0) {
|
||||
throw new \Exception('退款金额需大于 0');
|
||||
}
|
||||
if ($amount > $paid) {
|
||||
throw new \Exception('退款金额不能超过订单实付金额 ' . $paid . ' 元');
|
||||
}
|
||||
|
||||
$payType = (string)$order['pay_type'];
|
||||
if (!in_array($payType, ['wxpay', 'balance'], true)) {
|
||||
throw new \Exception('该订单支付方式不支持退款');
|
||||
}
|
||||
|
||||
// 充值订单:余额必须足够扣回,否则先拒绝(避免钱退了余额扣不回来)
|
||||
if ((string)$order['type'] === 'recharge') {
|
||||
$balance = (float)Db::name('user')->where('id', (int)$order['user_id'])->value('money');
|
||||
if ($balance < $amount) {
|
||||
throw new \Exception('用户当前余额不足 ' . $amount . ' 元,无法退回该笔充值(请先冻结或人工处理)');
|
||||
}
|
||||
}
|
||||
|
||||
$refundNo = $payType === 'wxpay' ? self::refundNo($order) : '';
|
||||
|
||||
// 0) 原子抢占:paid → refunding,避免并发重复退款(两个请求都调微信)
|
||||
$claimed = Db::name('fc_order')
|
||||
->where('id', (int)$order['id'])
|
||||
->where('status', 'paid')
|
||||
->update([
|
||||
'status' => 'refunding',
|
||||
'out_refund_no' => $refundNo,
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
if (!$claimed) {
|
||||
throw new \Exception('订单正在退款或已退款,请勿重复操作');
|
||||
}
|
||||
|
||||
// 1) 微信订单先退款(外部调用,放在事务外)
|
||||
if ($payType === 'wxpay') {
|
||||
try {
|
||||
self::requestWechatRefund($order, $refundNo, $amount, $reason);
|
||||
} catch (\Throwable $e) {
|
||||
// 退款未受理:回退为已支付,允许重新操作
|
||||
Db::name('fc_order')->where('id', (int)$order['id'])->where('status', 'refunding')->update([
|
||||
'status' => 'paid',
|
||||
'out_refund_no' => '',
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
$now = time();
|
||||
Db::transaction(function () use ($order, $amount, $reason, $refundNo, $now, $payType) {
|
||||
// 行锁 + 二次校验:此时应为 refunding
|
||||
$locked = Db::name('fc_order')->where('id', (int)$order['id'])->lock(true)->find();
|
||||
if (!$locked || (string)$locked['status'] !== 'refunding') {
|
||||
throw new \Exception('订单状态已变化,退款未写入');
|
||||
}
|
||||
|
||||
Db::name('fc_order')->where('id', (int)$order['id'])->update([
|
||||
'status' => 'refunded',
|
||||
'refund_amount' => $amount,
|
||||
'refund_reason' => (string)$reason,
|
||||
'out_refund_no' => $refundNo,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
|
||||
$userId = (int)$locked['user_id'];
|
||||
|
||||
// 2) 余额订单:直接退回余额
|
||||
if ($payType === 'balance') {
|
||||
Db::name('user')->where('id', $userId)->setInc('money', $amount);
|
||||
$balance = round((float)Db::name('user')->where('id', $userId)->value('money'), 2);
|
||||
|
||||
self::addFlow('income', '订单退款(余额)', $amount, $balance, (int)$locked['id'], '余额退款');
|
||||
} else {
|
||||
self::addFlow('expense', '订单退款', $amount, 0, (int)$locked['id'], '微信退款 ' . $refundNo);
|
||||
}
|
||||
|
||||
// 3) 权益回滚
|
||||
self::rollbackBenefits($locked, $amount, $now);
|
||||
|
||||
// 3.5) 退回优惠券(退款后券可再次使用)
|
||||
CouponService::release((string)$locked['order_no']);
|
||||
|
||||
// 4) 分销佣金冲销(所有支付方式都要做)
|
||||
self::reverseCommission($locked, $now);
|
||||
|
||||
Db::name('fc_message')->insert([
|
||||
'user_id' => $userId,
|
||||
'type' => 'system',
|
||||
'title' => '订单已退款',
|
||||
'content' => '您的订单「' . $locked['title'] . '」已退款 ' . $amount . ' 元'
|
||||
. ($payType === 'balance' ? ',已退回账户余额。' : ',将按原支付路径退回。'),
|
||||
'isread' => 0,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
});
|
||||
|
||||
Log::record('订单退款成功:订单 ' . $order['order_no'] . ',退款单号 ' . ($refundNo ?: '-') . ',金额 ' . $amount . ' 元,方式 ' . $payType, 'info');
|
||||
|
||||
return ['refundNo' => $refundNo, 'amount' => $amount];
|
||||
}
|
||||
|
||||
/**
|
||||
* 退款结果回调处理(微信 V3)
|
||||
*
|
||||
* @param array $data 解密后的回调数据
|
||||
* @return string 处理结果
|
||||
*/
|
||||
public static function handleNotify(array $data)
|
||||
{
|
||||
$outRefundNo = isset($data['out_refund_no']) ? (string)$data['out_refund_no'] : '';
|
||||
if ($outRefundNo === '') {
|
||||
return 'ignored';
|
||||
}
|
||||
|
||||
$order = Db::name('fc_order')->where('out_refund_no', $outRefundNo)->find();
|
||||
if (!$order) {
|
||||
Log::record('微信退款回调:未找到订单 out_refund_no=' . $outRefundNo, 'error');
|
||||
return 'ignored';
|
||||
}
|
||||
|
||||
$status = strtoupper((string)(isset($data['refund_status']) ? $data['refund_status'] : ''));
|
||||
if ($status === 'SUCCESS') {
|
||||
// 正常流程里已置 refunded,这里只做幂等确认
|
||||
return 'refunded';
|
||||
}
|
||||
|
||||
if (in_array($status, ['ABNORMAL', 'CLOSED'], true)) {
|
||||
// 退款失败/关闭:把订单改回 paid,等待人工重试
|
||||
Db::transaction(function () use ($order, $status) {
|
||||
$locked = Db::name('fc_order')->where('id', (int)$order['id'])->lock(true)->find();
|
||||
if (!$locked || (string)$locked['status'] !== 'refunded') {
|
||||
return;
|
||||
}
|
||||
Db::name('fc_order')->where('id', (int)$locked['id'])->update([
|
||||
'status' => 'paid',
|
||||
'refund_amount' => 0,
|
||||
'refund_reason' => '',
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
Db::name('fc_message')->insert([
|
||||
'user_id' => (int)$locked['user_id'],
|
||||
'type' => 'system',
|
||||
'title' => '退款异常',
|
||||
'content' => '您的订单「' . $locked['title'] . '」退款未成功(' . $status . '),客服将尽快处理。',
|
||||
'isread' => 0,
|
||||
'createtime' => time(),
|
||||
]);
|
||||
});
|
||||
Log::record('微信退款异常:订单 ' . $order['order_no'] . ' 状态 ' . $status, 'error');
|
||||
return 'failed';
|
||||
}
|
||||
|
||||
return 'refunding';
|
||||
}
|
||||
|
||||
/* ==================== 内部实现 ==================== */
|
||||
|
||||
/** 生成退款单号(≤ 64 字符,全局唯一) */
|
||||
protected static function refundNo(array $order)
|
||||
{
|
||||
return 'RF' . (string)$order['order_no'] . bin2hex(random_bytes(2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用微信退款(V2/V3 参数不同,交给插件 SDK 处理签名)
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected static function requestWechatRefund(array $order, $refundNo, $amount, $reason)
|
||||
{
|
||||
// 确保 epay 的 Yansongda 命名空间已注册(后台/CLI 场景下 action_begin 钩子可能未触发)
|
||||
if (!class_exists('\Yansongda\Pay\Pay')) {
|
||||
(new \addons\epay\Epay())->actionBegin();
|
||||
}
|
||||
|
||||
$config = EpayService::getConfig('wechat', []);
|
||||
$pay = \Yansongda\Pay\Pay::wechat($config);
|
||||
|
||||
$paidCents = (int)round((float)$order['amount'] * 100);
|
||||
$refundCents = (int)round($amount * 100);
|
||||
|
||||
try {
|
||||
if (EpayService::isVersionV3()) {
|
||||
$result = $pay->refund([
|
||||
'out_trade_no' => (string)$order['order_no'],
|
||||
'out_refund_no' => $refundNo,
|
||||
'reason' => mb_substr((string)$reason, 0, 80),
|
||||
'amount' => [
|
||||
'refund' => $refundCents,
|
||||
'total' => $paidCents,
|
||||
'currency' => 'CNY',
|
||||
],
|
||||
]);
|
||||
} else {
|
||||
$result = $pay->refund([
|
||||
'out_trade_no' => (string)$order['order_no'],
|
||||
'out_refund_no' => $refundNo,
|
||||
'total_fee' => $paidCents,
|
||||
'refund_fee' => $refundCents,
|
||||
'refund_desc' => mb_substr((string)$reason, 0, 80),
|
||||
]);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::record('微信退款失败:订单 ' . $order['order_no'] . ',' . $e->getMessage(), 'error');
|
||||
throw new \Exception('微信退款失败:' . $e->getMessage());
|
||||
}
|
||||
|
||||
$res = $result instanceof \Yansongda\Supports\Collection ? $result->all() : (array)$result;
|
||||
$status = isset($res['status']) ? (string)$res['status'] : '';
|
||||
// V3 受理成功返回 PROCESSING / SUCCESS;V2 返回 result_code=SUCCESS
|
||||
$ok = $status === 'SUCCESS' || $status === 'PROCESSING'
|
||||
|| (isset($res['result_code']) && (string)$res['result_code'] === 'SUCCESS');
|
||||
if (!$ok) {
|
||||
$msg = isset($res['message']) ? (string)$res['message'] : (isset($res['err_code_des']) ? (string)$res['err_code_des'] : '未知错误');
|
||||
Log::record('微信退款未受理:订单 ' . $order['order_no'] . ',' . json_encode($res, JSON_UNESCAPED_UNICODE), 'error');
|
||||
throw new \Exception('微信退款未受理:' . $msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 退款后的权益回滚
|
||||
*/
|
||||
protected static function rollbackBenefits(array $order, $amount, $now)
|
||||
{
|
||||
$type = (string)$order['type'];
|
||||
$userId = (int)$order['user_id'];
|
||||
|
||||
if ($type === 'recharge') {
|
||||
// 扣回余额(前面已校验余额充足,这里用条件更新兜底防并发)
|
||||
$affected = Db::name('user')
|
||||
->where('id', $userId)
|
||||
->where('money', '>=', $amount)
|
||||
->setDec('money', $amount);
|
||||
if (!$affected) {
|
||||
Log::record('退款回滚余额失败(余额不足):订单 ' . $order['order_no'] . ',用户 ' . $userId, 'error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ($type === 'payview') {
|
||||
Db::name('fc_pay_view')->where('order_id', (int)$order['id'])->delete();
|
||||
return;
|
||||
}
|
||||
|
||||
if ($type === 'member') {
|
||||
self::revokeMembership($order, $now);
|
||||
return;
|
||||
}
|
||||
|
||||
// post:信息保留,由运营决定是否下架
|
||||
}
|
||||
|
||||
/**
|
||||
* 会员权益回滚:按该订单套餐的天数与赠送条数扣减(支持多次叠加购买)
|
||||
*/
|
||||
protected static function revokeMembership(array $order, $now)
|
||||
{
|
||||
$userId = (int)$order['user_id'];
|
||||
$ext = Db::name('fc_user_ext')->where('user_id', $userId)->find();
|
||||
if (!$ext) {
|
||||
return;
|
||||
}
|
||||
|
||||
$plan = null;
|
||||
if (!empty($order['related_id'])) {
|
||||
$plan = Db::name('fc_plan')->where('id', (int)$order['related_id'])->find();
|
||||
}
|
||||
$days = $plan ? max(0, (int)$plan['days']) : 0;
|
||||
$quota = $plan && isset($plan['post_quota']) ? max(0, (int)$plan['post_quota']) : 0;
|
||||
|
||||
$currentExpire = (int)$ext['member_expiretime'];
|
||||
$expire = max($now, $currentExpire - $days * 86400);
|
||||
$left = max(0, (int)$ext['post_quota_left'] - $quota);
|
||||
|
||||
$update = [
|
||||
'post_quota_left' => $left,
|
||||
'updatetime' => $now,
|
||||
];
|
||||
if ($expire <= $now) {
|
||||
$update['is_member'] = 0;
|
||||
$update['member_level'] = '';
|
||||
$update['member_expiretime'] = null;
|
||||
$update['post_quota_left'] = 0;
|
||||
} else {
|
||||
$update['member_expiretime'] = $expire;
|
||||
}
|
||||
|
||||
Db::name('fc_user_ext')->where('user_id', $userId)->update($update);
|
||||
}
|
||||
|
||||
/**
|
||||
* 冲销订单产生的分销佣金:已结算记录改为未结算(status=0),并通知分销员
|
||||
*
|
||||
* 已提现部分不回滚现金,但会体现在「可提现余额」中(可能为负,后续佣金先抵扣)。
|
||||
*/
|
||||
protected static function reverseCommission(array $order, $now)
|
||||
{
|
||||
$orderNo = (string)$order['order_no'];
|
||||
if ($orderNo === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$rows = Db::name('fc_commission')
|
||||
->where('order_no', $orderNo)
|
||||
->where('status', 'in', [0, 1])
|
||||
->select();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
// status=2 表示已冲销(不计入累计/待结算/可提现)
|
||||
Db::name('fc_commission')->where('id', (int)$row['id'])->update([
|
||||
'status' => 2,
|
||||
'settletime' => null,
|
||||
]);
|
||||
|
||||
Db::name('fc_message')->insert([
|
||||
'user_id' => (int)$row['user_id'],
|
||||
'type' => 'system',
|
||||
'title' => '佣金已冲销',
|
||||
'content' => '下线订单「' . $order['title'] . '」已退款,对应佣金 ' . $row['amount'] . ' 元已冲销。',
|
||||
'isread' => 0,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** 资金流水 */
|
||||
protected static function addFlow($type, $scene, $amount, $balance, $relatedId, $remark)
|
||||
{
|
||||
Db::name('fc_finance_flow')->insert([
|
||||
'flow_no' => 'F' . date('YmdHis') . bin2hex(random_bytes(3)),
|
||||
'type' => $type,
|
||||
'scene' => $scene,
|
||||
'amount' => $amount,
|
||||
'balance' => $balance,
|
||||
'related_id' => (int)$relatedId,
|
||||
'remark' => (string)$remark,
|
||||
'createtime' => time(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use EasyWeChat\Factory;
|
||||
use EasyWeChat\MiniProgram\Application;
|
||||
use think\Db;
|
||||
|
||||
/**
|
||||
* 微信小程序统一入口(基于 overtrue/wechat 4.x,项目已随 composer 安装)
|
||||
*
|
||||
* 设计原则:
|
||||
* · 小程序侧的登录 / 手机号 / access_token **全部交给 EasyWeChat SDK**,
|
||||
* 业务代码不再手写 cURL、不再自行拼接微信接口 URL 与签名;
|
||||
* · 配置即用:只读 fa_fc_config 的 wx.appid / wx.secret(后台「小程序设置 → 微信登录」维护),
|
||||
* 换小程序或换密钥只需改配置,无需改代码;
|
||||
* · access_token 由 SDK 自带缓存管理(落盘 runtime/cache/wechat),到期自动刷新,
|
||||
* 多进程共享,不再写数据库。
|
||||
*
|
||||
* 使用示例:
|
||||
* $openid = WxMini::openid($code); // jscode2session
|
||||
* $phone = WxMini::phoneNumber($phoneCode); // getPhoneNumber
|
||||
*
|
||||
* @see \EasyWeChat\MiniProgram\Application
|
||||
*/
|
||||
class WxMini
|
||||
{
|
||||
/** @var \EasyWeChat\MiniProgram\Application|null SDK 实例(单请求内复用) */
|
||||
protected static $app = null;
|
||||
|
||||
/** @var array|null 配置缓存(fa_fc_config 中 group_key = wx) */
|
||||
protected static $cfg = null;
|
||||
|
||||
/* ==================== 配置 ==================== */
|
||||
|
||||
/**
|
||||
* 读取小程序配置
|
||||
*
|
||||
* @param string|null $key 配置键,如 wx.appid;传 null 返回全部
|
||||
* @param mixed $default 缺省值
|
||||
* @return mixed
|
||||
*/
|
||||
public static function config($key = null, $default = null)
|
||||
{
|
||||
if (self::$cfg === null) {
|
||||
self::$cfg = [];
|
||||
try {
|
||||
foreach (Db::name('fc_config')
|
||||
->where('group_key', 'wx')
|
||||
->whereOr('key', 'like', 'wx.%')
|
||||
->select() as $row) {
|
||||
self::$cfg[$row['key']] = $row['value'];
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// 业务表尚未初始化时不阻断请求,按「未配置」处理
|
||||
}
|
||||
}
|
||||
|
||||
if ($key === null) {
|
||||
return self::$cfg;
|
||||
}
|
||||
|
||||
return array_key_exists($key, self::$cfg) ? self::$cfg[$key] : $default;
|
||||
}
|
||||
|
||||
/** 清除运行时配置缓存(后台保存配置后调用) */
|
||||
public static function flush()
|
||||
{
|
||||
self::$cfg = null;
|
||||
self::$app = null;
|
||||
}
|
||||
|
||||
/** 是否已配置 AppID / AppSecret */
|
||||
public static function isConfigured()
|
||||
{
|
||||
return (string)self::config('wx.appid', '') !== ''
|
||||
&& (string)self::config('wx.secret', '') !== '';
|
||||
}
|
||||
|
||||
/* ==================== SDK ==================== */
|
||||
|
||||
/**
|
||||
* 获取 EasyWeChat 小程序实例
|
||||
*
|
||||
* @return \EasyWeChat\MiniProgram\Application
|
||||
* @throws \RuntimeException 未配置 AppID/AppSecret 时抛出
|
||||
*/
|
||||
public static function app()
|
||||
{
|
||||
if (self::$app instanceof Application) {
|
||||
return self::$app;
|
||||
}
|
||||
|
||||
if (!self::isConfigured()) {
|
||||
throw new \RuntimeException('微信小程序未配置,请先在后台「系统设置 → 系统配置 → 小程序配置」填写 AppID 与 AppSecret');
|
||||
}
|
||||
|
||||
$app = Factory::miniProgram([
|
||||
'app_id' => (string)self::config('wx.appid', ''),
|
||||
'secret' => (string)self::config('wx.secret', ''),
|
||||
'response_type' => 'array',
|
||||
'http' => [
|
||||
'timeout' => 8.0,
|
||||
'connect_timeout' => 5.0,
|
||||
],
|
||||
]);
|
||||
|
||||
// access_token 缓存落盘到 runtime(SDK 默认用系统临时目录,易被清理且不便排查)
|
||||
if (class_exists('Symfony\Component\Cache\Psr16Cache')
|
||||
&& class_exists('Symfony\Component\Cache\Adapter\FilesystemAdapter')) {
|
||||
$base = defined('CACHE_PATH') ? CACHE_PATH : RUNTIME_PATH . 'cache' . DIRECTORY_SEPARATOR;
|
||||
$dir = $base . 'wechat';
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0755, true);
|
||||
}
|
||||
$app['cache'] = new \Symfony\Component\Cache\Psr16Cache(
|
||||
new \Symfony\Component\Cache\Adapter\FilesystemAdapter('easywechat', 7200, $dir)
|
||||
);
|
||||
}
|
||||
|
||||
return self::$app = $app;
|
||||
}
|
||||
|
||||
/* ==================== 登录 / 手机号 ==================== */
|
||||
|
||||
/**
|
||||
* code 换取登录态(jscode2session)
|
||||
*
|
||||
* @param string $code wx.login / uni.login 返回的 code
|
||||
* @return array{openid:string,session_key?:string,unionid?:string}
|
||||
* @throws \RuntimeException 微信侧返回错误时抛出(message 可直接展示给用户)
|
||||
*/
|
||||
public static function session($code)
|
||||
{
|
||||
$code = trim((string)$code);
|
||||
if ($code === '') {
|
||||
throw new \RuntimeException('缺少微信授权 code');
|
||||
}
|
||||
|
||||
$res = self::toArray(self::app()->auth->session($code));
|
||||
if (empty($res['openid'])) {
|
||||
throw new \RuntimeException(self::errorMessage($res, '微信登录失败,请重试'));
|
||||
}
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
/**
|
||||
* code 换取 openid(登录场景的简写)
|
||||
*
|
||||
* @param string $code
|
||||
* @return string
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function openid($code)
|
||||
{
|
||||
$res = self::session($code);
|
||||
|
||||
return (string)$res['openid'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机号快速验证 code 换取真实手机号
|
||||
* (<button open-type="getPhoneNumber"> 回调里的 e.detail.code)
|
||||
*
|
||||
* @param string $code
|
||||
* @return string 11 位手机号
|
||||
* @throws \RuntimeException 微信侧失败 / 号码不合法时抛出
|
||||
*/
|
||||
public static function phoneNumber($code)
|
||||
{
|
||||
$code = trim((string)$code);
|
||||
if ($code === '') {
|
||||
throw new \RuntimeException('缺少手机号授权 code');
|
||||
}
|
||||
|
||||
// SDK 的 BaseClient 会自动带上 access_token(含缓存与 401 重试)
|
||||
$res = self::toArray(
|
||||
self::app()->getClient()->httpPostJson('wxa/business/getuserphonenumber', ['code' => $code])
|
||||
);
|
||||
|
||||
$info = (isset($res['phone_info']) && is_array($res['phone_info'])) ? $res['phone_info'] : [];
|
||||
$phone = '';
|
||||
if (!empty($info['phoneNumber'])) {
|
||||
$phone = (string)$info['phoneNumber'];
|
||||
} elseif (!empty($info['purePhoneNumber'])) {
|
||||
$phone = (string)$info['purePhoneNumber'];
|
||||
}
|
||||
|
||||
if (!preg_match('/^1\d{10}$/', $phone)) {
|
||||
throw new \RuntimeException(self::errorMessage($res, '微信手机号获取失败,请改用手动输入'));
|
||||
}
|
||||
|
||||
return $phone;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序 access_token(由 SDK 缓存与刷新,业务侧一般不需要直接调用)
|
||||
*
|
||||
* @return string
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function accessToken()
|
||||
{
|
||||
$token = self::toArray(self::app()->access_token->getToken());
|
||||
|
||||
return isset($token['access_token']) ? (string)$token['access_token'] : '';
|
||||
}
|
||||
|
||||
/* ==================== 内部工具 ==================== */
|
||||
|
||||
/** SDK 返回 Collection / array / object 统一转数组 */
|
||||
protected static function toArray($res)
|
||||
{
|
||||
if (is_array($res)) {
|
||||
return $res;
|
||||
}
|
||||
if ($res instanceof \EasyWeChat\Kernel\Support\Collection) {
|
||||
return $res->all();
|
||||
}
|
||||
if (is_object($res) && method_exists($res, 'toArray')) {
|
||||
return (array)$res->toArray();
|
||||
}
|
||||
|
||||
return (array)$res;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把微信返回的错误码翻译成可展示的中文
|
||||
*
|
||||
* @param array $res 微信应答
|
||||
* @param string $fallback 兜底文案
|
||||
* @return string
|
||||
*/
|
||||
protected static function errorMessage(array $res, $fallback)
|
||||
{
|
||||
$code = isset($res['errcode']) ? (int)$res['errcode'] : 0;
|
||||
$msg = isset($res['errmsg']) ? (string)$res['errmsg'] : '';
|
||||
|
||||
$known = [
|
||||
40029 => '微信登录凭证已失效,请重新授权',
|
||||
40163 => '微信登录凭证已被使用,请重新授权',
|
||||
41004 => '小程序 AppSecret 不正确,请在后台检查微信登录配置',
|
||||
45011 => '微信接口调用过于频繁,请稍后再试',
|
||||
-1 => '微信服务繁忙,请稍后再试',
|
||||
];
|
||||
if (isset($known[$code])) {
|
||||
return $known[$code];
|
||||
}
|
||||
|
||||
return $msg !== '' ? $fallback . '(' . $code . ': ' . $msg . ')' : $fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use think\Db;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 微信小程序订阅消息
|
||||
*
|
||||
* 配置(fa_fc_config,后台「系统配置 → 小程序配置」):
|
||||
* wx.tplAudit 审核结果通知模板 ID
|
||||
* wx.tplTransfer 提现到账通知模板 ID
|
||||
*
|
||||
* 说明:
|
||||
* - 模板字段名由微信侧模板决定,调用方传入的 data 需与模板一致;
|
||||
* - 用户未授权 / 模板未配置 / openid 非真实微信用户时静默跳过(不影响主流程);
|
||||
* - 发送失败只记日志,绝不阻断支付/审核等业务。
|
||||
*/
|
||||
class WxSubscribe
|
||||
{
|
||||
/** 场景 → 配置键 */
|
||||
const SCENES = [
|
||||
'audit' => 'wx.tplAudit',
|
||||
'transfer' => 'wx.tplTransfer',
|
||||
];
|
||||
|
||||
/**
|
||||
* 发送订阅消息
|
||||
*
|
||||
* @param int $userId
|
||||
* @param string $scene audit | transfer
|
||||
* @param array $data ['thing1' => '...', 'phrase2' => '...']
|
||||
* @param string $page 点击消息跳转的小程序页面
|
||||
* @return bool
|
||||
*/
|
||||
public static function send($userId, $scene, array $data, $page = 'pages/index/index')
|
||||
{
|
||||
if (!isset(self::SCENES[$scene]) || !WxMini::isConfigured()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tpl = trim((string)WxMini::config(self::SCENES[$scene], ''));
|
||||
if ($tpl === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$ext = Db::name('fc_user_ext')->where('user_id', (int)$userId)->find();
|
||||
$openid = $ext ? trim((string)$ext['openid']) : '';
|
||||
// 派生 openid(本地联调/h5)不是真实微信用户,发不出去
|
||||
if ($openid === '' || strpos($openid, 'openid_') === 0 || strpos($openid, 'h5_') === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$res = WxMini::app()->subscribe_message->send([
|
||||
'touser' => $openid,
|
||||
'template_id' => $tpl,
|
||||
'page' => $page,
|
||||
'data' => $data,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::record('订阅消息发送异常:' . $e->getMessage(), 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
$arr = $res instanceof \EasyWeChat\Kernel\Support\Collection ? $res->all() : (array)$res;
|
||||
if (isset($arr['errcode']) && (int)$arr['errcode'] !== 0) {
|
||||
Log::record('订阅消息发送失败:' . json_encode($arr, JSON_UNESCAPED_UNICODE), 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\library;
|
||||
|
||||
use addons\epay\library\Service as EpayService;
|
||||
use think\Db;
|
||||
use think\Log;
|
||||
|
||||
/**
|
||||
* 微信商家转账(V3「商家转账」,接口 /v3/fund-app/mch-transfer/transfer-bills)
|
||||
*
|
||||
* 业务链路:
|
||||
* 后台审核通过 → submit() 调微信创建转账单 → 用户微信确认收款 → 微信回调 transferNotify()
|
||||
* → applyResult() 把提现单置为 paid,并记支出流水/站内信。
|
||||
*
|
||||
* 约束(微信侧):
|
||||
* - 只能 PHP 8.0+ 且 version=v3(MchTransfer 插件只存在于 v3new);
|
||||
* - 转账场景固定 1005「佣金报酬」,必须带两条 transfer_scene_report_infos;
|
||||
* - notify_url 必须 HTTPS 且公网可访问;
|
||||
* - 单笔最低 0.1 元;≥2000 元必须传收款人姓名;
|
||||
* - 资金从「运营账户」出,余额不足会失败。
|
||||
*/
|
||||
class WxTransfer
|
||||
{
|
||||
/** 默认转账场景:佣金报酬 */
|
||||
const DEFAULT_SCENE_ID = '1005';
|
||||
|
||||
/** 提现单状态流转:auditing → paying → paid / failed */
|
||||
/**
|
||||
* 判断当前环境是否具备商家转账能力
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isReady()
|
||||
{
|
||||
if (PHP_VERSION_ID < 80000) {
|
||||
return false;
|
||||
}
|
||||
if (!EpayService::isVersionV3()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self::loadSdk();
|
||||
|
||||
return class_exists('\Yansongda\Pay\Plugin\Wechat\V3\Marketing\MchTransfer\CreatePlugin')
|
||||
&& class_exists('\Yansongda\Pay\Shortcut\Wechat\MchTransferShortcut');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建转账单
|
||||
*
|
||||
* 调用方需先把提现单置为 paying 并写入 out_bill_no(同一单重试必须复用同一单号)。
|
||||
*
|
||||
* @param array $withdraw fc_withdraw 行
|
||||
* @return array{state:string,out_bill_no:string,transfer_bill_no:string,package_info:string}
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function submit(array $withdraw)
|
||||
{
|
||||
if (!self::isReady()) {
|
||||
throw new \RuntimeException('当前环境不支持商家转账(需要 PHP 8.0+ 且 epay 插件 version=v3)');
|
||||
}
|
||||
|
||||
$outBillNo = trim((string)(isset($withdraw['out_bill_no']) ? $withdraw['out_bill_no'] : ''));
|
||||
if ($outBillNo === '') {
|
||||
throw new \RuntimeException('提现单缺少商户单号(out_bill_no)');
|
||||
}
|
||||
|
||||
$ext = Db::name('fc_user_ext')->where('user_id', (int)$withdraw['user_id'])->find();
|
||||
if (!$ext) {
|
||||
throw new \RuntimeException('用户扩展信息不存在,无法转账');
|
||||
}
|
||||
|
||||
$openid = trim((string)$ext['openid']);
|
||||
if ($openid === '' || strpos($openid, 'h5_') === 0) {
|
||||
throw new \RuntimeException('该用户没有可用的微信 openid,无法转账');
|
||||
}
|
||||
|
||||
$amountCents = (int)round((float)$withdraw['amount'] * 100);
|
||||
if ($amountCents < 10) {
|
||||
throw new \RuntimeException('单笔转账金额不能低于 0.1 元');
|
||||
}
|
||||
|
||||
$realname = trim((string)(isset($ext['realname']) ? $ext['realname'] : ''));
|
||||
if ($amountCents >= 200000 && $realname === '') {
|
||||
throw new \RuntimeException('转账金额≥2000 元时必须填写收款人真实姓名');
|
||||
}
|
||||
|
||||
$config = EpayService::getConfig('wechat', []);
|
||||
$pay = \Yansongda\Pay\Pay::wechat($config);
|
||||
|
||||
$params = [
|
||||
// mini:用 miniapp_id 作为 appid
|
||||
'_type' => 'mini',
|
||||
'out_bill_no' => $outBillNo,
|
||||
'openid' => $openid,
|
||||
'transfer_amount' => $amountCents,
|
||||
'transfer_remark' => '分销佣金提现',
|
||||
'transfer_scene_id' => self::sceneId(),
|
||||
'transfer_scene_report_infos' => self::sceneInfos(),
|
||||
'user_recv_perception' => '劳务报酬',
|
||||
];
|
||||
$notifyUrl = self::notifyUrl();
|
||||
if ($notifyUrl !== '') {
|
||||
$params['notify_url'] = $notifyUrl;
|
||||
}
|
||||
if ($realname !== '') {
|
||||
$params['user_name'] = $realname;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $pay->mchTransfer($params);
|
||||
} catch (\Throwable $e) {
|
||||
$detail = self::errorDetail($e);
|
||||
Log::record('商家转账创建失败:提现单 ' . $withdraw['withdraw_no'] . ',' . $detail, 'error');
|
||||
throw new \RuntimeException('微信转账失败:' . $detail);
|
||||
}
|
||||
|
||||
$res = $result instanceof \Yansongda\Supports\Collection ? $result->all() : (array)$result;
|
||||
$state = isset($res['state']) ? (string)$res['state'] : '';
|
||||
if ($state === '') {
|
||||
Log::record('商家转账应答异常:' . json_encode($res, JSON_UNESCAPED_UNICODE), 'error');
|
||||
throw new \RuntimeException('微信转账应答异常');
|
||||
}
|
||||
|
||||
return [
|
||||
'state' => $state,
|
||||
'out_bill_no' => $outBillNo,
|
||||
'transfer_bill_no' => isset($res['transfer_bill_no']) ? (string)$res['transfer_bill_no'] : '',
|
||||
'package_info' => isset($res['package_info']) ? (string)$res['package_info'] : '',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询转账单(回调丢失时补偿用)
|
||||
*
|
||||
* @param string $outBillNo
|
||||
* @return array
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function query($outBillNo)
|
||||
{
|
||||
if (!self::isReady()) {
|
||||
throw new \RuntimeException('当前环境不支持商家转账');
|
||||
}
|
||||
|
||||
$config = EpayService::getConfig('wechat', []);
|
||||
$pay = \Yansongda\Pay\Pay::wechat($config);
|
||||
|
||||
try {
|
||||
$result = $pay->mchTransfer(['_action' => 'query', 'out_bill_no' => $outBillNo]);
|
||||
} catch (\Throwable $e) {
|
||||
throw new \RuntimeException('查询转账单失败:' . $e->getMessage());
|
||||
}
|
||||
|
||||
return $result instanceof \Yansongda\Supports\Collection ? $result->all() : (array)$result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 审核通过并自动发起商家转账
|
||||
*
|
||||
* 流程:auditing → paying(落 out_bill_no)→ 调微信创建转账单 → 立即结果 / 等待回调
|
||||
* 失败时回滚为 auditing,允许重新审核。
|
||||
*
|
||||
* @param int $withdrawId
|
||||
* @return array{state:string,withdrawState:string}
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function approve($withdrawId)
|
||||
{
|
||||
$withdraw = Db::name('fc_withdraw')->where('id', (int)$withdrawId)->find();
|
||||
if (!$withdraw) {
|
||||
throw new \RuntimeException('提现记录不存在');
|
||||
}
|
||||
if ((string)$withdraw['status'] !== 'auditing') {
|
||||
throw new \RuntimeException('该提现记录已处理(当前状态:' . $withdraw['status'] . ')');
|
||||
}
|
||||
|
||||
$outBillNo = self::makeOutBillNo($withdraw);
|
||||
$now = time();
|
||||
|
||||
// 1) 先落「转账中」,防止重复点击造成重复转账
|
||||
Db::transaction(function () use ($withdraw, $outBillNo, $now) {
|
||||
$locked = Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->lock(true)->find();
|
||||
if (!$locked || (string)$locked['status'] !== 'auditing') {
|
||||
throw new \RuntimeException('该提现记录已处理,请刷新后重试');
|
||||
}
|
||||
Db::name('fc_withdraw')->where('id', (int)$locked['id'])->update([
|
||||
'status' => 'paying',
|
||||
'out_bill_no' => $outBillNo,
|
||||
'transfer_status' => '',
|
||||
'transfer_id' => '',
|
||||
'package_info' => '',
|
||||
'fail_reason' => '',
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
});
|
||||
|
||||
// 2) 调微信创建转账单;失败回滚为待审核
|
||||
try {
|
||||
$res = self::submit(array_merge($withdraw, ['out_bill_no' => $outBillNo]));
|
||||
} catch (\Throwable $e) {
|
||||
Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->where('status', 'paying')->update([
|
||||
'status' => 'auditing',
|
||||
'fail_reason' => mb_substr($e->getMessage(), 0, 200),
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
|
||||
Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->update([
|
||||
'transfer_id' => $res['transfer_bill_no'],
|
||||
'package_info' => $res['package_info'],
|
||||
'transfer_status' => $res['state'],
|
||||
'transfer_time' => time(),
|
||||
]);
|
||||
|
||||
// 3) 应用立即结果(SUCCESS → paid;FAIL/CANCELLED → failed;其余保持 paying)
|
||||
$state = self::applyResult([
|
||||
'out_bill_no' => $outBillNo,
|
||||
'state' => $res['state'],
|
||||
'transfer_bill_no' => $res['transfer_bill_no'],
|
||||
'fail_reason' => isset($res['fail_reason']) ? $res['fail_reason'] : '',
|
||||
]);
|
||||
|
||||
$withdrawState = (string)Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->value('status');
|
||||
|
||||
return ['state' => $state, 'withdrawState' => $withdrawState];
|
||||
}
|
||||
|
||||
/**
|
||||
* 主动同步单笔提现的转账状态(回调缺失时兜底)
|
||||
*
|
||||
* @param int $withdrawId
|
||||
* @return string 同步后的提现单状态
|
||||
*/
|
||||
public static function sync($withdrawId)
|
||||
{
|
||||
$withdraw = Db::name('fc_withdraw')->where('id', (int)$withdrawId)->find();
|
||||
if (!$withdraw) {
|
||||
return 'ignored';
|
||||
}
|
||||
if ((string)$withdraw['status'] !== 'paying') {
|
||||
return (string)$withdraw['status'];
|
||||
}
|
||||
|
||||
$outBillNo = trim((string)$withdraw['out_bill_no']);
|
||||
if ($outBillNo === '') {
|
||||
return 'ignored';
|
||||
}
|
||||
|
||||
try {
|
||||
$res = self::query($outBillNo);
|
||||
} catch (\Throwable $e) {
|
||||
Log::record('查询转账单失败:' . $outBillNo . ',' . $e->getMessage(), 'error');
|
||||
return 'paying';
|
||||
}
|
||||
|
||||
return self::applyResult($res);
|
||||
}
|
||||
|
||||
/**
|
||||
* 撤销「待用户确认」的转账单
|
||||
*
|
||||
* 仅当提现单为 paying 且有 out_bill_no 时可撤销;撤销后置为 failed,可重新申请。
|
||||
*
|
||||
* @param int $withdrawId
|
||||
* @return string 处理后的提现单状态
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function cancel($withdrawId)
|
||||
{
|
||||
$withdraw = Db::name('fc_withdraw')->where('id', (int)$withdrawId)->find();
|
||||
if (!$withdraw) {
|
||||
throw new \RuntimeException('提现记录不存在');
|
||||
}
|
||||
if ((string)$withdraw['status'] !== 'paying') {
|
||||
throw new \RuntimeException('只有「转账中」的提现单可以撤销(当前:' . $withdraw['status'] . ')');
|
||||
}
|
||||
$outBillNo = trim((string)$withdraw['out_bill_no']);
|
||||
if ($outBillNo === '') {
|
||||
throw new \RuntimeException('提现单缺少商户单号,无法撤销');
|
||||
}
|
||||
|
||||
if (!self::isReady()) {
|
||||
throw new \RuntimeException('当前环境不支持商家转账');
|
||||
}
|
||||
|
||||
$config = EpayService::getConfig('wechat', []);
|
||||
$pay = \Yansongda\Pay\Pay::wechat($config);
|
||||
|
||||
try {
|
||||
$result = $pay->mchTransfer([
|
||||
'_action' => 'cancel',
|
||||
'_type' => 'mini',
|
||||
'out_bill_no' => $outBillNo,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
$detail = self::errorDetail($e);
|
||||
Log::record('撤销商家转账失败:' . $outBillNo . ',' . $detail, 'error');
|
||||
throw new \RuntimeException('撤销失败:' . $detail);
|
||||
}
|
||||
|
||||
$res = $result instanceof \Yansongda\Supports\Collection ? $result->all() : (array)$result;
|
||||
$state = isset($res['state']) ? (string)$res['state'] : 'CANCELLED';
|
||||
|
||||
return self::applyResult([
|
||||
'out_bill_no' => $outBillNo,
|
||||
'state' => $state === 'CANCELLED' ? 'CANCELLED' : $state,
|
||||
'transfer_bill_no' => isset($res['transfer_bill_no']) ? (string)$res['transfer_bill_no'] : '',
|
||||
'fail_reason' => '已撤销',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用转账结果(创建应答 / 回调 / 主动查询 共用)
|
||||
*
|
||||
* @param array $data 微信返回或回调解密后的数据
|
||||
* @return string 处理后的提现单状态(paid / failed / paying / ignored)
|
||||
*/
|
||||
public static function applyResult(array $data)
|
||||
{
|
||||
$outBillNo = trim((string)(isset($data['out_bill_no']) ? $data['out_bill_no'] : ''));
|
||||
if ($outBillNo === '') {
|
||||
return 'ignored';
|
||||
}
|
||||
|
||||
$state = strtoupper(trim((string)(isset($data['state']) ? $data['state'] : '')));
|
||||
$transferBillNo = isset($data['transfer_bill_no']) ? (string)$data['transfer_bill_no'] : '';
|
||||
$failReason = isset($data['fail_reason']) ? (string)$data['fail_reason'] : '';
|
||||
|
||||
$withdraw = Db::name('fc_withdraw')->where('out_bill_no', $outBillNo)->find();
|
||||
if (!$withdraw) {
|
||||
Log::record('商家转账回调:未找到提现单 out_bill_no=' . $outBillNo, 'error');
|
||||
return 'ignored';
|
||||
}
|
||||
|
||||
// 已到终态:幂等返回
|
||||
if ((string)$withdraw['status'] === 'paid') {
|
||||
return 'paid';
|
||||
}
|
||||
|
||||
// 金额校验:成功回调的转账金额必须与提现申请一致(防止串单/异常)
|
||||
$transferAmount = isset($data['transfer_amount']) ? (int)$data['transfer_amount'] : null;
|
||||
$expectedCents = (int)round((float)$withdraw['amount'] * 100);
|
||||
if ($state === 'SUCCESS' && $transferAmount !== null && $transferAmount !== $expectedCents) {
|
||||
Log::record(
|
||||
'商家转账金额不一致:提现单 ' . $outBillNo . ' 申请 ' . $expectedCents . ' 分,回调 ' . $transferAmount . ' 分',
|
||||
'error'
|
||||
);
|
||||
Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->update([
|
||||
'transfer_status' => 'AMOUNT_MISMATCH',
|
||||
'fail_reason' => '回调金额与申请不一致,请人工核对',
|
||||
'updatetime' => time(),
|
||||
]);
|
||||
return 'ignored';
|
||||
}
|
||||
|
||||
$now = time();
|
||||
|
||||
if ($state === 'SUCCESS') {
|
||||
Db::transaction(function () use ($withdraw, $outBillNo, $transferBillNo, $now) {
|
||||
$locked = Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->lock(true)->find();
|
||||
if (!$locked || (string)$locked['status'] === 'paid') {
|
||||
return;
|
||||
}
|
||||
|
||||
$affected = Db::name('fc_withdraw')
|
||||
->where('id', (int)$locked['id'])
|
||||
->where('status', '<>', 'paid')
|
||||
->update([
|
||||
'status' => 'paid',
|
||||
'paytime' => $now,
|
||||
'transfer_status' => 'SUCCESS',
|
||||
'transfer_id' => $transferBillNo,
|
||||
'fail_reason' => '',
|
||||
'transfer_time' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
if (!$affected) {
|
||||
return;
|
||||
}
|
||||
|
||||
Db::name('fc_finance_flow')->insert([
|
||||
'flow_no' => 'FWD' . date('YmdHis') . $locked['id'] . bin2hex(random_bytes(2)),
|
||||
'type' => 'expense',
|
||||
'scene' => '佣金提现',
|
||||
'amount' => $locked['amount'],
|
||||
'balance' => 0,
|
||||
'related_id' => (int)$locked['id'],
|
||||
'remark' => '微信商家转账 ' . $transferBillNo,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
|
||||
Db::name('fc_message')->insert([
|
||||
'user_id' => (int)$locked['user_id'],
|
||||
'type' => 'system',
|
||||
'title' => '提现已到账',
|
||||
'content' => '您的提现申请「' . $locked['withdraw_no'] . '」已转入微信零钱,金额:' . $locked['amount'] . ' 元。',
|
||||
'isread' => 0,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
});
|
||||
|
||||
// 订阅消息:提现到账(未配置模板/未授权时静默跳过)
|
||||
\app\common\library\WxSubscribe::send(
|
||||
(int)$withdraw['user_id'],
|
||||
'transfer',
|
||||
[
|
||||
'amount1' => ['value' => number_format((float)$withdraw['amount'], 2) . '元'],
|
||||
'thing2' => ['value' => '分销佣金提现'],
|
||||
'time3' => ['value' => date('Y-m-d H:i')],
|
||||
],
|
||||
'pages/distribution/index'
|
||||
);
|
||||
|
||||
return 'paid';
|
||||
}
|
||||
|
||||
if (in_array($state, ['FAIL', 'CANCELLED'], true)) {
|
||||
Db::transaction(function () use ($withdraw, $transferBillNo, $failReason, $state, $now) {
|
||||
$locked = Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->lock(true)->find();
|
||||
if (!$locked || in_array((string)$locked['status'], ['paid', 'rejected'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Db::name('fc_withdraw')->where('id', (int)$locked['id'])->update([
|
||||
'status' => 'failed',
|
||||
'transfer_status' => $state,
|
||||
'transfer_id' => $transferBillNo,
|
||||
'fail_reason' => mb_substr($failReason, 0, 200),
|
||||
'transfer_time' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
|
||||
Db::name('fc_message')->insert([
|
||||
'user_id' => (int)$locked['user_id'],
|
||||
'type' => 'system',
|
||||
'title' => '提现转账失败',
|
||||
'content' => '您的提现申请「' . $locked['withdraw_no'] . '」转账失败' . ($failReason !== '' ? ':' . $failReason : '') . ',可重新申请。',
|
||||
'isread' => 0,
|
||||
'createtime' => $now,
|
||||
]);
|
||||
});
|
||||
|
||||
return 'failed';
|
||||
}
|
||||
|
||||
// WAIT_USER_CONFIRM / ACCEPTED / PROCESSING:保持 paying,等待用户确认或回调
|
||||
Db::name('fc_withdraw')->where('id', (int)$withdraw['id'])->update([
|
||||
'transfer_status' => $state,
|
||||
'transfer_id' => $transferBillNo,
|
||||
'transfer_time' => $now,
|
||||
'updatetime' => $now,
|
||||
]);
|
||||
|
||||
return 'paying';
|
||||
}
|
||||
|
||||
/* ==================== 配置与工具 ==================== */
|
||||
|
||||
/** 转账场景 ID(默认 1005 佣金报酬) */
|
||||
public static function sceneId()
|
||||
{
|
||||
$v = trim((string)self::cfg('transfer.sceneId', ''));
|
||||
return $v !== '' ? $v : self::DEFAULT_SCENE_ID;
|
||||
}
|
||||
|
||||
/** 场景报备信息(佣金报酬固定两条) */
|
||||
public static function sceneInfos()
|
||||
{
|
||||
$raw = self::cfg('transfer.sceneInfos', '');
|
||||
if (is_string($raw) && $raw !== '') {
|
||||
$decoded = json_decode($raw, true);
|
||||
if (is_array($decoded) && !empty($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
['info_type' => '岗位类型', 'info_content' => '推广员'],
|
||||
['info_type' => '报酬说明', 'info_content' => '分销佣金'],
|
||||
];
|
||||
}
|
||||
|
||||
/** 转账结果回调地址(必须 HTTPS 且公网可访问) */
|
||||
public static function notifyUrl()
|
||||
{
|
||||
$configured = trim((string)self::cfg('transfer.notifyUrl', ''));
|
||||
if ($configured !== '' && preg_match('#^https://#i', $configured)) {
|
||||
return $configured;
|
||||
}
|
||||
|
||||
$root = '';
|
||||
if (function_exists('request')) {
|
||||
try {
|
||||
$root = (string)request()->root(true);
|
||||
} catch (\Throwable $e) {
|
||||
$root = '';
|
||||
}
|
||||
}
|
||||
if ($root === '' && function_exists('request')) {
|
||||
try {
|
||||
$root = (string)request()->domain();
|
||||
} catch (\Throwable $e) {
|
||||
$root = '';
|
||||
}
|
||||
}
|
||||
|
||||
$root = rtrim(preg_replace('#/[a-zA-Z0-9_\-]+\.php$#i', '', $root), '/');
|
||||
if ($root === '' || !preg_match('#^https://#i', $root)) {
|
||||
// 微信要求 notify_url 必须 HTTPS;本地/HTTP 环境不传,改用主动查询同步结果
|
||||
return '';
|
||||
}
|
||||
|
||||
return $root . '/api/v1/pay/transfer-notify';
|
||||
}
|
||||
|
||||
/** 生成商户转账单号:TB + 提现单号(≤32,字母数字) */
|
||||
public static function makeOutBillNo(array $withdraw)
|
||||
{
|
||||
$no = preg_replace('/[^A-Za-z0-9]/', '', (string)$withdraw['withdraw_no']);
|
||||
|
||||
return substr('TB' . $no, 0, 32);
|
||||
}
|
||||
|
||||
/** 读取业务配置 */
|
||||
protected static function cfg($key, $default = null)
|
||||
{
|
||||
$row = Db::name('fc_config')->where('key', $key)->find();
|
||||
if (!$row || !isset($row['value']) || $row['value'] === '') {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $row['value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取微信返回的错误原因(yansongda 的异常 message 往往只有“状态码异常”)
|
||||
*
|
||||
* @param \Throwable $e
|
||||
* @return string
|
||||
*/
|
||||
protected static function errorDetail(\Throwable $e)
|
||||
{
|
||||
$response = null;
|
||||
if (isset($e->response)) {
|
||||
$response = $e->response;
|
||||
}
|
||||
if ($response instanceof \Yansongda\Supports\Collection) {
|
||||
$response = $response->all();
|
||||
}
|
||||
|
||||
if (is_array($response)) {
|
||||
if (!empty($response['message'])) {
|
||||
return (string)$response['message'];
|
||||
}
|
||||
if (!empty($response['code'])) {
|
||||
return (string)$response['code'];
|
||||
}
|
||||
}
|
||||
|
||||
return $e->getMessage();
|
||||
}
|
||||
|
||||
/** 注册 epay 内置 SDK 命名空间(后台/CLI 场景下钩子可能未触发) */
|
||||
protected static function loadSdk()
|
||||
{
|
||||
if (!class_exists('\Yansongda\Pay\Pay')) {
|
||||
(new \addons\epay\Epay())->actionBegin();
|
||||
}
|
||||
}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户