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

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

查看文件

@@ -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')
{