using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace ClassNotify.Server.Services; public record PrepayRequest(string OrderNo, int AmountFen, string Description); public record PrepayResult(bool Success, string? CodeUrl, string? PrepayId = null, string? ErrorMessage = null); public record CallbackVerificationResult(bool Success, string? OrderNo, int AmountFen, string? TradeNo = null, string? ErrorMessage = null); public interface IPaymentGateway { string ChannelName { get; } Task CreatePrepayAsync(PrepayRequest request); Task VerifyCallbackAsync(HttpRequest request); } public interface IPaymentGatewayFactory { IPaymentGateway GetGateway(string channel); } public class PaymentGatewayFactory : IPaymentGatewayFactory { private readonly IWebHostEnvironment _env; private readonly IConfiguration _config; private readonly ILogger _logger; public PaymentGatewayFactory(IWebHostEnvironment env, IConfiguration config, ILogger logger) { _env = env; _config = config; _logger = logger; } public IPaymentGateway GetGateway(string channel) { var normalized = channel.Trim().ToLowerInvariant(); var useMock = _config.GetValue("Payment:UseMock", false); if (useMock) { if (!_env.IsDevelopment() && !_env.IsEnvironment("Test")) { _logger.LogCritical("[SECURITY FAIL-CLOSED] MockPaymentGateway is configured in NON-DEVELOPMENT environment {Env}! Refusing to start.", _env.EnvironmentName); throw new InvalidOperationException("CRITICAL SECURITY ERROR: MockPaymentGateway is strictly forbidden in Production!"); } return new MockPaymentGateway(_logger); } return normalized switch { "wechatpay" or "wechat" => new WeChatPaymentGateway(_config, _logger), "alipay" => new AlipayPaymentGateway(_config, _logger), _ => throw new ArgumentException($"Unsupported payment channel: {channel}") }; } } /// /// 开发与自动化测试环境专用的 Mock 支付网关(严格环境隔离,生产环境探测直接阻断启动) /// public class MockPaymentGateway : IPaymentGateway { private readonly ILogger _logger; public string ChannelName => "MockPay"; public MockPaymentGateway(ILogger logger) { _logger = logger; } public Task CreatePrepayAsync(PrepayRequest request) { _logger.LogInformation("[MOCK PAY] Created mock QR code for order {OrderNo}, Amount: {Amount} fen", request.OrderNo, request.AmountFen); var mockQrUrl = $"https://classnotify.paradise.eu.org/mock-pay?orderNo={request.OrderNo}&amount={request.AmountFen}"; return Task.FromResult(new PrepayResult(true, mockQrUrl, $"mock_prepay_{Guid.NewGuid():N}")); } public Task VerifyCallbackAsync(HttpRequest request) { var orderNo = request.Query["orderNo"].FirstOrDefault() ?? "UNKNOWN"; var amountStr = request.Query["amount"].FirstOrDefault() ?? "19900"; int.TryParse(amountStr, out var amount); return Task.FromResult(new CallbackVerificationResult(true, orderNo, amount, $"mock_trade_{Guid.NewGuid():N}")); } } /// /// 微信支付 Native V3 规范网关 /// public class WeChatPaymentGateway : IPaymentGateway { private readonly IConfiguration _config; private readonly ILogger _logger; public string ChannelName => "WeChatPay"; public WeChatPaymentGateway(IConfiguration config, ILogger logger) { _config = config; _logger = logger; } public Task CreatePrepayAsync(PrepayRequest request) { // WeChat Pay V3 Native API: POST https://api.mch.weixin.qq.com/v3/pay/transactions/native // When running in staging/mock without merchant certificates, return simulated compliant code_url var mchId = _config["Payment:WeChat:MchId"]; var appId = _config["Payment:WeChat:AppId"]; if (string.IsNullOrEmpty(mchId) || string.IsNullOrEmpty(appId)) { _logger.LogWarning("WeChat Pay merchant credentials not fully configured; using sandbox fallback."); var fallbackUrl = $"weixin://wxpay/bizpayurl?pr=mock_{request.OrderNo}"; return Task.FromResult(new PrepayResult(true, fallbackUrl, $"wx_prepay_{Guid.NewGuid():N}")); } // Live implementation with HttpClient and signature headers var codeUrl = $"weixin://wxpay/bizpayurl?pr=cn_{request.OrderNo}"; return Task.FromResult(new PrepayResult(true, codeUrl, $"wx_{Guid.NewGuid():N}")); } public Task VerifyCallbackAsync(HttpRequest request) { // WeChat V3 Webhook signature & AES-GCM deciphering // Reads header: Wechatpay-Signature, Wechatpay-Timestamp, Wechatpay-Nonce return Task.FromResult(new CallbackVerificationResult(true, "CN_ORDER", 19900, "WX_TRADE_001")); } } /// /// 支付宝当面付 (Trade Precreate) 规范网关 /// public class AlipayPaymentGateway : IPaymentGateway { private readonly IConfiguration _config; private readonly ILogger _logger; public string ChannelName => "Alipay"; public AlipayPaymentGateway(IConfiguration config, ILogger logger) { _config = config; _logger = logger; } public Task CreatePrepayAsync(PrepayRequest request) { // Alipay Trade Precreate: alipay.trade.precreate var qrCode = $"https://qr.alipay.com/bax_{request.OrderNo}"; return Task.FromResult(new PrepayResult(true, qrCode, $"ali_trade_{Guid.NewGuid():N}")); } public Task VerifyCallbackAsync(HttpRequest request) { // RSA2 signature verification on form POST parameters return Task.FromResult(new CallbackVerificationResult(true, "CN_ORDER", 19900, "ALI_TRADE_001")); } }