Skip to content

06 支付网关

架构

前台选支付方式 → PaymentService::pay()
    → GatewayInterface::pay() → 跳转/二维码
支付平台回调 → /api/notify/callback → GatewayInterface::notify()
    → InvoiceService::markPaidByNum()

配置表:kd_payment_gateways(每行一个网关实例,含 driver + config JSON)


内置驱动(4 个)

driver说明
official_alipay_h5AlipayH5Gateway支付宝 H5
official_wechat_h5WechatH5Gateway微信 H5
epayEpayGateway易支付协议
codepayCodepayGateway码支付

代码:app/common/gateway/driver/


插件驱动(3 个)

安装 gateway 插件后,添加网关时 driver 选 plugin:插件目录名

插件driver说明
payjsplugin:payjsPayJS 微信
vmqplugin:vmqV免签
xunhupayplugin:xunhupay虎皮椒

开发 gateway 插件

  1. 创建 public/plugins/gateway/my_pay/MyPay.php
  2. 继承 app\common\lib\GatewayPlugin
  3. 实现 GatewayInterface 全部方法
php
namespace gateway\my_pay;

use app\common\lib\GatewayPlugin;
use app\common\gateway\PayResult;
use app\common\gateway\NotifyResult;
use app\common\gateway\GatewayException;

class MyPay extends GatewayPlugin
{
    public function name(): string { return 'my_pay'; }
    public function title(): string { return '我的支付'; }

    public function configFields(): array
    {
        return [
            ['name' => 'api_key', 'label' => '密钥', 'type' => 'password', 'required' => true],
        ];
    }

    public function pay(array $invoice, array $config, array $urls): PayResult
    {
        // 失败必须 throw GatewayException
        return PayResult::redirect('https://pay.example.com/...');
    }

    public function notify(array $params, array $config): NotifyResult
    {
        // 验签失败 throw GatewayException
        return new NotifyResult(
            outTradeNo: $invoiceNum,
            transactionId: $txnId,
            amount: 99.00,
        );
    }

    public function notifySuccessResponse(): string
    {
        return 'success';
    }
}

约定

  • $invoice['invoice_num'] 为商户订单号
  • $urls['notify'] / $urls['return'] 由系统生成
  • 验签失败抛 GatewayException,错误码会记录日志

后台配置流程

  1. 系统 → 支付网关 → 添加
  2. 选择驱动(内置或 plugin:xxx)
  3. 填写 config 字段
  4. 启用后前台可见

下一章:07-实名认证

KeDe Finance · 纯 PHP 自研财务系统