文件
fenleixinxi/application/api/controller/Pay.php

580 行
25 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

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