n/programu/Mike-Leone · 6 个月前
注册 登录
n/program · 6 个月前 · 524 次浏览
u/Mike-Leone钻石
红包

Fossbilling 易支付插件(不确定能用)

有没有哪位MJJ帮我测试一下,我的测试站以前删了,非常感谢
命名为Epay.php放到网站根目录/library/Payment/Adapter即可,有问题联系我
:xhj16:

<?php
/**
 * Copyright 2022-2025 FOSSBilling
 * Copyright 2011-2021 BoxBilling, Inc.
 * SPDX-License-Identifier: Apache-2.0.
 *
 * @copyright FOSSBilling (https://www.fossbilling.org)
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 */

/**
 * 易支付网关适配器。
 * 仅支持一次性付款,不支持订阅续费。
 */
class Payment_Adapter_Epay extends Payment_AdapterAbstract implements FOSSBilling\InjectionAwareInterface
{
    protected ?Pimple\Container $di = null;

    public function __construct(private $config)
    {
        // 检查易支付网关的基础配置是否齐全。
        foreach (['pid', 'key', 'api_url'] as $required) {
            if (empty($this->config[$required])) {
                throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'Epay', ':missing' => $required], 4001);
            }
        }
    }

    public function setDi(Pimple\Container $di): void
    {
        $this->di = $di;
    }

    public function getDi(): ?Pimple\Container
    {
        return $this->di;
    }

    public static function getConfig()
    {
        return [
            'supports_one_time_payments' => true,
            'supports_subscriptions' => false,
            'description' => 'Epay gateway for one-time invoice payments using redirect checkout and async notification.',
            'logo' => [
                'logo' => 'epay.png',
                'height' => '25px',
                'width' => '85px',
            ],
            'form' => [
                'pid' => [
                    'text',
                    [
                        'label' => 'Epay merchant PID',
                    ],
                ],
                'key' => [
                    'text',
                    [
                        'label' => 'Epay merchant key',
                    ],
                ],
                'api_url' => [
                    'text',
                    [
                        'label' => 'Epay API base URL',
                    ],
                ],
                'type' => [
                    'text',
                    [
                        'label' => 'Default payment type code',
                    ],
                ],
            ],
        ];
    }

    public function getHtml($api_admin, $invoice_id, $subscription)
    {
        // 订阅模式不走易支付,直接拒绝。
        if ($subscription) {
            throw new Payment_Exception('Epay gateway does not support subscriptions');
        }

        // 读取发票信息,拼装易支付下单参数。
        $invoice = $api_admin->invoice_get(['id' => $invoice_id]);
        $title = $this->getInvoiceTitle($invoice);
        $orderNo = sprintf('FB%s', $invoice['id']);
        $amount = $this->moneyFormat($invoice['subtotal'] + $invoice['tax'], $invoice['currency']);
        $notifyUrl = $this->config['notify_url'];
        $returnUrl = $this->config['thankyou_url'];
        // 默认支付类型,后台可覆盖。
        $type = $this->config['type'] ?? 'alipay';

        $params = [
            'pid' => $this->config['pid'],
            'type' => $type,
            'out_trade_no' => $orderNo,
            'notify_url' => $notifyUrl,
            'return_url' => $returnUrl,
            'name' => $title,
            'money' => $amount,
        ];

        // 生成易支付 MD5 签名。
        $params['sign'] = $this->sign($params);
        $params['sign_type'] = 'MD5';

        // 输出自动提交表单,跳转到易支付收银台。
        return $this->_generateForm($this->buildPayUrl(), $params);
    }

    public function processTransaction($api_admin, $id, $data, $gateway_id)
    {
        // 只处理回调中的 GET 参数。
        $request = $data['get'] ?? [];
        if (!$this->verifySign($request)) {
            throw new Payment_Exception('Epay signature is invalid');
        }

        // 只有交易成功才入账。
        $tradeStatus = $request['trade_status'] ?? '';
        if ($tradeStatus !== 'TRADE_SUCCESS') {
            return;
        }

        $tx = $api_admin->invoice_transaction_get(['id' => $id]);
        // 如果交易还没绑定发票,则尝试从商户订单号中解析。
        if (!$tx['invoice_id'] && isset($request['out_trade_no'])) {
            $invoiceId = $this->extractInvoiceId($request['out_trade_no']);
            if ($invoiceId) {
                $api_admin->invoice_transaction_update(['id' => $id, 'invoice_id' => $invoiceId]);
                $tx['invoice_id'] = $invoiceId;
            }
        }

        // 记录易支付流水号。
        if (!$tx['txn_id'] && isset($request['trade_no'])) {
            $api_admin->invoice_transaction_update(['id' => $id, 'txn_id' => $request['trade_no']]);
        }

        // 记录支付金额。
        if (!$tx['amount'] && isset($request['money'])) {
            $api_admin->invoice_transaction_update(['id' => $id, 'amount' => $request['money']]);
        }

        // 记录币种,便于后续对账。
        if (!$tx['currency'] && $tx['invoice_id']) {
            $invoice = $api_admin->invoice_get(['id' => $tx['invoice_id']]);
            $api_admin->invoice_transaction_update(['id' => $id, 'currency' => $invoice['currency']]);
        }

        $invoice = $api_admin->invoice_get(['id' => $tx['invoice_id']]);
        $clientId = $invoice['client']['id'];
        $invoiceTotal = $this->moneyFormat($invoice['subtotal'] + $invoice['tax'], $invoice['currency']);
        $paidAmount = $request['money'] ?? $invoiceTotal;

        // 金额不一致时拒绝入账,避免被篡改回调。
        if (!isset($request['money']) || (string) $paidAmount !== (string) $invoiceTotal) {
            throw new Payment_Exception('Invoice amount mismatch');
        }

        // 防止同一笔成功交易被重复处理。
        if ($this->isDuplicate($request['trade_no'] ?? '', $request['trade_status'] ?? '', $paidAmount)) {
            throw new Payment_Exception('Cannot process duplicate transaction');
        }

        $bd = [
            'id' => $clientId,
            'amount' => $paidAmount,
            'description' => 'Epay transaction ' . ($request['trade_no'] ?? ''),
            'type' => 'Epay',
            'rel_id' => $request['trade_no'] ?? '',
        ];

        // 给客户加款并自动支付对应发票。
        $api_admin->client_balance_add_funds($bd);
        $api_admin->invoice_pay_with_credits(['id' => $tx['invoice_id']]);
    }

    private function buildPayUrl(): string
    {
        // 易支付下单地址,按文档默认指向 submit.php。
        return rtrim((string) $this->config['api_url'], '/') . '/submit.php';
    }

    private function sign(array $params): string
    {
        // 参数按字母排序,再拼接成 query string 风格签名串。
        ksort($params);
        $filtered = [];
        foreach ($params as $key => $value) {
            if ($value === '' || $value === null || $key === 'sign' || $key === 'sign_type') {
                continue;
            }
            $filtered[] = $key . '=' . $value;
        }

        // 最后拼接商户密钥并做 MD5。
        return md5(implode('&', $filtered) . $this->config['key']);
    }

    private function verifySign(array $params): bool
    {
        if (empty($params['sign'])) {
            return false;
        }

        $sign = $params['sign'];
        unset($params['sign'], $params['sign_type']);

        return strtoupper($sign) === strtoupper($this->sign($params));
    }

    private function extractInvoiceId(string $outTradeNo): ?int
    {
        // 我们下单时用 FB + 发票ID 作为商户订单号,这里反向解析回来。
        if (preg_match('/^(?:FB)?(\d+)$/', $outTradeNo, $matches)) {
            return (int) $matches[1];
        }

        return null;
    }

    private function isDuplicate(string $tradeNo, string $tradeStatus, string|float $money): bool
    {
        if (!$this->di) {
            return false;
        }

        // 通过流水号、状态和金额组合做重复判断。
        $sql = 'SELECT id FROM transaction WHERE txn_id = :trade_no AND txn_status = :trade_status AND amount = :amount LIMIT 2';
        $rows = $this->di['db']->getAll($sql, [
            ':trade_no' => $tradeNo,
            ':trade_status' => $tradeStatus,
            ':amount' => $money,
        ]);

        return count($rows) > 1;
    }
}
0
15
登录后参与讨论。
u/deleted 广告
海外原生IP VPS,稳定访问全球网络

还在为IP不纯、平台风控、频繁验证而烦恼? 丽萨主机海外原生IP VPS,双ISP住宅IP,覆盖美国、香港、日本、新加坡、台湾、德国、越南、英国等热门地区,适合跨境电商、社媒运营、AI工具、流媒体及海外业务使用。

lisahost.com 了解更多

15 条回复

排序
  1. GeorgeXie 💬 钻石 不离不弃 6 个月前

    来看看

    4
  2. xingyun1000 黄金 6 个月前

    这个有啥用 现在我还没有主机

    0
  3. Dudu007 钻石 6 个月前

    感谢分享👍

    0
  4. Gill007 💬 钻石 2 YEARS 6 个月前

    路过,领个红包

    0
  5. feijiao 黄金 6 个月前

    虽然看不懂,但是路过帮忙顶一下

    0
  6. nannango56 白银 6 个月前

    没有 fossbilling, 但是偷个红包 (六百六十六, 给一个啊)

    0
  7. nodec 黄金 6 个月前

    路过帮忙顶一下

    0
  8. linxone2895 黄金 6 个月前

    路过,领个红包!

    0
  9. user68 💬 铂金 3 YEARS 6 个月前

    路过帮忙顶一下!

    0
  10. M2026 💬 铂金 2 YEARS 6 个月前

    路过,领个红包!

    0
  11. supers 王者 王者会员 6 个月前

    你自己不是有 fossbilling 吗

    0
  12. Mike-Leone 钻石 楼主 指导顾问 6 个月前

    上文有提:删掉了

    0
  13. liuping 黄金 6 个月前

    我瞅瞅怎么个事儿

    0
  14. Arvin_Leung 王者 3 YEARS 6 个月前

    来晚了,没红包领了。

    0
  15. trial 钻石 钻石会员 6 个月前

    纯了解一下也好

    0