mirror of
https://gitee.com/wanwujie/sub2api
synced 2026-05-04 21:20:51 +08:00
refactor(payment): code standards fixes and regression repairs
Backend: - Split payment_order.go (546→314 lines) into payment_order_lifecycle.go - Replace magic strings with constants in factory, easypay, webhook handler - Add rate limit/validity unit constants in payment_order_lifecycle, payment_service - Fix critical regression: add PaymentEnabled to GetPublicSettings response - Add missing migration 099_fix_migrated_purchase_menu_label_icon.sql Frontend: - Fix StripePopupView.vue: replace `as any` with typed interface, use extractApiErrorMessage - Fix AdminOrderTable.vue: replace hardcoded column labels with i18n t() calls - Fix SubscriptionsView.vue: replace hardcoded Today/Tomorrow with i18n - Extract duplicate statusBadgeClass/canRefund/formatOrderDateTime to orderUtils.ts - Add missing i18n keys: common.today, common.tomorrow, payment.orders.orderType/actions - Remove dead PurchaseSubscriptionView.vue (replaced by PaymentView)
This commit is contained in:
@@ -137,13 +137,19 @@ type wxpaySuccessResponse struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// WeChat Pay webhook success response constants.
|
||||
const (
|
||||
wxpaySuccessCode = "SUCCESS"
|
||||
wxpaySuccessMessage = "成功"
|
||||
)
|
||||
|
||||
// writeSuccessResponse sends the provider-specific success response.
|
||||
// WeChat Pay requires JSON {"code":"SUCCESS","message":"成功"};
|
||||
// Stripe expects an empty 200; others accept plain text "success".
|
||||
func writeSuccessResponse(c *gin.Context, providerKey string) {
|
||||
switch providerKey {
|
||||
case payment.TypeWxpay:
|
||||
c.JSON(http.StatusOK, wxpaySuccessResponse{Code: "SUCCESS", Message: "成功"})
|
||||
c.JSON(http.StatusOK, wxpaySuccessResponse{Code: wxpaySuccessCode, Message: wxpaySuccessMessage})
|
||||
case payment.TypeStripe:
|
||||
c.String(http.StatusOK, "")
|
||||
default:
|
||||
|
||||
@@ -57,6 +57,7 @@ func (h *SettingHandler) GetPublicSettings(c *gin.Context) {
|
||||
OIDCOAuthEnabled: settings.OIDCOAuthEnabled,
|
||||
OIDCOAuthProviderName: settings.OIDCOAuthProviderName,
|
||||
BackendModeEnabled: settings.BackendModeEnabled,
|
||||
PaymentEnabled: settings.PaymentEnabled,
|
||||
Version: h.version,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ const (
|
||||
maxEasypayResponseSize = 1 << 20 // 1MB
|
||||
tradeStatusSuccess = "TRADE_SUCCESS"
|
||||
signTypeMD5 = "MD5"
|
||||
paymentModePopup = "popup"
|
||||
deviceMobile = "mobile"
|
||||
)
|
||||
|
||||
// EasyPay implements payment.Provider for the EasyPay aggregation platform.
|
||||
@@ -61,7 +63,7 @@ func (e *EasyPay) CreatePayment(ctx context.Context, req payment.CreatePaymentRe
|
||||
// Payment mode determined by instance config, not payment type.
|
||||
// "popup" → hosted page (submit.php); "qrcode"/default → API call (mapi.php).
|
||||
mode := e.config["paymentMode"]
|
||||
if mode == "popup" {
|
||||
if mode == paymentModePopup {
|
||||
return e.createRedirectPayment(req)
|
||||
}
|
||||
return e.createAPIPayment(ctx, req)
|
||||
@@ -106,7 +108,7 @@ func (e *EasyPay) createAPIPayment(ctx context.Context, req payment.CreatePaymen
|
||||
params["cid"] = cid
|
||||
}
|
||||
if req.IsMobile {
|
||||
params["device"] = "mobile"
|
||||
params["device"] = deviceMobile
|
||||
}
|
||||
params["sign"] = easyPaySign(params, e.config["pkey"])
|
||||
params["sign_type"] = signTypeMD5
|
||||
|
||||
@@ -9,13 +9,13 @@ import (
|
||||
// CreateProvider creates a Provider from a provider key, instance ID and decrypted config.
|
||||
func CreateProvider(providerKey string, instanceID string, config map[string]string) (payment.Provider, error) {
|
||||
switch providerKey {
|
||||
case "easypay":
|
||||
case payment.TypeEasyPay:
|
||||
return NewEasyPay(instanceID, config)
|
||||
case "alipay":
|
||||
case payment.TypeAlipay:
|
||||
return NewAlipay(instanceID, config)
|
||||
case "wxpay":
|
||||
case payment.TypeWxpay:
|
||||
return NewWxpay(instanceID, config)
|
||||
case "stripe":
|
||||
case payment.TypeStripe:
|
||||
return NewStripe(instanceID, config)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown provider key: %s", providerKey)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/paymentauditlog"
|
||||
"github.com/Wei-Shaw/sub2api/ent/paymentorder"
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment/provider"
|
||||
@@ -170,68 +169,6 @@ func (s *PaymentService) checkPendingLimit(ctx context.Context, tx *dbent.Tx, us
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PaymentService) checkCancelRateLimit(ctx context.Context, userID int64, cfg *PaymentConfig) error {
|
||||
if !cfg.CancelRateLimitEnabled || cfg.CancelRateLimitMax <= 0 {
|
||||
return nil
|
||||
}
|
||||
windowStart := cancelRateLimitWindowStart(cfg)
|
||||
operator := fmt.Sprintf("user:%d", userID)
|
||||
count, err := s.entClient.PaymentAuditLog.Query().
|
||||
Where(
|
||||
paymentauditlog.ActionEQ("ORDER_CANCELLED"),
|
||||
paymentauditlog.OperatorEQ(operator),
|
||||
paymentauditlog.CreatedAtGTE(windowStart),
|
||||
).Count(ctx)
|
||||
if err != nil {
|
||||
slog.Error("check cancel rate limit failed", "userID", userID, "error", err)
|
||||
return nil // fail open
|
||||
}
|
||||
if count >= cfg.CancelRateLimitMax {
|
||||
return infraerrors.TooManyRequests("CANCEL_RATE_LIMITED", "cancel rate limited").
|
||||
WithMetadata(map[string]string{
|
||||
"max": strconv.Itoa(cfg.CancelRateLimitMax),
|
||||
"window": strconv.Itoa(cfg.CancelRateLimitWindow),
|
||||
"unit": cfg.CancelRateLimitUnit,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cancelRateLimitWindowStart(cfg *PaymentConfig) time.Time {
|
||||
now := time.Now()
|
||||
w := cfg.CancelRateLimitWindow
|
||||
if w <= 0 {
|
||||
w = 1
|
||||
}
|
||||
unit := cfg.CancelRateLimitUnit
|
||||
if unit == "" {
|
||||
unit = "day"
|
||||
}
|
||||
if cfg.CancelRateLimitMode == "fixed" {
|
||||
switch unit {
|
||||
case "minute":
|
||||
t := now.Truncate(time.Minute)
|
||||
return t.Add(-time.Duration(w-1) * time.Minute)
|
||||
case "day":
|
||||
y, m, d := now.Date()
|
||||
t := time.Date(y, m, d, 0, 0, 0, 0, now.Location())
|
||||
return t.AddDate(0, 0, -(w - 1))
|
||||
default: // hour
|
||||
t := now.Truncate(time.Hour)
|
||||
return t.Add(-time.Duration(w-1) * time.Hour)
|
||||
}
|
||||
}
|
||||
// rolling window
|
||||
switch unit {
|
||||
case "minute":
|
||||
return now.Add(-time.Duration(w) * time.Minute)
|
||||
case "day":
|
||||
return now.AddDate(0, 0, -w)
|
||||
default: // hour
|
||||
return now.Add(-time.Duration(w) * time.Hour)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PaymentService) checkDailyLimit(ctx context.Context, tx *dbent.Tx, userID int64, amount, limit float64) error {
|
||||
if limit <= 0 {
|
||||
return nil
|
||||
@@ -375,172 +312,3 @@ func (s *PaymentService) AdminListOrders(ctx context.Context, userID int64, p Or
|
||||
}
|
||||
return orders, total, nil
|
||||
}
|
||||
|
||||
// --- Cancel & Expire ---
|
||||
|
||||
func (s *PaymentService) CancelOrder(ctx context.Context, orderID, userID int64) (string, error) {
|
||||
o, err := s.entClient.PaymentOrder.Get(ctx, orderID)
|
||||
if err != nil {
|
||||
return "", infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.UserID != userID {
|
||||
return "", infraerrors.Forbidden("FORBIDDEN", "no permission for this order")
|
||||
}
|
||||
if o.Status != OrderStatusPending {
|
||||
return "", infraerrors.BadRequest("INVALID_STATUS", "order cannot be cancelled in current status")
|
||||
}
|
||||
return s.cancelCore(ctx, o, OrderStatusCancelled, fmt.Sprintf("user:%d", userID), "user cancelled order")
|
||||
}
|
||||
|
||||
func (s *PaymentService) AdminCancelOrder(ctx context.Context, orderID int64) (string, error) {
|
||||
o, err := s.entClient.PaymentOrder.Get(ctx, orderID)
|
||||
if err != nil {
|
||||
return "", infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.Status != OrderStatusPending {
|
||||
return "", infraerrors.BadRequest("INVALID_STATUS", "order cannot be cancelled in current status")
|
||||
}
|
||||
return s.cancelCore(ctx, o, OrderStatusCancelled, "admin", "admin cancelled order")
|
||||
}
|
||||
|
||||
func (s *PaymentService) cancelCore(ctx context.Context, o *dbent.PaymentOrder, fs, op, ad string) (string, error) {
|
||||
if o.PaymentTradeNo != "" || o.PaymentType != "" {
|
||||
if s.checkPaid(ctx, o) == "already_paid" {
|
||||
return "already_paid", nil
|
||||
}
|
||||
}
|
||||
c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(o.ID), paymentorder.StatusEQ(OrderStatusPending)).SetStatus(fs).Save(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("update order status: %w", err)
|
||||
}
|
||||
if c > 0 {
|
||||
auditAction := "ORDER_CANCELLED"
|
||||
if fs == OrderStatusExpired {
|
||||
auditAction = "ORDER_EXPIRED"
|
||||
}
|
||||
s.writeAuditLog(ctx, o.ID, auditAction, op, map[string]any{"detail": ad})
|
||||
}
|
||||
return "cancelled", nil
|
||||
}
|
||||
|
||||
func (s *PaymentService) checkPaid(ctx context.Context, o *dbent.PaymentOrder) string {
|
||||
prov, err := s.getOrderProvider(ctx, o)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
// Use OutTradeNo as fallback when PaymentTradeNo is empty
|
||||
// (e.g. EasyPay popup mode where trade_no arrives only via notify callback)
|
||||
tradeNo := o.PaymentTradeNo
|
||||
if tradeNo == "" {
|
||||
tradeNo = o.OutTradeNo
|
||||
}
|
||||
resp, err := prov.QueryOrder(ctx, tradeNo)
|
||||
if err != nil {
|
||||
slog.Warn("query upstream failed", "orderID", o.ID, "error", err)
|
||||
return ""
|
||||
}
|
||||
if resp.Status == payment.ProviderStatusPaid {
|
||||
if err := s.HandlePaymentNotification(ctx, &payment.PaymentNotification{TradeNo: o.PaymentTradeNo, OrderID: o.OutTradeNo, Amount: resp.Amount, Status: payment.ProviderStatusSuccess}, prov.ProviderKey()); err != nil {
|
||||
slog.Error("fulfillment failed during checkPaid", "orderID", o.ID, "error", err)
|
||||
// Still return already_paid — order was paid, fulfillment can be retried
|
||||
}
|
||||
return "already_paid"
|
||||
}
|
||||
if cp, ok := prov.(payment.CancelableProvider); ok {
|
||||
_ = cp.CancelPayment(ctx, tradeNo)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// VerifyOrderByOutTradeNo actively queries the upstream provider to check
|
||||
// if a payment was made, and processes it if so. This handles the case where
|
||||
// the provider's notify callback was missed (e.g. EasyPay popup mode).
|
||||
func (s *PaymentService) VerifyOrderByOutTradeNo(ctx context.Context, outTradeNo string, userID int64) (*dbent.PaymentOrder, error) {
|
||||
o, err := s.entClient.PaymentOrder.Query().
|
||||
Where(paymentorder.OutTradeNo(outTradeNo)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.UserID != userID {
|
||||
return nil, infraerrors.Forbidden("FORBIDDEN", "no permission for this order")
|
||||
}
|
||||
// Only verify orders that are still pending or recently expired
|
||||
if o.Status == OrderStatusPending || o.Status == OrderStatusExpired {
|
||||
result := s.checkPaid(ctx, o)
|
||||
if result == "already_paid" {
|
||||
// Reload order to get updated status
|
||||
o, err = s.entClient.PaymentOrder.Get(ctx, o.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reload order: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// VerifyOrderPublic verifies payment status without user authentication.
|
||||
// Used by the payment result page when the user's session has expired.
|
||||
func (s *PaymentService) VerifyOrderPublic(ctx context.Context, outTradeNo string) (*dbent.PaymentOrder, error) {
|
||||
o, err := s.entClient.PaymentOrder.Query().
|
||||
Where(paymentorder.OutTradeNo(outTradeNo)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.Status == OrderStatusPending || o.Status == OrderStatusExpired {
|
||||
result := s.checkPaid(ctx, o)
|
||||
if result == "already_paid" {
|
||||
o, err = s.entClient.PaymentOrder.Get(ctx, o.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reload order: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
func (s *PaymentService) ExpireTimedOutOrders(ctx context.Context) (int, error) {
|
||||
now := time.Now()
|
||||
orders, err := s.entClient.PaymentOrder.Query().Where(paymentorder.StatusEQ(OrderStatusPending), paymentorder.ExpiresAtLTE(now)).All(ctx)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("query expired: %w", err)
|
||||
}
|
||||
n := 0
|
||||
for _, o := range orders {
|
||||
// Check upstream payment status before expiring — the user may have
|
||||
// paid just before timeout and the webhook hasn't arrived yet.
|
||||
outcome, _ := s.cancelCore(ctx, o, OrderStatusExpired, "system", "order expired")
|
||||
if outcome == "already_paid" {
|
||||
slog.Info("order was paid during expiry", "orderID", o.ID)
|
||||
continue
|
||||
}
|
||||
if outcome != "" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// getOrderProvider creates a provider using the order's original instance config.
|
||||
// Falls back to registry lookup if instance ID is missing (legacy orders).
|
||||
func (s *PaymentService) getOrderProvider(ctx context.Context, o *dbent.PaymentOrder) (payment.Provider, error) {
|
||||
if o.ProviderInstanceID != nil && *o.ProviderInstanceID != "" {
|
||||
instID, err := strconv.ParseInt(*o.ProviderInstanceID, 10, 64)
|
||||
if err == nil {
|
||||
cfg, err := s.loadBalancer.GetInstanceConfig(ctx, instID)
|
||||
if err == nil {
|
||||
providerKey := s.registry.GetProviderKey(o.PaymentType)
|
||||
if providerKey == "" {
|
||||
providerKey = o.PaymentType
|
||||
}
|
||||
p, err := provider.CreateProvider(providerKey, *o.ProviderInstanceID, cfg)
|
||||
if err == nil {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.EnsureProviders(ctx)
|
||||
return s.registry.GetProvider(o.PaymentType)
|
||||
}
|
||||
|
||||
257
backend/internal/service/payment_order_lifecycle.go
Normal file
257
backend/internal/service/payment_order_lifecycle.go
Normal file
@@ -0,0 +1,257 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/paymentauditlog"
|
||||
"github.com/Wei-Shaw/sub2api/ent/paymentorder"
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment/provider"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// --- Cancel & Expire ---
|
||||
|
||||
// Cancel rate limit configuration constants.
|
||||
const (
|
||||
rateLimitUnitDay = "day"
|
||||
rateLimitUnitMinute = "minute"
|
||||
rateLimitUnitHour = "hour"
|
||||
rateLimitModeFixed = "fixed"
|
||||
checkPaidResultAlreadyPaid = "already_paid"
|
||||
checkPaidResultCancelled = "cancelled"
|
||||
)
|
||||
|
||||
func (s *PaymentService) checkCancelRateLimit(ctx context.Context, userID int64, cfg *PaymentConfig) error {
|
||||
if !cfg.CancelRateLimitEnabled || cfg.CancelRateLimitMax <= 0 {
|
||||
return nil
|
||||
}
|
||||
windowStart := cancelRateLimitWindowStart(cfg)
|
||||
operator := fmt.Sprintf("user:%d", userID)
|
||||
count, err := s.entClient.PaymentAuditLog.Query().
|
||||
Where(
|
||||
paymentauditlog.ActionEQ("ORDER_CANCELLED"),
|
||||
paymentauditlog.OperatorEQ(operator),
|
||||
paymentauditlog.CreatedAtGTE(windowStart),
|
||||
).Count(ctx)
|
||||
if err != nil {
|
||||
slog.Error("check cancel rate limit failed", "userID", userID, "error", err)
|
||||
return nil // fail open
|
||||
}
|
||||
if count >= cfg.CancelRateLimitMax {
|
||||
return infraerrors.TooManyRequests("CANCEL_RATE_LIMITED", "cancel rate limited").
|
||||
WithMetadata(map[string]string{
|
||||
"max": strconv.Itoa(cfg.CancelRateLimitMax),
|
||||
"window": strconv.Itoa(cfg.CancelRateLimitWindow),
|
||||
"unit": cfg.CancelRateLimitUnit,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cancelRateLimitWindowStart(cfg *PaymentConfig) time.Time {
|
||||
now := time.Now()
|
||||
w := cfg.CancelRateLimitWindow
|
||||
if w <= 0 {
|
||||
w = 1
|
||||
}
|
||||
unit := cfg.CancelRateLimitUnit
|
||||
if unit == "" {
|
||||
unit = rateLimitUnitDay
|
||||
}
|
||||
if cfg.CancelRateLimitMode == rateLimitModeFixed {
|
||||
switch unit {
|
||||
case rateLimitUnitMinute:
|
||||
t := now.Truncate(time.Minute)
|
||||
return t.Add(-time.Duration(w-1) * time.Minute)
|
||||
case rateLimitUnitDay:
|
||||
y, m, d := now.Date()
|
||||
t := time.Date(y, m, d, 0, 0, 0, 0, now.Location())
|
||||
return t.AddDate(0, 0, -(w - 1))
|
||||
default: // hour
|
||||
t := now.Truncate(time.Hour)
|
||||
return t.Add(-time.Duration(w-1) * time.Hour)
|
||||
}
|
||||
}
|
||||
// rolling window
|
||||
switch unit {
|
||||
case rateLimitUnitMinute:
|
||||
return now.Add(-time.Duration(w) * time.Minute)
|
||||
case rateLimitUnitDay:
|
||||
return now.AddDate(0, 0, -w)
|
||||
default: // hour
|
||||
return now.Add(-time.Duration(w) * time.Hour)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PaymentService) CancelOrder(ctx context.Context, orderID, userID int64) (string, error) {
|
||||
o, err := s.entClient.PaymentOrder.Get(ctx, orderID)
|
||||
if err != nil {
|
||||
return "", infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.UserID != userID {
|
||||
return "", infraerrors.Forbidden("FORBIDDEN", "no permission for this order")
|
||||
}
|
||||
if o.Status != OrderStatusPending {
|
||||
return "", infraerrors.BadRequest("INVALID_STATUS", "order cannot be cancelled in current status")
|
||||
}
|
||||
return s.cancelCore(ctx, o, OrderStatusCancelled, fmt.Sprintf("user:%d", userID), "user cancelled order")
|
||||
}
|
||||
|
||||
func (s *PaymentService) AdminCancelOrder(ctx context.Context, orderID int64) (string, error) {
|
||||
o, err := s.entClient.PaymentOrder.Get(ctx, orderID)
|
||||
if err != nil {
|
||||
return "", infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.Status != OrderStatusPending {
|
||||
return "", infraerrors.BadRequest("INVALID_STATUS", "order cannot be cancelled in current status")
|
||||
}
|
||||
return s.cancelCore(ctx, o, OrderStatusCancelled, "admin", "admin cancelled order")
|
||||
}
|
||||
|
||||
func (s *PaymentService) cancelCore(ctx context.Context, o *dbent.PaymentOrder, fs, op, ad string) (string, error) {
|
||||
if o.PaymentTradeNo != "" || o.PaymentType != "" {
|
||||
if s.checkPaid(ctx, o) == checkPaidResultAlreadyPaid {
|
||||
return checkPaidResultAlreadyPaid, nil
|
||||
}
|
||||
}
|
||||
c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(o.ID), paymentorder.StatusEQ(OrderStatusPending)).SetStatus(fs).Save(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("update order status: %w", err)
|
||||
}
|
||||
if c > 0 {
|
||||
auditAction := "ORDER_CANCELLED"
|
||||
if fs == OrderStatusExpired {
|
||||
auditAction = "ORDER_EXPIRED"
|
||||
}
|
||||
s.writeAuditLog(ctx, o.ID, auditAction, op, map[string]any{"detail": ad})
|
||||
}
|
||||
return checkPaidResultCancelled, nil
|
||||
}
|
||||
|
||||
func (s *PaymentService) checkPaid(ctx context.Context, o *dbent.PaymentOrder) string {
|
||||
prov, err := s.getOrderProvider(ctx, o)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
// Use OutTradeNo as fallback when PaymentTradeNo is empty
|
||||
// (e.g. EasyPay popup mode where trade_no arrives only via notify callback)
|
||||
tradeNo := o.PaymentTradeNo
|
||||
if tradeNo == "" {
|
||||
tradeNo = o.OutTradeNo
|
||||
}
|
||||
resp, err := prov.QueryOrder(ctx, tradeNo)
|
||||
if err != nil {
|
||||
slog.Warn("query upstream failed", "orderID", o.ID, "error", err)
|
||||
return ""
|
||||
}
|
||||
if resp.Status == payment.ProviderStatusPaid {
|
||||
if err := s.HandlePaymentNotification(ctx, &payment.PaymentNotification{TradeNo: o.PaymentTradeNo, OrderID: o.OutTradeNo, Amount: resp.Amount, Status: payment.ProviderStatusSuccess}, prov.ProviderKey()); err != nil {
|
||||
slog.Error("fulfillment failed during checkPaid", "orderID", o.ID, "error", err)
|
||||
// Still return already_paid — order was paid, fulfillment can be retried
|
||||
}
|
||||
return checkPaidResultAlreadyPaid
|
||||
}
|
||||
if cp, ok := prov.(payment.CancelableProvider); ok {
|
||||
_ = cp.CancelPayment(ctx, tradeNo)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// VerifyOrderByOutTradeNo actively queries the upstream provider to check
|
||||
// if a payment was made, and processes it if so. This handles the case where
|
||||
// the provider's notify callback was missed (e.g. EasyPay popup mode).
|
||||
func (s *PaymentService) VerifyOrderByOutTradeNo(ctx context.Context, outTradeNo string, userID int64) (*dbent.PaymentOrder, error) {
|
||||
o, err := s.entClient.PaymentOrder.Query().
|
||||
Where(paymentorder.OutTradeNo(outTradeNo)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.UserID != userID {
|
||||
return nil, infraerrors.Forbidden("FORBIDDEN", "no permission for this order")
|
||||
}
|
||||
// Only verify orders that are still pending or recently expired
|
||||
if o.Status == OrderStatusPending || o.Status == OrderStatusExpired {
|
||||
result := s.checkPaid(ctx, o)
|
||||
if result == checkPaidResultAlreadyPaid {
|
||||
// Reload order to get updated status
|
||||
o, err = s.entClient.PaymentOrder.Get(ctx, o.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reload order: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// VerifyOrderPublic verifies payment status without user authentication.
|
||||
// Used by the payment result page when the user's session has expired.
|
||||
func (s *PaymentService) VerifyOrderPublic(ctx context.Context, outTradeNo string) (*dbent.PaymentOrder, error) {
|
||||
o, err := s.entClient.PaymentOrder.Query().
|
||||
Where(paymentorder.OutTradeNo(outTradeNo)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return nil, infraerrors.NotFound("NOT_FOUND", "order not found")
|
||||
}
|
||||
if o.Status == OrderStatusPending || o.Status == OrderStatusExpired {
|
||||
result := s.checkPaid(ctx, o)
|
||||
if result == checkPaidResultAlreadyPaid {
|
||||
o, err = s.entClient.PaymentOrder.Get(ctx, o.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reload order: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
func (s *PaymentService) ExpireTimedOutOrders(ctx context.Context) (int, error) {
|
||||
now := time.Now()
|
||||
orders, err := s.entClient.PaymentOrder.Query().Where(paymentorder.StatusEQ(OrderStatusPending), paymentorder.ExpiresAtLTE(now)).All(ctx)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("query expired: %w", err)
|
||||
}
|
||||
n := 0
|
||||
for _, o := range orders {
|
||||
// Check upstream payment status before expiring — the user may have
|
||||
// paid just before timeout and the webhook hasn't arrived yet.
|
||||
outcome, _ := s.cancelCore(ctx, o, OrderStatusExpired, "system", "order expired")
|
||||
if outcome == checkPaidResultAlreadyPaid {
|
||||
slog.Info("order was paid during expiry", "orderID", o.ID)
|
||||
continue
|
||||
}
|
||||
if outcome != "" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// getOrderProvider creates a provider using the order's original instance config.
|
||||
// Falls back to registry lookup if instance ID is missing (legacy orders).
|
||||
func (s *PaymentService) getOrderProvider(ctx context.Context, o *dbent.PaymentOrder) (payment.Provider, error) {
|
||||
if o.ProviderInstanceID != nil && *o.ProviderInstanceID != "" {
|
||||
instID, err := strconv.ParseInt(*o.ProviderInstanceID, 10, 64)
|
||||
if err == nil {
|
||||
cfg, err := s.loadBalancer.GetInstanceConfig(ctx, instID)
|
||||
if err == nil {
|
||||
providerKey := s.registry.GetProviderKey(o.PaymentType)
|
||||
if providerKey == "" {
|
||||
providerKey = o.PaymentType
|
||||
}
|
||||
p, err := provider.CreateProvider(providerKey, *o.ProviderInstanceID, cfg)
|
||||
if err == nil {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.EnsureProviders(ctx)
|
||||
return s.registry.GetProvider(o.PaymentType)
|
||||
}
|
||||
@@ -271,11 +271,17 @@ func psSliceContains(sl []string, s string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Subscription validity period unit constants.
|
||||
const (
|
||||
validityUnitWeek = "week"
|
||||
validityUnitMonth = "month"
|
||||
)
|
||||
|
||||
func psComputeValidityDays(days int, unit string) int {
|
||||
switch unit {
|
||||
case "week":
|
||||
case validityUnitWeek:
|
||||
return days * 7
|
||||
case "month":
|
||||
case validityUnitMonth:
|
||||
return days * 30
|
||||
default:
|
||||
return days
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
-- 097_fix_migrated_purchase_menu_label_icon.sql
|
||||
--
|
||||
-- Fixes the custom menu item created by migration 096: updates the label
|
||||
-- from hardcoded English "Purchase" to "充值/订阅", and sets the icon_svg
|
||||
-- to a credit-card SVG matching the sidebar CreditCardIcon.
|
||||
--
|
||||
-- Idempotent: only modifies items where id = 'migrated_purchase_subscription'.
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
v_raw text;
|
||||
v_items jsonb;
|
||||
v_idx int;
|
||||
v_icon text;
|
||||
v_elem jsonb;
|
||||
v_i int := 0;
|
||||
BEGIN
|
||||
SELECT value INTO v_raw
|
||||
FROM settings WHERE key = 'custom_menu_items';
|
||||
|
||||
IF COALESCE(v_raw, '') = '' OR v_raw = 'null' THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
v_items := v_raw::jsonb;
|
||||
|
||||
-- Find the index of the migrated item by iterating the array
|
||||
v_idx := NULL;
|
||||
FOR v_elem IN SELECT jsonb_array_elements(v_items) LOOP
|
||||
IF v_elem ->> 'id' = 'migrated_purchase_subscription' THEN
|
||||
v_idx := v_i;
|
||||
EXIT;
|
||||
END IF;
|
||||
v_i := v_i + 1;
|
||||
END LOOP;
|
||||
|
||||
IF v_idx IS NULL THEN
|
||||
RETURN; -- item not found, nothing to fix
|
||||
END IF;
|
||||
|
||||
-- Credit card SVG (Heroicons outline, matches CreditCardIcon in AppSidebar)
|
||||
v_icon := '<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 8.25h19.5M2.25 9h19.5m-16.5 5.25h6m-6 2.25h3m-3.75 3h15a2.25 2.25 0 002.25-2.25V6.75A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 004.5 19.5z"/></svg>';
|
||||
|
||||
-- Update label and icon_svg
|
||||
v_items := jsonb_set(v_items, ARRAY[v_idx::text, 'label'], '"充值/订阅"'::jsonb);
|
||||
v_items := jsonb_set(v_items, ARRAY[v_idx::text, 'icon_svg'], to_jsonb(v_icon));
|
||||
|
||||
UPDATE settings SET value = v_items::text WHERE key = 'custom_menu_items';
|
||||
|
||||
RAISE NOTICE '[migration-097] Fixed migrated_purchase_subscription: label=充值/订阅, icon=CreditCard SVG';
|
||||
END $$;
|
||||
@@ -113,6 +113,7 @@
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import BaseDialog from '@/components/common/BaseDialog.vue'
|
||||
import type { PaymentOrder } from '@/types/payment'
|
||||
import { statusBadgeClass, canRefund as canRefundStatus, formatOrderDateTime } from '@/components/payment/orderUtils'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -128,22 +129,11 @@ const emit = defineEmits<{
|
||||
(e: 'refund', order: PaymentOrder): void
|
||||
}>()
|
||||
|
||||
function statusBadgeClass(status: string): string {
|
||||
const m: Record<string, string> = {
|
||||
PENDING: 'badge-warning', PAID: 'badge-info', RECHARGING: 'badge-info',
|
||||
COMPLETED: 'badge-success', EXPIRED: 'badge-secondary', CANCELLED: 'badge-secondary',
|
||||
FAILED: 'badge-danger', REFUND_REQUESTED: 'badge-warning', REFUNDING: 'badge-warning',
|
||||
PARTIALLY_REFUNDED: 'badge-warning', REFUNDED: 'badge-info', REFUND_FAILED: 'badge-danger',
|
||||
}
|
||||
return m[status] || 'badge-secondary'
|
||||
}
|
||||
|
||||
function canRefund(order: PaymentOrder): boolean {
|
||||
return ['COMPLETED', 'PARTIALLY_REFUNDED', 'REFUND_REQUESTED', 'REFUND_FAILED'].includes(order.status)
|
||||
return canRefundStatus(order.status)
|
||||
}
|
||||
|
||||
function formatDateTime(dateStr: string): string {
|
||||
if (!dateStr) return '-'
|
||||
return new Date(dateStr).toLocaleString()
|
||||
return formatOrderDateTime(dateStr)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
<span class="text-xs">{{ t('payment.admin.retry') }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="canRefund(row)"
|
||||
v-if="canRefundRow(row)"
|
||||
@click="emit('refund', row)"
|
||||
class="flex flex-col items-center gap-0.5 rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:text-red-400"
|
||||
>
|
||||
@@ -139,6 +139,7 @@ import DataTable from '@/components/common/DataTable.vue'
|
||||
import Pagination from '@/components/common/Pagination.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import { statusBadgeClass, canRefund, formatOrderDateTime } from '@/components/payment/orderUtils'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -179,16 +180,16 @@ function emitFiltersChanged() {
|
||||
})
|
||||
}
|
||||
|
||||
const columns: Column[] = [
|
||||
{ key: 'id', label: 'ID' },
|
||||
{ key: 'user_id', label: 'User' },
|
||||
{ key: 'amount', label: 'Amount' },
|
||||
{ key: 'payment_type', label: 'Method' },
|
||||
{ key: 'status', label: 'Status' },
|
||||
{ key: 'order_type', label: 'Type' },
|
||||
{ key: 'created_at', label: 'Created' },
|
||||
{ key: 'actions', label: 'Actions' },
|
||||
]
|
||||
const columns = computed<Column[]>(() => [
|
||||
{ key: 'id', label: t('payment.orders.orderId') },
|
||||
{ key: 'user_id', label: t('payment.orders.userId') },
|
||||
{ key: 'amount', label: t('payment.orders.amount') },
|
||||
{ key: 'payment_type', label: t('payment.orders.paymentMethod') },
|
||||
{ key: 'status', label: t('payment.orders.status') },
|
||||
{ key: 'order_type', label: t('payment.orders.orderType') },
|
||||
{ key: 'created_at', label: t('payment.orders.createdAt') },
|
||||
{ key: 'actions', label: t('payment.orders.actions') },
|
||||
])
|
||||
|
||||
const statusFilterOptions = computed(() => [
|
||||
{ value: '', label: t('payment.admin.allStatuses') },
|
||||
@@ -216,22 +217,11 @@ const orderTypeFilterOptions = computed(() => [
|
||||
{ value: 'subscription', label: t('payment.admin.subscriptionOrder') },
|
||||
])
|
||||
|
||||
function statusBadgeClass(status: string): string {
|
||||
const m: Record<string, string> = {
|
||||
PENDING: 'badge-warning', PAID: 'badge-info', RECHARGING: 'badge-info',
|
||||
COMPLETED: 'badge-success', EXPIRED: 'badge-secondary', CANCELLED: 'badge-secondary',
|
||||
FAILED: 'badge-danger', REFUND_REQUESTED: 'badge-warning', REFUNDING: 'badge-warning',
|
||||
PARTIALLY_REFUNDED: 'badge-warning', REFUNDED: 'badge-info', REFUND_FAILED: 'badge-danger',
|
||||
}
|
||||
return m[status] || 'badge-secondary'
|
||||
}
|
||||
|
||||
function canRefund(order: PaymentOrder): boolean {
|
||||
return ['COMPLETED', 'PARTIALLY_REFUNDED', 'REFUND_REQUESTED', 'REFUND_FAILED'].includes(order.status)
|
||||
function canRefundRow(order: PaymentOrder): boolean {
|
||||
return canRefund(order.status)
|
||||
}
|
||||
|
||||
function formatDateTime(dateStr: string): string {
|
||||
if (!dateStr) return '-'
|
||||
return new Date(dateStr).toLocaleString()
|
||||
return formatOrderDateTime(dateStr)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -164,6 +164,7 @@ import { reactive, computed, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import BaseDialog from '@/components/common/BaseDialog.vue'
|
||||
import type { PaymentOrder } from '@/types/payment'
|
||||
import { formatOrderDateTime } from '@/components/payment/orderUtils'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -222,8 +223,7 @@ watch(() => props.show, (val) => {
|
||||
})
|
||||
|
||||
function formatDateTime(dateStr: string): string {
|
||||
if (!dateStr) return '-'
|
||||
return new Date(dateStr).toLocaleString()
|
||||
return formatOrderDateTime(dateStr)
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
|
||||
34
frontend/src/components/payment/orderUtils.ts
Normal file
34
frontend/src/components/payment/orderUtils.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Shared utility functions for payment order display.
|
||||
* Used by AdminOrderDetail, AdminOrderTable, AdminRefundDialog, AdminOrdersView, etc.
|
||||
*/
|
||||
|
||||
const STATUS_BADGE_MAP: Record<string, string> = {
|
||||
PENDING: 'badge-warning',
|
||||
PAID: 'badge-info',
|
||||
RECHARGING: 'badge-info',
|
||||
COMPLETED: 'badge-success',
|
||||
EXPIRED: 'badge-secondary',
|
||||
CANCELLED: 'badge-secondary',
|
||||
FAILED: 'badge-danger',
|
||||
REFUND_REQUESTED: 'badge-warning',
|
||||
REFUNDING: 'badge-warning',
|
||||
PARTIALLY_REFUNDED: 'badge-warning',
|
||||
REFUNDED: 'badge-info',
|
||||
REFUND_FAILED: 'badge-danger',
|
||||
}
|
||||
|
||||
const REFUNDABLE_STATUSES = ['COMPLETED', 'PARTIALLY_REFUNDED', 'REFUND_REQUESTED', 'REFUND_FAILED']
|
||||
|
||||
export function statusBadgeClass(status: string): string {
|
||||
return STATUS_BADGE_MAP[status] || 'badge-secondary'
|
||||
}
|
||||
|
||||
export function canRefund(status: string): boolean {
|
||||
return REFUNDABLE_STATUSES.includes(status)
|
||||
}
|
||||
|
||||
export function formatOrderDateTime(dateStr: string): string {
|
||||
if (!dateStr) return '-'
|
||||
return new Date(dateStr).toLocaleString()
|
||||
}
|
||||
@@ -308,6 +308,8 @@ export default {
|
||||
chooseFile: 'Choose File',
|
||||
notAvailable: 'N/A',
|
||||
now: 'Now',
|
||||
today: 'Today',
|
||||
tomorrow: 'Tomorrow',
|
||||
unknown: 'Unknown',
|
||||
minutes: 'min',
|
||||
time: {
|
||||
@@ -5237,6 +5239,8 @@ export default {
|
||||
createdAt: 'Created',
|
||||
cancel: 'Cancel Order',
|
||||
userId: 'User ID',
|
||||
orderType: 'Order Type',
|
||||
actions: 'Actions',
|
||||
requestRefund: 'Request Refund',
|
||||
},
|
||||
result: {
|
||||
|
||||
@@ -308,6 +308,8 @@ export default {
|
||||
chooseFile: '选择文件',
|
||||
notAvailable: '不可用',
|
||||
now: '现在',
|
||||
today: '今天',
|
||||
tomorrow: '明天',
|
||||
unknown: '未知',
|
||||
minutes: '分钟',
|
||||
time: {
|
||||
@@ -5425,6 +5427,8 @@ export default {
|
||||
createdAt: '创建时间',
|
||||
cancel: '取消订单',
|
||||
userId: '用户 ID',
|
||||
orderType: '订单类型',
|
||||
actions: '操作',
|
||||
requestRefund: '申请退款',
|
||||
},
|
||||
result: {
|
||||
|
||||
@@ -117,6 +117,7 @@ import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore } from '@/stores/app'
|
||||
import { adminPaymentAPI } from '@/api/admin/payment'
|
||||
import { extractApiErrorMessage } from '@/utils/apiError'
|
||||
import { formatOrderDateTime } from '@/components/payment/orderUtils'
|
||||
import type { PaymentOrder } from '@/types/payment'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'
|
||||
import Pagination from '@/components/common/Pagination.vue'
|
||||
@@ -233,7 +234,7 @@ async function handleRefund(data: { amount: number; reason: string; deduct_balan
|
||||
finally { refundSubmitting.value = false }
|
||||
}
|
||||
|
||||
function formatDateTime(dateStr: string): string { if (!dateStr) return '-'; return new Date(dateStr).toLocaleString() }
|
||||
function formatDateTime(dateStr: string): string { return formatOrderDateTime(dateStr) }
|
||||
|
||||
onMounted(() => loadOrders())
|
||||
</script>
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
<template>
|
||||
<AppLayout>
|
||||
<div class="purchase-page-layout">
|
||||
<div class="card flex-1 min-h-0 overflow-hidden">
|
||||
<div v-if="loading" class="flex h-full items-center justify-center py-12">
|
||||
<div
|
||||
class="h-8 w-8 animate-spin rounded-full border-2 border-primary-500 border-t-transparent"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="!purchaseEnabled"
|
||||
class="flex h-full items-center justify-center p-10 text-center"
|
||||
>
|
||||
<div class="max-w-md">
|
||||
<div
|
||||
class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 dark:bg-dark-700"
|
||||
>
|
||||
<Icon name="creditCard" size="lg" class="text-gray-400" />
|
||||
</div>
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('purchase.notEnabledTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm text-gray-500 dark:text-dark-400">
|
||||
{{ t('purchase.notEnabledDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="!isValidUrl"
|
||||
class="flex h-full items-center justify-center p-10 text-center"
|
||||
>
|
||||
<div class="max-w-md">
|
||||
<div
|
||||
class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 dark:bg-dark-700"
|
||||
>
|
||||
<Icon name="link" size="lg" class="text-gray-400" />
|
||||
</div>
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('purchase.notConfiguredTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm text-gray-500 dark:text-dark-400">
|
||||
{{ t('purchase.notConfiguredDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="purchase-embed-shell">
|
||||
<a
|
||||
:href="purchaseUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="btn btn-secondary btn-sm purchase-open-fab"
|
||||
>
|
||||
<Icon name="externalLink" size="sm" class="mr-1.5" :stroke-width="2" />
|
||||
{{ t('purchase.openInNewTab') }}
|
||||
</a>
|
||||
<iframe
|
||||
:src="purchaseUrl"
|
||||
class="purchase-embed-frame"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore } from '@/stores'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import { buildEmbeddedUrl, detectTheme } from '@/utils/embedded-url'
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const loading = ref(false)
|
||||
const purchaseTheme = ref<'light' | 'dark'>('light')
|
||||
let themeObserver: MutationObserver | null = null
|
||||
|
||||
const purchaseEnabled = computed(() => {
|
||||
return appStore.cachedPublicSettings?.purchase_subscription_enabled ?? false
|
||||
})
|
||||
|
||||
const purchaseUrl = computed(() => {
|
||||
const baseUrl = (appStore.cachedPublicSettings?.purchase_subscription_url || '').trim()
|
||||
return buildEmbeddedUrl(baseUrl, authStore.user?.id, authStore.token, purchaseTheme.value, locale.value)
|
||||
})
|
||||
|
||||
const isValidUrl = computed(() => {
|
||||
const url = purchaseUrl.value
|
||||
return url.startsWith('http://') || url.startsWith('https://')
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
purchaseTheme.value = detectTheme()
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
themeObserver = new MutationObserver(() => {
|
||||
purchaseTheme.value = detectTheme()
|
||||
})
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class'],
|
||||
})
|
||||
}
|
||||
|
||||
if (appStore.publicSettingsLoaded) return
|
||||
loading.value = true
|
||||
try {
|
||||
await appStore.fetchPublicSettings()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (themeObserver) {
|
||||
themeObserver.disconnect()
|
||||
themeObserver = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.purchase-page-layout {
|
||||
@apply flex flex-col;
|
||||
height: calc(100vh - 64px - 4rem);
|
||||
}
|
||||
|
||||
.purchase-embed-shell {
|
||||
@apply relative;
|
||||
@apply h-full w-full overflow-hidden rounded-2xl;
|
||||
@apply bg-gradient-to-b from-gray-50 to-white dark:from-dark-900 dark:to-dark-950;
|
||||
@apply p-0;
|
||||
}
|
||||
|
||||
.purchase-open-fab {
|
||||
@apply absolute right-3 top-3 z-10;
|
||||
@apply shadow-sm backdrop-blur supports-[backdrop-filter]:bg-white/80 dark:supports-[backdrop-filter]:bg-dark-800/80;
|
||||
}
|
||||
|
||||
.purchase-embed-frame {
|
||||
display: block;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
@@ -56,6 +56,11 @@
|
||||
import { computed, ref, onMounted, onUnmounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { extractApiErrorMessage } from '@/utils/apiError'
|
||||
|
||||
interface StripeWithWechatPay {
|
||||
confirmWechatPayPayment(clientSecret: string, options: Record<string, unknown>): Promise<{ error?: { message?: string }; paymentIntent?: { status: string } }>
|
||||
}
|
||||
|
||||
const METHOD_COLORS: Record<string, string> = {
|
||||
alipay: '#00AEEF',
|
||||
@@ -123,7 +128,7 @@ async function initStripe(clientSecret: string, publishableKey: string) {
|
||||
} else if (method === 'wechat_pay') {
|
||||
// WeChat: Stripe shows its built-in QR dialog, user scans, promise resolves
|
||||
hint.value = t('payment.stripePopup.loadingQr')
|
||||
const result = await (stripe as any).confirmWechatPayPayment(clientSecret, {
|
||||
const result = await (stripe as unknown as StripeWithWechatPay).confirmWechatPayPayment(clientSecret, {
|
||||
payment_method_options: { wechat_pay: { client: 'web' } },
|
||||
})
|
||||
if (result.error) {
|
||||
@@ -137,7 +142,7 @@ async function initStripe(clientSecret: string, publishableKey: string) {
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
error.value = err instanceof Error ? err.message : t('payment.stripeLoadFailed')
|
||||
error.value = extractApiErrorMessage(err, t('payment.stripeLoadFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -313,10 +313,10 @@ function formatExpirationDate(expiresAt: string): string {
|
||||
const dateStr = formatDateOnly(expires)
|
||||
|
||||
if (days === 0) {
|
||||
return `${dateStr} (Today)`
|
||||
return `${dateStr} (${t('common.today')})`
|
||||
}
|
||||
if (days === 1) {
|
||||
return `${dateStr} (Tomorrow)`
|
||||
return `${dateStr} (${t('common.tomorrow')})`
|
||||
}
|
||||
|
||||
return t('userSubscriptions.daysRemaining', { days }) + ` (${dateStr})`
|
||||
|
||||
Reference in New Issue
Block a user