文件
fenleixinxi/addons/epay/library/Service.php
MiAn 63fdfe87d7 feat(v1.1.0): 支付改由 epay 插件承载、插件纳入版本库,补齐媒体上传/LBS/互动/优惠券/后台看板,并修复余额充值资损
## 一、支付:改由已安装的 epay 插件承载(不再自研签名)
- 下单:\addons\epay\library\Service::submitOrder($amount 元, $orderNo, 'wechat', $body, $notifyUrl, null, 'miniapp', $openid)
- 验签:Service::checkNotify('wechat')(内部 $pay->verify());应答:$pay->success()(v2 = XML)
- 业务编排仍在 application/api/controller/Pay.php,不改插件源码:
  POST /pay/prepay(取调起参数,下发前剔除 appId);POST /pay/notify(公开路由:插件验签 → 金额核对 → 幂等分派)
- 配置真源 = addons/epay/config.php(后台「插件管理 → 微信支付宝整合插件 → 配置」);
  fc_config 的 wx.mchId / wx.apiKey / wx.payNotifyUrl 废弃;后台「系统设置」支付表单改只读并跳插件配置页
- 插件 API 保持 version=v2(PHP 7.4 可跑);certs/* 为 0 字节占位,不含任何真实密钥
- 修复 BUG-015:Pay::notify() 与基类站内信同名且签名不兼容导致 /pay/* 全 500,动作改名 notifyCallback()

## 二、插件纳入 Git 版本管理
- .gitignore 移除 /addons/* 与 /public/assets/addons/*(保留 .gitkeep 占位)
- 入库 addons/epay、addons/wechat、public/assets/addons/*、addons/.htaccess(deny from all)
- config.php 入库为空白模板;服务器请在填好密钥后执行
  git update-index --skip-worktree addons/epay/config.php,避免真实密钥回传仓库

## 三、安全修复:余额充值资损(高危,已实测复现)
- 现象:POST /order/recharge {payType:'balance'} 只加余额不扣款(余额 134.50 → 1022.50),等于凭空增发余额,
  可再去买会员 / 付费发布 / 解锁联系方式
- 修复:/order/recharge 仅接受 payType=wxpay,balance → 「余额充值仅支持微信支付」,其它 → 「支付方式不支持」;
  订单恒为 status=pending、pay_type=wxpay、paytime=null;入账只发生在 /pay/notify 回调(Order::creditRecharge)
  或后台「会员管理 → 余额充值」(fc/userext/recharge)
- 小程序充值页同步为「仅微信支付」+ 防重复提交 + onShow 刷新资产;mock / 用例 / 文档同步

## 四、其他 v1.1.0 能力
- 媒体上传:POST /post/upload(图片 ≤10MB / 视频 ≤50MB,真落盘),发布页 uni.uploadFile 真上传
- LBS:fc_post.lat/lng、首页 sort=nearby(距离升序、无坐标排最后)、卡片 distance、详情页地图
- 互动:举报 POST /report(原因字典)、收藏 / 关注(fc_favorite / fc_follow、/favorite/*、/follow/toggle)
- 交易:余额充值 POST /order/recharge、优惠券 /coupon/list|receive(fc_coupon / fc_user_coupon、我的资产券)
- 发布计费:会员发布折扣(discountRate/discountText)+ 免费发布条数(freeQuota*)
- 后台新增:数据总览 fc/dashboard、系统设置 fc/setting、优惠券管理 fc/coupon(含菜单与权限节点)

## 五、本批审核修复
- 详情页:游客不再请求登录态接口(避免 401 被清 token 踢去登录);微信付费查看改为支付后轮询解锁,
  不再读取 wxpay 分支未返回的 contact;加防重复提交
- 发布页:freeLeftToday → freeQuotaLeft / freeQuotaCycle / freeUnlimited(对齐后端出参);
  上传图预览拼后端域名(新增 format.js#assetUrl,后端返回相对路径)
- 收藏空态「去首页」:switchTab → reLaunch(项目用自绘 fc-tabbar,无 tabBar,switchTab 必然失败)
- 会员券 days=0 显示「永久有效」;manifest.json 补 requiredPrivateInfos(getLocation / chooseLocation)
- 后端:publishConfig 补 discountRate/discountText 与 memberPostDiscountText();优惠券总开关 coupon.enabled
  真生效(关闭后 list/receive 拒绝);后台 fc/Coupon 的 add/edit 补 strip_tags 过滤(防存储型 XSS)、
  补 searchFields='name',列表 name 列再做一次 HTML 转义
- FcInstall:补清理后台菜单缓存 __menu__(否则新菜单要等缓存过期才显示),并同步 README 说明
- 后台语言包 fc/setting.php 按「支付只读 + 跳插件配置」的新页面重写
- 文档同步:uniapp/docs/{01,03,04}、uniapp/README.md、docs/05-后端实现规范.md、后台 README 上线步骤

## 六、校验结果(全部通过)
- 后端端到端:tools/verify-api.mjs 226/226(含新增「拒绝余额充值(资损防护)」用例)
- 小程序:uniapp/tests/run.mjs 167/167;validate.mjs 0 错 0 警;check-scss 19/19
- 后台:check-admin-i18n 0 错 0 警;check-theme 0 错 0 警;9 个页面 HTTP 200 全中文
- php -l 改动/新增 PHP 文件 0 语法错误;探针复测:余额不再增长、epay 插件下单/验签链路通
2026-10-19 10:03:13 +08:00

495 行
19 KiB
PHP

<?php
namespace addons\epay\library;
use addons\third\model\Third;
use app\common\library\Auth;
use Exception;
use think\Hook;
use think\Session;
use Yansongda\Pay\Pay;
use Yansongda\Supports\Str;
/**
* 订单服务类
*
* @package addons\epay\library
*/
class Service
{
public const SDK_VERSION_V2 = 'v2';
public const SDK_VERSION_V3 = 'v3';
/**
* 提交订单
* @param array|float $amount 订单金额
* @param string $orderid 订单号
* @param string $type 支付类型,可选alipay或wechat
* @param string $title 订单标题
* @param string $notifyurl 通知回调URL
* @param string $returnurl 跳转返回URL
* @param string $method 支付方法
* @param string $openid Openid
* @param array $custom 自定义微信支付宝相关配置
* @return Response|RedirectResponse|Collection
* @throws Exception
*/
public static function submitOrder($amount, $orderid = null, $type = null, $title = null, $notifyurl = null, $returnurl = null, $method = null, $openid = '', $custom = [])
{
$version = self::getSdkVersion();
$request = request();
$addonConfig = get_addon_config('epay');
if (!is_array($amount)) {
$params = [
'amount' => $amount,
'orderid' => $orderid,
'type' => $type,
'title' => $title,
'notifyurl' => $notifyurl,
'returnurl' => $returnurl,
'method' => $method,
'openid' => $openid,
'custom' => $custom,
];
} else {
$params = $amount;
}
$type = isset($params['type']) && in_array($params['type'], ['alipay', 'wechat']) ? $params['type'] : 'wechat';
$method = $params['method'] ?? 'web';
$orderid = $params['orderid'] ?? date("YmdHis") . mt_rand(100000, 999999);
$amount = $params['amount'] ?? 1;
$title = $params['title'] ?? "支付";
$auth_code = $params['auth_code'] ?? '';
$openid = $params['openid'] ?? '';
//自定义微信支付宝相关配置
$custom = $params['custom'] ?? [];
//未定义则使用默认回调和跳转
$notifyurl = !empty($params['notifyurl']) ? $params['notifyurl'] : $request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
$returnurl = !empty($params['returnurl']) ? $params['returnurl'] : $request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $orderid;
$html = '';
$config = Service::getConfig($type, array_merge($custom, ['notify_url' => $notifyurl, 'return_url' => $returnurl]));
//判断是否移动端或微信内浏览器
$isMobile = $request->isMobile();
$isWechat = strpos($request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
$result = null;
if ($type == 'alipay') {
//如果是PC支付,判断当前环境,进行跳转
if ($method == 'web') {
//如果是微信环境或后台配置PC使用扫码支付
if ($isWechat || $addonConfig['alipay']['scanpay']) {
Session::set("alipayorderdata", $params);
$url = addon_url('epay/api/alipay', [], true, true);
return new RedirectResponse($url);
} elseif ($isMobile) {
$method = 'wap';
}
}
//创建支付对象
$pay = Pay::alipay($config);
$params = [
'out_trade_no' => $orderid,//你的订单号
'total_amount' => $amount,//单位元
'subject' => $title,
];
switch ($method) {
case 'web':
//电脑支付
$result = $pay->web($params);
break;
case 'wap':
//手机网页支付
$result = $pay->wap($params);
break;
case 'app':
//APP支付
$result = $pay->app($params);
break;
case 'scan':
//扫码支付
$result = $pay->scan($params);
break;
case 'pos':
//刷卡支付必须要有auth_code
$params['auth_code'] = $auth_code;
$result = $pay->pos($params);
break;
case 'mini':
case 'miniapp':
//小程序支付,直接返回字符串
//小程序支付必须要有buyer_id或buyer_open_id
if (is_numeric($openid) && strlen($openid) === 16) {
$params['buyer_id'] = $openid;
} else {
$params['buyer_open_id'] = $openid;
}
$result = $pay->mini($params);
break;
default:
}
} else {
//如果是PC支付,判断当前环境,进行跳转
if ($method == 'web') {
//如果是移动端,但不是微信环境
if ($isMobile && !$isWechat) {
$method = 'wap';
} else {
Session::set("wechatorderdata", $params);
$url = addon_url('epay/api/wechat', [], true, true);
return new RedirectResponse($url);
}
}
//单位分
$total_fee = function_exists('bcmul') ? bcmul($amount, 100) : $amount * 100;
$total_fee = (int)$total_fee;
$ip = $request->ip();
//微信服务商模式时需传递sub_openid参数
$openidName = $addonConfig['wechat']['mode'] == 'service' ? 'sub_openid' : 'openid';
//创建支付对象
$pay = Pay::wechat($config);
if (self::isVersionV3()) {
//V3支付
$params = [
'out_trade_no' => $orderid,
'description' => $title,
'amount' => [
'total' => $total_fee,
]
];
switch ($method) {
case 'mp':
//公众号支付
//公众号支付必须有openid
$params['payer'] = [$openidName => $openid];
$result = $pay->mp($params);
break;
case 'wap':
//手机网页支付,跳转
$params['scene_info'] = [
'payer_client_ip' => $ip,
'h5_info' => [
'type' => 'Wap',
]
];
$result = $pay->wap($params);
break;
case 'app':
//APP支付,直接返回字符串
$result = $pay->app($params);
break;
case 'scan':
//扫码支付,直接返回字符串
$result = $pay->scan($params);
break;
case 'pos':
//刷卡支付,直接返回字符串
//刷卡支付必须要有auth_code
$params['auth_code'] = $auth_code;
$result = $pay->pos($params);
break;
case 'mini':
case 'miniapp':
//小程序支付,直接返回字符串
//小程序支付必须要有openid
$params['payer'] = [$openidName => $openid];
$result = $pay->mini($params);
break;
default:
}
} else {
//V2支付
$params = [
'out_trade_no' => $orderid,
'body' => $title,
'total_fee' => $total_fee,
];
switch ($method) {
case 'mp':
//公众号支付
//公众号支付必须有openid
$params[$openidName] = $openid;
$result = $pay->mp($params);
break;
case 'wap':
//手机网页支付,跳转
$params['spbill_create_ip'] = $ip;
$result = $pay->wap($params);
break;
case 'app':
//APP支付,直接返回字符串
$result = $pay->app($params);
break;
case 'scan':
//扫码支付,直接返回字符串
$result = $pay->scan($params);
break;
case 'pos':
//刷卡支付,直接返回字符串
//刷卡支付必须要有auth_code
$params['auth_code'] = $auth_code;
$result = $pay->pos($params);
break;
case 'mini':
case 'miniapp':
//小程序支付,直接返回字符串
//小程序支付必须要有openid
$params[$openidName] = $openid;
$result = $pay->miniapp($params);
break;
default:
}
}
}
//使用重写的Response类、RedirectResponse、Collection类
if ($result instanceof \Symfony\Component\HttpFoundation\RedirectResponse) {
$result = new RedirectResponse($result->getTargetUrl());
} elseif ($result instanceof \Symfony\Component\HttpFoundation\Response) {
$result = new Response($result->getContent());
} elseif ($result instanceof \Yansongda\Supports\Collection) {
$result = Collection::make($result->all());
} elseif ($result instanceof \GuzzleHttp\Psr7\Response) {
$result = new Response($result->getBody());
}
return $result;
}
/**
* 验证回调是否成功
* @param string $type 支付类型
* @param array $custom 自定义配置信息
* @return bool|\Yansongda\Pay\Gateways\Alipay|\Yansongda\Pay\Gateways\Wechat|\Yansongda\Pay\Provider\Wechat|\Yansongda\Pay\Provider\Alipay
*/
public static function checkNotify($type, $custom = [])
{
$type = strtolower($type);
if (!in_array($type, ['wechat', 'alipay'])) {
return false;
}
$version = self::getSdkVersion();
try {
$config = self::getConfig($type, $custom);
$pay = $type == 'wechat' ? Pay::wechat($config) : Pay::alipay($config);
$data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
if ($type == 'alipay') {
if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
return $pay;
}
} else {
return $pay;
}
} catch (Exception $e) {
\think\Log::record("回调请求参数解析错误", "error");
return false;
}
return false;
}
/**
* 验证返回是否成功,请勿用于判断是否支付成功的逻辑验证
* 已弃用
*
* @param string $type 支付类型
* @param array $custom 自定义配置信息
* @return bool
* @deprecated 已弃用,请勿用于逻辑验证
*/
public static function checkReturn($type, $custom = [])
{
//由于PC及移动端无法获取请求的参数信息,取消return验证,均返回true
return true;
}
/**
* 处理证书路径
* @param array $config 配置
* @param string $field 字段
* @return void
*/
private static function processAddonsPath(&$config, $field)
{
if (isset($config[$field]) && substr($config[$field], 0, 8) == '/addons/') {
$config[$field] = ROOT_PATH . str_replace('/', DS, substr($config[$field], 1));
}
}
/**
* 获取配置
* @param string $type 支付类型
* @param array $custom 自定义配置,用于覆盖插件默认配置
* @return array
*/
public static function getConfig($type = 'wechat', $custom = [])
{
$addonConfig = get_addon_config('epay');
$config = $addonConfig[$type] ?? $addonConfig['wechat'];
// SDK版本
$version = self::getSdkVersion();
// 处理微信证书路径
if ($type === 'wechat') {
$certFields = ['cert_client', 'cert_key', 'public_key'];
foreach ($certFields as $field) {
self::processAddonsPath($config, $field);
}
}
// 处理支付宝证书路径
if ($type === 'alipay') {
$config['signtype'] = $config['signtype'] ?? 'publickey';
if ($config['signtype'] == 'cert') {
$certFields = ['app_cert_public_key', 'alipay_root_cert', 'ali_public_key'];
foreach ($certFields as $field) {
self::processAddonsPath($config, $field);
}
} else {
// 如果是普通公钥需要将app_cert_public_key和alipay_root_cert设置为空,不然会导致错误
$config['app_cert_public_key'] = '';
$config['alipay_root_cert'] = '';
}
}
// V3支付
if (self::isVersionV3()) {
if ($type == 'wechat') {
$config['mp_app_id'] = $config['app_id'] ?? '';
$config['app_id'] = $config['appid'] ?? '';
$config['mini_app_id'] = $config['miniapp_id'] ?? '';
$config['combine_mch_id'] = $config['combine_mch_id'] ?? '';
$config['mch_secret_key'] = $config['key_v3'] ?? '';
$config['mch_secret_cert'] = $config['cert_key'];
$config['mch_public_cert_path'] = $config['cert_client'];
// 配置微信支付公钥ID及证书路径
$config['wechat_public_cert_path'] = [
($config['public_key_id'] ?? '') => ($config['public_key'] ?? '')
];
$config['sub_mp_app_id'] = $config['sub_appid'] ?? '';
$config['sub_app_id'] = $config['sub_app_id'] ?? '';
$config['sub_mini_app_id'] = $config['sub_miniapp_id'] ?? '';
$config['sub_mch_id'] = $config['sub_mch_id'] ?? '';
} elseif ($type == 'alipay') {
$config['app_secret_cert'] = $config['private_key'] ?? '';
$config['app_public_cert_path'] = $config['app_cert_public_key'] ?? '';
$config['alipay_public_cert_path'] = $config['ali_public_key'] ?? '';
$config['alipay_root_cert_path'] = $config['alipay_root_cert'] ?? '';
$config['service_provider_id'] = $config['pid'] ?? '';
}
$modeArr = ['normal' => 0, 'dev' => 1, 'service' => 2];
$config['mode'] = $modeArr[$config['mode']] ?? 0;
}
// 日志
if ($config['log']) {
$config['log'] = [
'enable' => true,
'file' => LOG_PATH . 'epaylogs' . DS . $type . '-' . date("Y-m-d") . '.log',
'level' => 'debug'
];
} else {
$config['log'] = [
'enable' => false,
];
}
// GuzzleHttp配置,可选
$config['http'] = [
'timeout' => 10,
'connect_timeout' => 10,
// 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
];
$config['notify_url'] = empty($config['notify_url']) ? addon_url('epay/api/notifyx', [], false) . '/type/' . $type : $config['notify_url'];
$config['notify_url'] = !preg_match("/^(http:\/\/|https:\/\/)/i", $config['notify_url']) ? request()->root(true) . $config['notify_url'] : $config['notify_url'];
$config['return_url'] = empty($config['return_url']) ? addon_url('epay/api/returnx', [], false) . '/type/' . $type : $config['return_url'];
$config['return_url'] = !preg_match("/^(http:\/\/|https:\/\/)/i", $config['return_url']) ? request()->root(true) . $config['return_url'] : $config['return_url'];
//合并自定义配置
$config = array_merge($config, $custom);
//v3版本时返回的结构不同
if (self::isVersionV3()) {
$config = [$type => ['default' => $config], 'logger' => $config['log'], 'http' => $config['http'], '_force' => true];
}
return $config;
}
/**
* 获取微信Openid
*
* @param array $custom 自定义配置信息
* @return mixed|string
*/
public static function getOpenid($custom = [])
{
$openid = '';
$auth = Auth::instance();
if ($auth->isLogin()) {
$third = get_addon_info('third');
if ($third && $third['state']) {
$thirdInfo = Third::where('user_id', $auth->id)->where('platform', 'wechat')->where('apptype', 'mp')->find();
$openid = $thirdInfo ? $thirdInfo['openid'] : '';
}
}
if (!$openid) {
$openid = Session::get("openid");
//如果未传openid,则去读取openid
if (!$openid) {
$addonConfig = get_addon_config('epay');
$wechat = new Wechat($custom['app_id'] ?? $addonConfig['wechat']['app_id'], $custom['app_secret'] ?? $addonConfig['wechat']['app_secret']);
$openid = $wechat->getOpenid();
}
}
return $openid;
}
/**
* 获取SDK版本
* @return mixed|string
*/
public static function getSdkVersion()
{
$addonConfig = get_addon_config('epay');
return $addonConfig['version'] ?? self::SDK_VERSION_V2;
}
/**
* 判断是否V2支付
* @return bool
*/
public static function isVersionV2()
{
return self::getSdkVersion() === self::SDK_VERSION_V2;
}
/**
* 判断是否V3支付
* @return bool
*/
public static function isVersionV3()
{
return self::getSdkVersion() === self::SDK_VERSION_V3;
}
}