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