first commit

This commit is contained in:
2025-08-16 18:46:29 +08:00
commit 5f008b3228
511 changed files with 53667 additions and 0 deletions

View File

@@ -0,0 +1,211 @@
package service
import (
"context"
"database/sql"
"time"
"znc-server/app/main/model"
"znc-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminPromotionLinkStatsService struct {
logx.Logger
AdminPromotionLinkModel model.AdminPromotionLinkModel
AdminPromotionLinkStatsTotalModel model.AdminPromotionLinkStatsTotalModel
AdminPromotionLinkStatsHistoryModel model.AdminPromotionLinkStatsHistoryModel
}
func NewAdminPromotionLinkStatsService(
AdminPromotionLinkModel model.AdminPromotionLinkModel,
AdminPromotionLinkStatsTotalModel model.AdminPromotionLinkStatsTotalModel,
AdminPromotionLinkStatsHistoryModel model.AdminPromotionLinkStatsHistoryModel,
) *AdminPromotionLinkStatsService {
return &AdminPromotionLinkStatsService{
Logger: logx.WithContext(context.Background()),
AdminPromotionLinkModel: AdminPromotionLinkModel,
AdminPromotionLinkStatsTotalModel: AdminPromotionLinkStatsTotalModel,
AdminPromotionLinkStatsHistoryModel: AdminPromotionLinkStatsHistoryModel,
}
}
// ensureTotalStats 确保总统计记录存在,如果不存在则创建
func (s *AdminPromotionLinkStatsService) ensureTotalStats(ctx context.Context, session sqlx.Session, linkId int64) (*model.AdminPromotionLinkStatsTotal, error) {
totalStats, err := s.AdminPromotionLinkStatsTotalModel.FindOneByLinkId(ctx, linkId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
// 如果记录不存在,创建新记录
totalStats = &model.AdminPromotionLinkStatsTotal{
LinkId: linkId,
ClickCount: 0,
PayCount: 0,
PayAmount: 0,
}
_, err = s.AdminPromotionLinkStatsTotalModel.Insert(ctx, session, totalStats)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建总统计记录失败: %+v", err)
}
// 重新获取创建后的记录
totalStats, err = s.AdminPromotionLinkStatsTotalModel.FindOneByLinkId(ctx, linkId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的总统计记录失败: %+v", err)
}
} else {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询总统计失败: %+v", err)
}
}
return totalStats, nil
}
// ensureHistoryStats 确保历史统计记录存在,如果不存在则创建
func (s *AdminPromotionLinkStatsService) ensureHistoryStats(ctx context.Context, session sqlx.Session, linkId int64, today time.Time) (*model.AdminPromotionLinkStatsHistory, error) {
historyStats, err := s.AdminPromotionLinkStatsHistoryModel.FindOneByLinkIdStatsDate(ctx, linkId, today)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
// 如果记录不存在,创建新记录
historyStats = &model.AdminPromotionLinkStatsHistory{
LinkId: linkId,
StatsDate: today,
ClickCount: 0,
PayCount: 0,
PayAmount: 0,
}
_, err = s.AdminPromotionLinkStatsHistoryModel.Insert(ctx, session, historyStats)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建今日统计记录失败: %+v", err)
}
// 重新获取创建后的记录
historyStats, err = s.AdminPromotionLinkStatsHistoryModel.FindOneByLinkIdStatsDate(ctx, linkId, today)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的今日统计记录失败: %+v", err)
}
} else {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询今日统计记录失败: %+v", err)
}
}
return historyStats, nil
}
// UpdateLinkStats 更新推广链接统计
func (s *AdminPromotionLinkStatsService) UpdateLinkStats(ctx context.Context, linkId int64) error {
return s.AdminPromotionLinkStatsTotalModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
// 确保总统计记录存在
totalStats, err := s.ensureTotalStats(ctx, session, linkId)
if err != nil {
return err
}
// 更新总统计
totalStats.ClickCount++
totalStats.LastClickTime = sql.NullTime{Time: time.Now(), Valid: true}
err = s.AdminPromotionLinkStatsTotalModel.UpdateWithVersion(ctx, session, totalStats)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新总统计失败: %+v", err)
}
// 确保历史统计记录存在
now := time.Now()
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
historyStats, err := s.ensureHistoryStats(ctx, session, linkId, today)
if err != nil {
return err
}
// 更新历史统计
historyStats.ClickCount++
historyStats.LastClickTime = sql.NullTime{Time: time.Now(), Valid: true}
err = s.AdminPromotionLinkStatsHistoryModel.UpdateWithVersion(ctx, session, historyStats)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新历史统计失败: %+v", err)
}
return nil
})
}
// UpdatePaymentStats 更新付费统计
func (s *AdminPromotionLinkStatsService) UpdatePaymentStats(ctx context.Context, linkId int64, amount float64) error {
return s.AdminPromotionLinkStatsTotalModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
// 确保总统计记录存在
totalStats, err := s.ensureTotalStats(ctx, session, linkId)
if err != nil {
return err
}
// 更新总统计
totalStats.PayCount++
totalStats.PayAmount += amount
totalStats.LastPayTime = sql.NullTime{Time: time.Now(), Valid: true}
err = s.AdminPromotionLinkStatsTotalModel.UpdateWithVersion(ctx, session, totalStats)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新总统计失败: %+v", err)
}
// 确保历史统计记录存在
now := time.Now()
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
historyStats, err := s.ensureHistoryStats(ctx, session, linkId, today)
if err != nil {
return err
}
// 更新历史统计
historyStats.PayCount++
historyStats.PayAmount += amount
historyStats.LastPayTime = sql.NullTime{Time: time.Now(), Valid: true}
err = s.AdminPromotionLinkStatsHistoryModel.UpdateWithVersion(ctx, session, historyStats)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新历史统计失败: %+v", err)
}
return nil
})
}
// CreateLinkStats 创建新的推广链接统计记录
func (s *AdminPromotionLinkStatsService) CreateLinkStats(ctx context.Context, linkId int64) error {
return s.AdminPromotionLinkStatsTotalModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
// 检查总统计记录是否已存在
_, err := s.AdminPromotionLinkStatsTotalModel.FindOneByLinkId(ctx, linkId)
if err == nil {
// 记录已存在,不需要创建
return nil
}
if err != model.ErrNotFound {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询总统计记录失败: %+v", err)
}
// 创建总统计记录
totalStats := &model.AdminPromotionLinkStatsTotal{
LinkId: linkId,
ClickCount: 0,
PayCount: 0,
PayAmount: 0,
}
_, err = s.AdminPromotionLinkStatsTotalModel.Insert(ctx, session, totalStats)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建总统计记录失败: %+v", err)
}
// 创建今日历史统计记录
now := time.Now()
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
historyStats := &model.AdminPromotionLinkStatsHistory{
LinkId: linkId,
StatsDate: today,
ClickCount: 0,
PayCount: 0,
PayAmount: 0,
}
_, err = s.AdminPromotionLinkStatsHistoryModel.Insert(ctx, session, historyStats)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建历史统计记录失败: %+v", err)
}
return nil
})
}

View File

@@ -0,0 +1,344 @@
package service
import (
"context"
"znc-server/app/main/api/internal/config"
"znc-server/app/main/model"
"znc-server/pkg/lzkit/lzUtils"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AgentService struct {
config config.Config
AgentModel model.AgentModel
AgentAuditModel model.AgentAuditModel
AgentClosureModel model.AgentClosureModel
AgentCommissionModel model.AgentCommissionModel
AgentCommissionDeductionModel model.AgentCommissionDeductionModel
AgentWalletModel model.AgentWalletModel
AgentLinkModel model.AgentLinkModel
AgentOrderModel model.AgentOrderModel
AgentRewardsModel model.AgentRewardsModel
AgentMembershipConfigModel model.AgentMembershipConfigModel
AgentMembershipRechargeOrderModel model.AgentMembershipRechargeOrderModel
AgentMembershipUserConfigModel model.AgentMembershipUserConfigModel
AgentProductConfigModel model.AgentProductConfigModel
AgentPlatformDeductionModel model.AgentPlatformDeductionModel
AgentActiveStatModel model.AgentActiveStatModel
AgentWithdrawalModel model.AgentWithdrawalModel
}
func NewAgentService(c config.Config, agentModel model.AgentModel, agentAuditModel model.AgentAuditModel,
agentClosureModel model.AgentClosureModel, agentCommissionModel model.AgentCommissionModel,
agentCommissionDeductionModel model.AgentCommissionDeductionModel, agentWalletModel model.AgentWalletModel, agentLinkModel model.AgentLinkModel, agentOrderModel model.AgentOrderModel, agentRewardsModel model.AgentRewardsModel,
agentMembershipConfigModel model.AgentMembershipConfigModel,
agentMembershipRechargeOrderModel model.AgentMembershipRechargeOrderModel,
agentMembershipUserConfigModel model.AgentMembershipUserConfigModel,
agentProductConfigModel model.AgentProductConfigModel, agentPlatformDeductionModel model.AgentPlatformDeductionModel,
agentActiveStatModel model.AgentActiveStatModel, agentWithdrawalModel model.AgentWithdrawalModel) *AgentService {
return &AgentService{
config: c,
AgentModel: agentModel,
AgentAuditModel: agentAuditModel,
AgentClosureModel: agentClosureModel,
AgentCommissionModel: agentCommissionModel,
AgentCommissionDeductionModel: agentCommissionDeductionModel,
AgentWalletModel: agentWalletModel,
AgentLinkModel: agentLinkModel,
AgentOrderModel: agentOrderModel,
AgentRewardsModel: agentRewardsModel,
AgentMembershipConfigModel: agentMembershipConfigModel,
AgentMembershipRechargeOrderModel: agentMembershipRechargeOrderModel,
AgentMembershipUserConfigModel: agentMembershipUserConfigModel,
AgentProductConfigModel: agentProductConfigModel,
AgentPlatformDeductionModel: agentPlatformDeductionModel,
AgentActiveStatModel: agentActiveStatModel,
AgentWithdrawalModel: agentWithdrawalModel,
}
}
// AgentProcess 推广单成功
func (l *AgentService) AgentProcess(ctx context.Context, order *model.Order) error {
// 获取是否该订单是代理推广订单
agentOrderModel, err := l.AgentOrderModel.FindOneByOrderId(ctx, order.Id)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return err
}
if errors.Is(err, model.ErrNotFound) || agentOrderModel == nil {
return nil
}
// 事务
transErr := l.AgentWalletModel.Trans(ctx, func(transCtx context.Context, session sqlx.Session) error {
agentID := agentOrderModel.AgentId
agentProductConfigModel, findAgentProductConfigModelErr := l.AgentProductConfigModel.FindOneByProductId(transCtx, order.ProductId)
if findAgentProductConfigModelErr != nil {
return findAgentProductConfigModelErr
}
// 平台底价成本
PlatformCostAmount, platformCostErr := l.PlatformCost(transCtx, agentID, agentProductConfigModel, session)
if platformCostErr != nil {
return platformCostErr
}
// 平台提价成本
PlatformPricingAmount, platformPricingErr := l.PlatformPricing(transCtx, agentID, order.Amount, agentProductConfigModel, session)
if platformPricingErr != nil {
return platformPricingErr
}
// 查找上级
AgentClosureModel, findAgentClosureModelErr := l.AgentClosureModel.FindOneByDescendantIdDepth(transCtx, agentID, 1)
if findAgentClosureModelErr != nil && !errors.Is(findAgentClosureModelErr, model.ErrNotFound) {
return findAgentClosureModelErr
}
var descendantDeductedAmount = 0.00
if AgentClosureModel != nil {
AncestorId := AgentClosureModel.AncestorId
AncestorModel, findAgentModelErr := l.AgentModel.FindOne(transCtx, AncestorId)
if findAgentModelErr != nil != errors.Is(findAgentModelErr, model.ErrNotFound) {
return findAgentModelErr
}
if AgentClosureModel != nil {
if AncestorModel.LevelName == "" {
AncestorModel.LevelName = model.AgentLeveNameNormal
}
AgentMembershipConfigModel, findAgentMembersipConfigModelErr := l.AgentMembershipConfigModel.FindOneByLevelName(ctx, AncestorModel.LevelName)
if findAgentMembersipConfigModelErr != nil {
return findAgentMembersipConfigModelErr
}
// 定价
commissionCost, commissionCostErr := l.CommissionCost(transCtx, agentID, AncestorId, AgentMembershipConfigModel, order.ProductId, session)
if commissionCostErr != nil {
return commissionCostErr
}
// 提价
commissionPricing, commissionPricingErr := l.CommissionPricing(transCtx, agentID, AncestorId, AgentMembershipConfigModel, order.ProductId, order.Amount, session)
if commissionPricingErr != nil {
return commissionPricingErr
}
// 上级克扣的成本
descendantDeductedAmount = commissionCost + commissionPricing
// 佣金
ancestorCommissionReward, ancestorCommissionErr := l.AncestorCommission(transCtx, agentID, AncestorId, session)
if ancestorCommissionErr != nil {
return ancestorCommissionErr
}
// 给上级成本以及佣金
ancestorCommissionAmount := commissionCost + commissionPricing + ancestorCommissionReward
ancestorWallet, findAgentWalletModelErr := l.AgentWalletModel.FindOneByAgentId(transCtx, AncestorId)
if findAgentWalletModelErr != nil {
return findAgentWalletModelErr
}
ancestorWallet.Balance += ancestorCommissionAmount
ancestorWallet.TotalEarnings += ancestorCommissionAmount
updateErr := l.AgentWalletModel.UpdateWithVersion(transCtx, session, ancestorWallet)
if updateErr != nil {
return updateErr
}
}
}
// 推广人扣除金额 = 平台成本价 + 平台提价成本 + 上级佣金
deductedAmount := PlatformCostAmount + PlatformPricingAmount + descendantDeductedAmount
agentCommissionErr := l.AgentCommission(transCtx, agentID, order, deductedAmount, session)
if agentCommissionErr != nil {
return agentCommissionErr
}
return nil
})
if transErr != nil {
return transErr
}
return nil
}
// AgentCommission 直推报告推广人佣金
func (l *AgentService) AgentCommission(ctx context.Context, agentID int64, order *model.Order, deductedAmount float64, session sqlx.Session) error {
agentWalletModel, findAgentWalletModelErr := l.AgentWalletModel.FindOneByAgentId(ctx, agentID)
if findAgentWalletModelErr != nil {
return findAgentWalletModelErr
}
// 推广人最终获得代理佣金
finalCommission := order.Amount - deductedAmount
agentWalletModel.Balance += finalCommission
agentWalletModel.TotalEarnings += finalCommission
agentCommission := model.AgentCommission{
AgentId: agentID,
OrderId: order.Id,
Amount: finalCommission,
ProductId: order.ProductId,
}
_, insertAgentCommissionErr := l.AgentCommissionModel.Insert(ctx, session, &agentCommission)
if insertAgentCommissionErr != nil {
return insertAgentCommissionErr
}
updateAgentWalletErr := l.AgentWalletModel.UpdateWithVersion(ctx, session, agentWalletModel)
if updateAgentWalletErr != nil {
return updateAgentWalletErr
}
return nil
}
// AncestorCommission 直推报告上级佣金(奖励型)
func (l *AgentService) AncestorCommission(ctx context.Context, descendantId int64, ancestorId int64, session sqlx.Session) (float64, error) {
agentModel, err := l.AgentModel.FindOne(ctx, ancestorId)
if err != nil {
return 0, err
}
if agentModel.LevelName == "" {
agentModel.LevelName = model.AgentLeveNameNormal
}
agentMembershipConfigModel, err := l.AgentMembershipConfigModel.FindOneByLevelName(ctx, agentModel.LevelName)
if err != nil {
return 0, err
}
if agentMembershipConfigModel.ReportCommission.Valid {
reportCommissionAmount := agentMembershipConfigModel.ReportCommission.Float64
agentRewards := model.AgentRewards{
AgentId: ancestorId,
Amount: reportCommissionAmount,
RelationAgentId: lzUtils.Int64ToNullInt64(descendantId),
Type: model.AgentRewardsTypeDescendantPromotion,
}
_, agentRewardsModelInsetErr := l.AgentRewardsModel.Insert(ctx, session, &agentRewards)
if agentRewardsModelInsetErr != nil {
return 0, agentRewardsModelInsetErr
}
return reportCommissionAmount, nil
}
return 0, nil
}
// PlatformCost 平台底价成本
func (l *AgentService) PlatformCost(ctx context.Context, agentID int64, agentProductConfigModel *model.AgentProductConfig, session sqlx.Session) (float64, error) {
costAgentPlatformDeductionModel := model.AgentPlatformDeduction{
AgentId: agentID,
Amount: agentProductConfigModel.CostPrice,
Type: model.AgentDeductionTypeCost,
}
_, err := l.AgentPlatformDeductionModel.Insert(ctx, session, &costAgentPlatformDeductionModel)
if err != nil {
return 0, err
}
return agentProductConfigModel.CostPrice, nil
}
// PlatformPricing 平台提价成本
func (l *AgentService) PlatformPricing(ctx context.Context, agentID int64, pricing float64, agentProductConfigModel *model.AgentProductConfig, session sqlx.Session) (float64, error) {
// 2. 计算平台提价成本
if pricing > agentProductConfigModel.PricingStandard {
// 超出部分
overpricing := pricing - agentProductConfigModel.PricingStandard
// 收取成本
overpricingCost := overpricing * agentProductConfigModel.OverpricingRatio
pricingAgentPlatformDeductionModel := model.AgentPlatformDeduction{
AgentId: agentID,
Amount: overpricingCost,
Type: model.AgentDeductionTypePricing,
}
_, err := l.AgentPlatformDeductionModel.Insert(ctx, session, &pricingAgentPlatformDeductionModel)
if err != nil {
return 0, err
}
return overpricingCost, nil
}
return 0, nil
}
// CommissionCost 上级底价成本
func (l *AgentService) CommissionCost(ctx context.Context, descendantId int64, AncestorId int64, agentMembershipConfigModel *model.AgentMembershipConfig, productID int64, session sqlx.Session) (float64, error) {
if agentMembershipConfigModel.PriceIncreaseAmount.Valid {
// 拥有则查看该上级设定的成本
agentMembershipUserConfigModel, findAgentMembershipUserConfigModelErr := l.AgentMembershipUserConfigModel.FindOneByAgentIdProductId(ctx, AncestorId, productID)
if findAgentMembershipUserConfigModelErr != nil {
return 0, findAgentMembershipUserConfigModelErr
}
deductCostAmount := agentMembershipUserConfigModel.PriceIncreaseAmount
agentCommissionDeductionModel := model.AgentCommissionDeduction{
AgentId: AncestorId,
DeductedAgentId: descendantId,
Amount: deductCostAmount,
Type: model.AgentDeductionTypeCost,
ProductId: productID,
}
_, insertAgentCommissionDeductionModelErr := l.AgentCommissionDeductionModel.Insert(ctx, session, &agentCommissionDeductionModel)
if insertAgentCommissionDeductionModelErr != nil {
return 0, insertAgentCommissionDeductionModelErr
}
return deductCostAmount, nil
}
return 0, nil
}
// CommissionPricing 上级提价成本
func (l *AgentService) CommissionPricing(ctx context.Context, descendantId int64, AncestorId int64, agentMembershipConfigModel *model.AgentMembershipConfig, productID int64, pricing float64, session sqlx.Session) (float64, error) {
//看上级代理等级否有拥有定价标准收益功能
if agentMembershipConfigModel.PriceIncreaseMax.Valid && agentMembershipConfigModel.PriceRatio.Valid {
// 拥有则查看该上级设定的成本
agentMembershipUserConfigModel, findAgentMembershipUserConfigModelErr := l.AgentMembershipUserConfigModel.FindOneByAgentIdProductId(ctx, AncestorId, productID)
if findAgentMembershipUserConfigModelErr != nil {
return 0, findAgentMembershipUserConfigModelErr
}
// 计算是否在范围内
var pricingRange float64
if pricing > agentMembershipUserConfigModel.PriceRangeFrom {
if pricing > agentMembershipUserConfigModel.PriceRangeTo {
pricingRange = agentMembershipUserConfigModel.PriceRangeTo - agentMembershipUserConfigModel.PriceRangeFrom
} else {
pricingRange = pricing - agentMembershipUserConfigModel.PriceRangeFrom
}
}
deductCostAmount := pricingRange * agentMembershipUserConfigModel.PriceRatio
agentCommissionDeductionModel := model.AgentCommissionDeduction{
AgentId: AncestorId,
DeductedAgentId: descendantId,
Amount: deductCostAmount,
Type: model.AgentDeductionTypePricing,
ProductId: productID,
}
_, insertAgentCommissionDeductionModelErr := l.AgentCommissionDeductionModel.Insert(ctx, session, &agentCommissionDeductionModel)
if insertAgentCommissionDeductionModelErr != nil {
return 0, insertAgentCommissionDeductionModelErr
}
return deductCostAmount, nil
}
return 0, nil
}
//func (l *AgentService) UpgradeVip(ctx context.Context, agentID int64, leve string, session sqlx.Session) error {
// agentModel, err := l.AgentModel.FindOne(ctx, agentID)
// if err != nil {
// return err
// }
// if agentModel.LevelName != model.AgentLeveNameNormal {
// return fmt.Errorf("已经是会员")
// }
// return nil
//}

View File

@@ -0,0 +1,258 @@
package service
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"strconv"
"sync/atomic"
"time"
"znc-server/app/main/api/internal/config"
"znc-server/app/main/model"
"znc-server/pkg/lzkit/lzUtils"
"github.com/smartwalle/alipay/v3"
)
type AliPayService struct {
config config.AlipayConfig
AlipayClient *alipay.Client
}
// NewAliPayService 是一个构造函数,用于初始化 AliPayService
func NewAliPayService(c config.Config) *AliPayService {
client, err := alipay.New(c.Alipay.AppID, c.Alipay.PrivateKey, c.Alipay.IsProduction)
if err != nil {
panic(fmt.Sprintf("创建支付宝客户端失败: %v", err))
}
//// 加载支付宝公钥
//err = client.LoadAliPayPublicKey(c.Alipay.AlipayPublicKey)
//if err != nil {
// panic(fmt.Sprintf("加载支付宝公钥失败: %v", err))
//}
// 加载证书
if err = client.LoadAppCertPublicKeyFromFile(c.Alipay.AppCertPath); err != nil {
panic(fmt.Sprintf("加载应用公钥证书失败: %v", err))
}
if err = client.LoadAlipayCertPublicKeyFromFile(c.Alipay.AlipayCertPath); err != nil {
panic(fmt.Sprintf("加载支付宝公钥证书失败: %v", err))
}
if err = client.LoadAliPayRootCertFromFile(c.Alipay.AlipayRootCertPath); err != nil {
panic(fmt.Sprintf("加载根证书失败: %v", err))
}
return &AliPayService{
config: c.Alipay,
AlipayClient: client,
}
}
func (a *AliPayService) CreateAlipayAppOrder(amount float64, subject string, outTradeNo string) (string, error) {
client := a.AlipayClient
totalAmount := lzUtils.ToAlipayAmount(amount)
// 构造移动支付请求
p := alipay.TradeAppPay{
Trade: alipay.Trade{
Subject: subject,
OutTradeNo: outTradeNo,
TotalAmount: totalAmount,
ProductCode: "QUICK_MSECURITY_PAY", // 移动端支付专用代码
NotifyURL: a.config.NotifyUrl, // 异步回调通知地址
},
}
// 获取APP支付字符串这里会签名
payStr, err := client.TradeAppPay(p)
if err != nil {
return "", fmt.Errorf("创建支付宝订单失败: %v", err)
}
return payStr, nil
}
// CreateAlipayH5Order 创建支付宝H5支付订单
func (a *AliPayService) CreateAlipayH5Order(amount float64, subject string, outTradeNo string) (string, error) {
client := a.AlipayClient
totalAmount := lzUtils.ToAlipayAmount(amount)
// 构造H5支付请求
p := alipay.TradeWapPay{
Trade: alipay.Trade{
Subject: subject,
OutTradeNo: outTradeNo,
TotalAmount: totalAmount,
ProductCode: "QUICK_WAP_PAY", // H5支付专用产品码
NotifyURL: a.config.NotifyUrl, // 异步回调通知地址
ReturnURL: a.config.ReturnURL,
},
}
// 获取H5支付请求字符串这里会签名
payUrl, err := client.TradeWapPay(p)
if err != nil {
return "", fmt.Errorf("创建支付宝H5订单失败: %v", err)
}
return payUrl.String(), nil
}
// CreateAlipayOrder 根据平台类型创建支付宝支付订单
func (a *AliPayService) CreateAlipayOrder(ctx context.Context, amount float64, subject string, outTradeNo string) (string, error) {
// 根据 ctx 中的 platform 判断平台
platform, platformOk := ctx.Value("platform").(string)
if !platformOk {
return "", fmt.Errorf("无的支付平台: %s", platform)
}
switch platform {
case model.PlatformApp:
// 调用App支付的创建方法
return a.CreateAlipayAppOrder(amount, subject, outTradeNo)
case model.PlatformH5:
// 调用H5支付的创建方法并传入 returnUrl
return a.CreateAlipayH5Order(amount, subject, outTradeNo)
default:
return "", fmt.Errorf("不支持的支付平台: %s", platform)
}
}
// AliRefund 发起支付宝退款
func (a *AliPayService) AliRefund(ctx context.Context, outTradeNo string, refundAmount float64) (*alipay.TradeRefundRsp, error) {
refund := alipay.TradeRefund{
OutTradeNo: outTradeNo,
RefundAmount: lzUtils.ToAlipayAmount(refundAmount),
OutRequestNo: fmt.Sprintf("refund-%s", outTradeNo),
}
// 发起退款请求
refundResp, err := a.AlipayClient.TradeRefund(ctx, refund)
if err != nil {
return nil, fmt.Errorf("支付宝退款请求错误:%v", err)
}
return refundResp, nil
}
// HandleAliPaymentNotification 支付宝支付回调
func (a *AliPayService) HandleAliPaymentNotification(r *http.Request) (*alipay.Notification, error) {
// 解析表单
err := r.ParseForm()
if err != nil {
return nil, fmt.Errorf("解析请求表单失败:%v", err)
}
// 解析并验证通知DecodeNotification 会自动验证签名
notification, err := a.AlipayClient.DecodeNotification(r.Form)
if err != nil {
return nil, fmt.Errorf("验证签名失败: %v", err)
}
return notification, nil
}
func (a *AliPayService) QueryOrderStatus(ctx context.Context, outTradeNo string) (*alipay.TradeQueryRsp, error) {
queryRequest := alipay.TradeQuery{
OutTradeNo: outTradeNo,
}
// 发起查询请求
resp, err := a.AlipayClient.TradeQuery(ctx, queryRequest)
if err != nil {
return nil, fmt.Errorf("查询支付宝订单失败: %v", err)
}
// 返回交易状态
if resp.IsSuccess() {
return resp, nil
}
return nil, fmt.Errorf("查询支付宝订单失败: %v", resp.SubMsg)
}
// 添加全局原子计数器
var alipayOrderCounter uint32 = 0
// GenerateOutTradeNo 生成唯一订单号的函数 - 优化版本
func (a *AliPayService) GenerateOutTradeNo() string {
// 获取当前时间戳(毫秒级)
timestamp := time.Now().UnixMilli()
timeStr := strconv.FormatInt(timestamp, 10)
// 原子递增计数器
counter := atomic.AddUint32(&alipayOrderCounter, 1)
// 生成4字节真随机数
randomBytes := make([]byte, 4)
_, err := rand.Read(randomBytes)
if err != nil {
// 如果随机数生成失败,回退到使用时间纳秒数据
randomBytes = []byte(strconv.FormatInt(time.Now().UnixNano()%1000000, 16))
}
randomHex := hex.EncodeToString(randomBytes)
// 组合所有部分: 前缀 + 时间戳 + 计数器 + 随机数
orderNo := fmt.Sprintf("%s%06x%s", timeStr[:10], counter%0xFFFFFF, randomHex[:6])
// 确保长度不超过32字符大多数支付平台的限制
if len(orderNo) > 32 {
orderNo = orderNo[:32]
}
return orderNo
}
// AliTransfer 支付宝单笔转账到支付宝账户(提现功能)
func (a *AliPayService) AliTransfer(
ctx context.Context,
payeeAccount string, // 收款方支付宝账户
payeeName string, // 收款方姓名
amount float64, // 转账金额
remark string, // 转账备注
outBizNo string, // 商户转账唯一订单号可使用GenerateOutTradeNo生成
) (*alipay.FundTransUniTransferRsp, error) {
// 参数校验
if payeeAccount == "" {
return nil, fmt.Errorf("收款账户不能为空")
}
if amount <= 0 {
return nil, fmt.Errorf("转账金额必须大于0")
}
// 构造转账请求
req := alipay.FundTransUniTransfer{
OutBizNo: outBizNo,
TransAmount: lzUtils.ToAlipayAmount(amount), // 金额格式转换
ProductCode: "TRANS_ACCOUNT_NO_PWD", // 单笔无密转账到支付宝账户
BizScene: "DIRECT_TRANSFER", // 单笔转账
OrderTitle: "账户提现", // 转账标题
Remark: remark,
PayeeInfo: &alipay.PayeeInfo{
Identity: payeeAccount,
IdentityType: "ALIPAY_LOGON_ID", // 根据账户类型选择:
Name: payeeName,
// ALIPAY_USER_ID/ALIPAY_LOGON_ID
},
}
// 执行转账请求
transferRsp, err := a.AlipayClient.FundTransUniTransfer(ctx, req)
if err != nil {
return nil, fmt.Errorf("支付宝转账请求失败: %v", err)
}
return transferRsp, nil
}
func (a *AliPayService) QueryTransferStatus(
ctx context.Context,
outBizNo string,
) (*alipay.FundTransOrderQueryRsp, error) {
req := alipay.FundTransOrderQuery{
OutBizNo: outBizNo,
}
response, err := a.AlipayClient.FundTransOrderQuery(ctx, req)
if err != nil {
return nil, fmt.Errorf("支付宝接口调用失败: %v", err)
}
// 处理响应
if response.Code.IsFailure() {
return nil, fmt.Errorf("支付宝返回错误: %s-%s", response.Code, response.Msg)
}
return response, nil
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,169 @@
package service
import (
"context"
"crypto/ecdsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
"znc-server/app/main/api/internal/config"
"github.com/golang-jwt/jwt/v4"
)
// ApplePayService 是 Apple IAP 支付服务的结构体
type ApplePayService struct {
config config.ApplepayConfig // 配置项
}
// NewApplePayService 是一个构造函数,用于初始化 ApplePayService
func NewApplePayService(c config.Config) *ApplePayService {
return &ApplePayService{
config: c.Applepay,
}
}
func (a *ApplePayService) GetIappayAppID(productName string) string {
return fmt.Sprintf("%s.%s", a.config.BundleID, productName)
}
// VerifyReceipt 验证苹果支付凭证
func (a *ApplePayService) VerifyReceipt(ctx context.Context, receipt string) (*AppleVerifyResponse, error) {
var reqUrl string
if a.config.Sandbox {
reqUrl = a.config.SandboxVerifyURL
} else {
reqUrl = a.config.ProductionVerifyURL
}
// 读取私钥
privateKey, err := loadPrivateKey(a.config.LoadPrivateKeyPath)
if err != nil {
return nil, fmt.Errorf("加载私钥失败:%v", err)
}
// 生成 JWT
token, err := generateJWT(privateKey, a.config.KeyID, a.config.IssuerID)
if err != nil {
return nil, fmt.Errorf("生成JWT失败%v", err)
}
// 构造查询参数
queryParams := fmt.Sprintf("?receipt-data=%s", receipt)
fullUrl := reqUrl + queryParams
// 构建 HTTP GET 请求
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullUrl, nil)
if err != nil {
return nil, fmt.Errorf("创建 HTTP 请求失败:%v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
// 发送请求
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("请求苹果验证接口失败:%v", err)
}
defer resp.Body.Close()
// 解析响应
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取响应体失败:%v", err)
}
var verifyResponse AppleVerifyResponse
err = json.Unmarshal(body, &verifyResponse)
if err != nil {
return nil, fmt.Errorf("解析响应体失败:%v", err)
}
// 根据实际响应处理逻辑
if verifyResponse.Status != 0 {
return nil, fmt.Errorf("验证失败,状态码:%d", verifyResponse.Status)
}
return &verifyResponse, nil
}
func loadPrivateKey(path string) (*ecdsa.PrivateKey, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil || block.Type != "PRIVATE KEY" {
return nil, fmt.Errorf("无效的私钥数据")
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
ecdsaKey, ok := key.(*ecdsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("私钥类型错误")
}
return ecdsaKey, nil
}
func generateJWT(privateKey *ecdsa.PrivateKey, keyID, issuerID string) (string, error) {
now := time.Now()
claims := jwt.RegisteredClaims{
Issuer: issuerID,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(1 * time.Hour)),
Audience: jwt.ClaimStrings{"appstoreconnect-v1"},
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header["kid"] = keyID
tokenString, err := token.SignedString(privateKey)
if err != nil {
return "", err
}
return tokenString, nil
}
// GenerateOutTradeNo 生成唯一订单号
func (a *ApplePayService) GenerateOutTradeNo() string {
length := 16
timestamp := time.Now().UnixNano()
timeStr := strconv.FormatInt(timestamp, 10)
randomPart := strconv.Itoa(int(timestamp % 1e6))
combined := timeStr + randomPart
if len(combined) >= length {
return combined[:length]
}
for len(combined) < length {
combined += strconv.Itoa(int(timestamp % 10))
}
return combined
}
// AppleVerifyResponse 定义苹果验证接口的响应结构
type AppleVerifyResponse struct {
Status int `json:"status"` // 验证状态码0 表示收据有效
Receipt *Receipt `json:"receipt"` // 收据信息
}
// Receipt 定义收据的精简结构
type Receipt struct {
BundleID string `json:"bundle_id"` // 应用的 Bundle ID
InApp []InAppItem `json:"in_app"` // 应用内购买记录
}
// InAppItem 定义单条交易记录
type InAppItem struct {
ProductID string `json:"product_id"` // 商品 ID
TransactionID string `json:"transaction_id"` // 交易 ID
PurchaseDate string `json:"purchase_date"` // 购买日期 (ISO 8601)
OriginalTransID string `json:"original_transaction_id"` // 原始交易 ID
}

View File

@@ -0,0 +1,60 @@
// asynq_service.go
package service
import (
"encoding/json"
"znc-server/app/main/api/internal/config"
"znc-server/app/main/api/internal/types"
"github.com/hibiken/asynq"
"github.com/zeromicro/go-zero/core/logx"
)
type AsynqService struct {
client *asynq.Client
config config.Config
}
// NewAsynqService 创建并初始化 Asynq 客户端
func NewAsynqService(c config.Config) *AsynqService {
client := asynq.NewClient(asynq.RedisClientOpt{
Addr: c.CacheRedis[0].Host,
Password: c.CacheRedis[0].Pass,
})
return &AsynqService{client: client, config: c}
}
// Close 关闭 Asynq 客户端
func (s *AsynqService) Close() error {
return s.client.Close()
}
func (s *AsynqService) SendQueryTask(orderID int64) error {
// 准备任务的 payload
payload := types.MsgPaySuccessQueryPayload{
OrderID: orderID,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
logx.Errorf("发送异步任务失败 (无法编码 payload): %v, 订单号: %d", err, orderID)
return err // 直接返回错误,避免继续执行
}
options := []asynq.Option{
asynq.MaxRetry(5), // 设置最大重试次数
}
// 创建任务
task := asynq.NewTask(types.MsgPaySuccessQuery, payloadBytes, options...)
// 将任务加入队列并获取任务信息
info, err := s.client.Enqueue(task)
if err != nil {
logx.Errorf("发送异步任务失败 (加入队列失败): %+v, 订单号: %d", err, orderID)
return err
}
// 记录成功日志,带上任务 ID 和队列信息
logx.Infof("发送异步任务成功任务ID: %s, 队列: %s, 订单号: %d", info.ID, info.Queue, orderID)
return nil
}

View File

@@ -0,0 +1,47 @@
package service
import (
"context"
"errors"
"znc-server/app/main/model"
)
type DictService struct {
adminDictTypeModel model.AdminDictTypeModel
adminDictDataModel model.AdminDictDataModel
}
func NewDictService(adminDictTypeModel model.AdminDictTypeModel, adminDictDataModel model.AdminDictDataModel) *DictService {
return &DictService{adminDictTypeModel: adminDictTypeModel, adminDictDataModel: adminDictDataModel}
}
func (s *DictService) GetDictLabel(ctx context.Context, dictType string, dictValue int64) (string, error) {
dictTypeModel, err := s.adminDictTypeModel.FindOneByDictType(ctx, dictType)
if err != nil {
return "", err
}
if dictTypeModel.Status != 1 {
return "", errors.New("字典类型未启用")
}
dictData, err := s.adminDictDataModel.FindOneByDictTypeDictValue(ctx, dictTypeModel.DictType, dictValue)
if err != nil {
return "", err
}
if dictData.Status != 1 {
return "", errors.New("字典数据未启用")
}
return dictData.DictLabel, nil
}
func (s *DictService) GetDictValue(ctx context.Context, dictType string, dictLabel string) (int64, error) {
dictTypeModel, err := s.adminDictTypeModel.FindOneByDictType(ctx, dictType)
if err != nil {
return 0, err
}
if dictTypeModel.Status != 1 {
return 0, errors.New("字典类型未启用")
}
dictData, err := s.adminDictDataModel.FindOneByDictTypeDictLabel(ctx, dictTypeModel.DictType, dictLabel)
if err != nil {
return 0, err
}
return dictData.DictValue, nil
}

View File

@@ -0,0 +1,173 @@
package service
import (
"bytes"
"fmt"
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"github.com/fogleman/gg"
"github.com/skip2/go-qrcode"
"github.com/zeromicro/go-zero/core/logx"
)
type ImageService struct {
baseImagePath string
}
func NewImageService() *ImageService {
return &ImageService{
baseImagePath: "static/images", // 原图存放目录
}
}
// ProcessImageWithQRCode 处理图片,在中间添加二维码
func (s *ImageService) ProcessImageWithQRCode(qrcodeType, qrcodeUrl string) ([]byte, string, error) {
// 1. 根据qrcodeType确定使用哪张背景图
var backgroundImageName string
switch qrcodeType {
case "promote":
backgroundImageName = "tg_qrcode_1.png"
case "invitation":
backgroundImageName = "yq_qrcode_1.png"
default:
backgroundImageName = "tg_qrcode_1.png" // 默认使用第一张图片
}
// 2. 读取原图
originalImagePath := filepath.Join(s.baseImagePath, backgroundImageName)
originalImage, err := s.loadImage(originalImagePath)
if err != nil {
logx.Errorf("加载原图失败: %v, 图片路径: %s", err, originalImagePath)
return nil, "", fmt.Errorf("加载原图失败: %v", err)
}
// 3. 获取原图尺寸
bounds := originalImage.Bounds()
imgWidth := bounds.Dx()
imgHeight := bounds.Dy()
// 4. 创建绘图上下文
dc := gg.NewContext(imgWidth, imgHeight)
// 5. 绘制原图作为背景
dc.DrawImageAnchored(originalImage, imgWidth/2, imgHeight/2, 0.5, 0.5)
// 6. 生成二维码(去掉白边)
qrCode, err := qrcode.New(qrcodeUrl, qrcode.Medium)
if err != nil {
logx.Errorf("生成二维码失败: %v, 二维码内容: %s", err, qrcodeUrl)
return nil, "", fmt.Errorf("生成二维码失败: %v", err)
}
// 禁用二维码边框,去掉白边
qrCode.DisableBorder = true
// 7. 根据二维码类型设置不同的尺寸和位置
var qrSize int
var qrX, qrY int
switch qrcodeType {
case "promote":
// promote类型精确设置二维码尺寸
qrSize = 280 // 固定尺寸280px
// 左下角位置:距左边和底边留一些边距
qrX = 192 // 距左边180px
qrY = imgHeight - qrSize - 190 // 距底边100px
case "invitation":
// invitation类型精确设置二维码尺寸
qrSize = 360 // 固定尺寸320px
// 中间偏上位置
qrX = (imgWidth - qrSize) / 2 // 水平居中
qrY = 555 // 垂直位置200px
default:
// 默认promote样式
qrSize = 280 // 固定尺寸280px
qrX = 200 // 距左边180px
qrY = imgHeight - qrSize - 200 // 距底边100px
}
// 8. 生成指定尺寸的二维码图片
qrCodeImage := qrCode.Image(qrSize)
// 9. 直接绘制二维码(不添加背景)
dc.DrawImageAnchored(qrCodeImage, qrX+qrSize/2, qrY+qrSize/2, 0.5, 0.5)
// 11. 输出为字节数组
var buf bytes.Buffer
err = png.Encode(&buf, dc.Image())
if err != nil {
logx.Errorf("编码图片失败: %v", err)
return nil, "", fmt.Errorf("编码图片失败: %v", err)
}
logx.Infof("成功生成带二维码的图片,类型: %s, 二维码内容: %s, 图片尺寸: %dx%d, 二维码尺寸: %dx%d, 位置: (%d,%d)",
qrcodeType, qrcodeUrl, imgWidth, imgHeight, qrSize, qrSize, qrX, qrY)
return buf.Bytes(), "image/png", nil
}
// loadImage 加载图片文件
func (s *ImageService) loadImage(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
// 尝试解码PNG
img, err := png.Decode(file)
if err != nil {
// 如果PNG解码失败重新打开文件尝试JPEG
file.Close()
file, err = os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, err = jpeg.Decode(file)
if err != nil {
// 如果还是失败,使用通用解码器
file.Close()
file, err = os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err = image.Decode(file)
if err != nil {
return nil, err
}
}
}
return img, nil
}
// GetSupportedImageTypes 获取支持的图片类型列表
func (s *ImageService) GetSupportedImageTypes() []string {
return []string{"promote", "invitation"}
}
// CheckImageExists 检查指定类型的背景图是否存在
func (s *ImageService) CheckImageExists(qrcodeType string) bool {
var backgroundImageName string
switch qrcodeType {
case "promote":
backgroundImageName = "tg_qrcode_1.png"
case "invitation":
backgroundImageName = "yq_qrcode_1.png"
default:
backgroundImageName = "tg_qrcode_1.png"
}
imagePath := filepath.Join(s.baseImagePath, backgroundImageName)
_, err := os.Stat(imagePath)
return err == nil
}

View File

@@ -0,0 +1,416 @@
package tianyuanapi
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
// API调用相关错误类型
var (
ErrQueryEmpty = errors.New("查询为空")
ErrSystem = errors.New("接口异常")
ErrDecryptFail = errors.New("解密失败")
ErrRequestParam = errors.New("请求参数结构不正确")
ErrInvalidParam = errors.New("参数校验不正确")
ErrInvalidIP = errors.New("未经授权的IP")
ErrMissingAccessId = errors.New("缺少Access-Id")
ErrInvalidAccessId = errors.New("未经授权的AccessId")
ErrFrozenAccount = errors.New("账户已冻结")
ErrArrears = errors.New("账户余额不足,无法请求")
ErrProductNotFound = errors.New("产品不存在")
ErrProductDisabled = errors.New("产品已停用")
ErrNotSubscribed = errors.New("未订阅此产品")
ErrBusiness = errors.New("业务失败")
)
// 错误码映射 - 严格按照用户要求
var ErrorCodeMap = map[error]int{
ErrQueryEmpty: 1000,
ErrSystem: 1001,
ErrDecryptFail: 1002,
ErrRequestParam: 1003,
ErrInvalidParam: 1003,
ErrInvalidIP: 1004,
ErrMissingAccessId: 1005,
ErrInvalidAccessId: 1006,
ErrFrozenAccount: 1007,
ErrArrears: 1007,
ErrProductNotFound: 1008,
ErrProductDisabled: 1008,
ErrNotSubscribed: 1008,
ErrBusiness: 2001,
}
// ApiCallOptions API调用选项
type ApiCallOptions struct {
Json bool `json:"json,omitempty"` // 是否返回JSON格式
}
// Client 天元API客户端
type Client struct {
accessID string
key string
baseURL string
timeout time.Duration
client *http.Client
}
// Config 客户端配置
type Config struct {
AccessID string // 访问ID
Key string // AES密钥16进制
BaseURL string // API基础URL
Timeout time.Duration // 超时时间
}
// Request 请求参数
type Request struct {
InterfaceName string `json:"interfaceName"` // 接口名称
Params map[string]interface{} `json:"params"` // 请求参数
Timeout int `json:"timeout"` // 超时时间(毫秒)
Options *ApiCallOptions `json:"options"` // 调用选项
}
// ApiResponse HTTP API响应
type ApiResponse struct {
Code int `json:"code"`
Message string `json:"message"`
TransactionID string `json:"transaction_id"` // 流水号
Data string `json:"data"` // 加密的数据
}
// Response Call方法的响应
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Success bool `json:"success"`
TransactionID string `json:"transaction_id"` // 流水号
Data map[string]interface{} `json:"data"` // 解密后的数据
Timeout int64 `json:"timeout"` // 请求耗时(毫秒)
Error string `json:"error,omitempty"`
}
// NewClient 创建新的客户端实例
func NewClient(config Config) (*Client, error) {
// 参数校验
if config.AccessID == "" {
return nil, fmt.Errorf("accessID不能为空")
}
if config.Key == "" {
return nil, fmt.Errorf("key不能为空")
}
if config.BaseURL == "" {
config.BaseURL = "http://127.0.0.1:8080"
}
if config.Timeout == 0 {
config.Timeout = 60 * time.Second
}
// 验证密钥格式
if _, err := hex.DecodeString(config.Key); err != nil {
return nil, fmt.Errorf("无效的密钥格式必须是16进制字符串: %v", err)
}
return &Client{
accessID: config.AccessID,
key: config.Key,
baseURL: config.BaseURL,
timeout: config.Timeout,
client: &http.Client{
Timeout: config.Timeout,
},
}, nil
}
// Call 调用API接口
func (c *Client) Call(req Request) (*Response, error) {
startTime := time.Now()
// 参数校验
if err := c.validateRequest(req); err != nil {
return nil, fmt.Errorf("请求参数校验失败: %v", err)
}
// 加密参数
jsonData, err := json.Marshal(req.Params)
if err != nil {
return nil, fmt.Errorf("参数序列化失败: %v", err)
}
encryptedData, err := c.encrypt(string(jsonData))
if err != nil {
return nil, fmt.Errorf("数据加密失败: %v", err)
}
// 构建请求体
requestBody := map[string]interface{}{
"data": encryptedData,
}
// 添加选项
if req.Options != nil {
requestBody["options"] = req.Options
} else {
// 默认选项
defaultOptions := &ApiCallOptions{
Json: true,
}
requestBody["options"] = defaultOptions
}
requestBodyBytes, err := json.Marshal(requestBody)
if err != nil {
return nil, fmt.Errorf("请求体序列化失败: %v", err)
}
// 创建HTTP请求
url := fmt.Sprintf("%s/api/v1/%s", c.baseURL, req.InterfaceName)
httpReq, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBodyBytes))
if err != nil {
return nil, fmt.Errorf("创建HTTP请求失败: %v", err)
}
// 设置请求头
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Access-Id", c.accessID)
httpReq.Header.Set("User-Agent", "TianyuanAPI-Go-SDK/1.0.0")
// 发送请求
resp, err := c.client.Do(httpReq)
if err != nil {
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
return &Response{
Success: false,
Message: "请求失败",
Error: err.Error(),
Timeout: requestTime,
}, nil
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
return &Response{
Success: false,
Message: "读取响应失败",
Error: err.Error(),
Timeout: requestTime,
}, nil
}
// 解析HTTP API响应
var apiResp ApiResponse
if err := json.Unmarshal(body, &apiResp); err != nil {
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
return &Response{
Success: false,
Message: "响应解析失败",
Error: err.Error(),
Timeout: requestTime,
}, nil
}
// 计算请求耗时
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
// 构建Call方法的响应
response := &Response{
Code: apiResp.Code,
Message: apiResp.Message,
Success: apiResp.Code == 0,
TransactionID: apiResp.TransactionID,
Timeout: requestTime,
}
// 如果有加密数据,尝试解密
if apiResp.Data != "" {
decryptedData, err := c.decrypt(apiResp.Data)
if err == nil {
var decryptedMap map[string]interface{}
if json.Unmarshal([]byte(decryptedData), &decryptedMap) == nil {
response.Data = decryptedMap
}
}
}
// 根据响应码返回对应的错误
if apiResp.Code != 0 {
err := GetErrorByCode(apiResp.Code)
return nil, err
}
return response, nil
}
// CallInterface 简化接口调用方法
func (c *Client) CallInterface(interfaceName string, params map[string]interface{}, options ...*ApiCallOptions) (*Response, error) {
var opts *ApiCallOptions
if len(options) > 0 {
opts = options[0]
}
req := Request{
InterfaceName: interfaceName,
Params: params,
Timeout: 60000,
Options: opts,
}
return c.Call(req)
}
// validateRequest 校验请求参数
func (c *Client) validateRequest(req Request) error {
if req.InterfaceName == "" {
return fmt.Errorf("interfaceName不能为空")
}
if req.Params == nil {
return fmt.Errorf("params不能为空")
}
return nil
}
// encrypt AES CBC加密
func (c *Client) encrypt(plainText string) (string, error) {
keyBytes, err := hex.DecodeString(c.key)
if err != nil {
return "", err
}
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
// 生成随机IV
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
// 填充数据
paddedData := c.pkcs7Pad([]byte(plainText), aes.BlockSize)
// 加密
ciphertext := make([]byte, len(iv)+len(paddedData))
copy(ciphertext, iv)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[len(iv):], paddedData)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// decrypt AES CBC解密
func (c *Client) decrypt(encryptedText string) (string, error) {
keyBytes, err := hex.DecodeString(c.key)
if err != nil {
return "", err
}
ciphertext, err := base64.StdEncoding.DecodeString(encryptedText)
if err != nil {
return "", err
}
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
return "", fmt.Errorf("密文太短")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
if len(ciphertext)%aes.BlockSize != 0 {
return "", fmt.Errorf("密文长度不是块大小的倍数")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// 去除填充
unpaddedData, err := c.pkcs7Unpad(ciphertext)
if err != nil {
return "", err
}
return string(unpaddedData), nil
}
// pkcs7Pad PKCS7填充
func (c *Client) pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padtext...)
}
// pkcs7Unpad PKCS7去除填充
func (c *Client) pkcs7Unpad(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, fmt.Errorf("数据为空")
}
unpadding := int(data[length-1])
if unpadding > length {
return nil, fmt.Errorf("无效的填充")
}
return data[:length-unpadding], nil
}
// GetErrorByCode 根据错误码获取错误
func GetErrorByCode(code int) error {
// 对于有多个错误对应同一错误码的情况,返回第一个
switch code {
case 1000:
return ErrQueryEmpty
case 1001:
return ErrSystem
case 1002:
return ErrDecryptFail
case 1003:
return ErrRequestParam
case 1004:
return ErrInvalidIP
case 1005:
return ErrMissingAccessId
case 1006:
return ErrInvalidAccessId
case 1007:
return ErrFrozenAccount
case 1008:
return ErrProductNotFound
case 2001:
return ErrBusiness
default:
return fmt.Errorf("未知错误码: %d", code)
}
}
// GetCodeByError 根据错误获取错误码
func GetCodeByError(err error) int {
if code, exists := ErrorCodeMap[err]; exists {
return code
}
return -1
}

View File

@@ -0,0 +1,296 @@
package service
import (
"context"
"database/sql"
"znc-server/app/main/api/internal/config"
"znc-server/app/main/model"
"znc-server/common/ctxdata"
jwtx "znc-server/common/jwt"
"znc-server/common/xerr"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type UserService struct {
Config *config.Config
userModel model.UserModel
userAuthModel model.UserAuthModel
userTempModel model.UserTempModel
agentModel model.AgentModel
}
// NewUserService 创建UserService实例
func NewUserService(config *config.Config, userModel model.UserModel, userAuthModel model.UserAuthModel, userTempModel model.UserTempModel, agentModel model.AgentModel) *UserService {
return &UserService{
Config: config,
userModel: userModel,
userAuthModel: userAuthModel,
userTempModel: userTempModel,
agentModel: agentModel,
}
}
// GenerateUUIDUserId 生成UUID用户ID
func (s *UserService) GenerateUUIDUserId(ctx context.Context) (string, error) {
id := uuid.NewString()
return id, nil
}
// RegisterUUIDUser 注册UUID用户返回用户ID
func (s *UserService) RegisterUUIDUser(ctx context.Context) (int64, error) {
// 生成UUID
uuidStr, err := s.GenerateUUIDUserId(ctx)
if err != nil {
return 0, err
}
var userId int64
err = s.userModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
// 创建用户记录
user := &model.User{}
result, err := s.userModel.Insert(ctx, session, user)
if err != nil {
return err
}
userId, err = result.LastInsertId()
if err != nil {
return err
}
// 创建用户认证记录
userAuth := &model.UserAuth{
UserId: userId,
AuthType: model.UserAuthTypeUUID,
AuthKey: uuidStr,
}
_, err = s.userAuthModel.Insert(ctx, session, userAuth)
return err
})
if err != nil {
return 0, err
}
return userId, nil
}
// generalUserToken 生成用户token
func (s *UserService) GeneralUserToken(ctx context.Context, userID int64, userType int64) (string, error) {
platform, err := ctxdata.GetPlatformFromCtx(ctx)
if err != nil {
return "", err
}
var isAgent int64
var agentID int64
if userType == model.UserTypeNormal {
agent, err := s.agentModel.FindOneByUserId(ctx, userID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return "", err
}
if agent != nil {
agentID = agent.Id
isAgent = model.AgentStatusYes
}
} else {
userTemp, err := s.userTempModel.FindOne(ctx, userID)
if err != nil {
return "", err
}
if userTemp != nil {
userID = userTemp.Id
}
}
token, generaErr := jwtx.GenerateJwtToken(jwtx.JwtClaims{
UserId: userID,
AgentId: agentID,
Platform: platform,
UserType: userType,
IsAgent: isAgent,
}, s.Config.JwtAuth.AccessSecret, s.Config.JwtAuth.AccessExpire)
if generaErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "更新token, 生成token失败 : %d", userID)
}
return token, nil
}
// RegisterUser 注册用户返回用户ID
// 传入手机号自动注册如果ctx存在临时用户则临时用户转为正式用户
func (s *UserService) RegisterUser(ctx context.Context, mobile string) (int64, error) {
claims, err := ctxdata.GetClaimsFromCtx(ctx)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return 0, err
}
user, err := s.userModel.FindOneByMobile(ctx, sql.NullString{String: mobile, Valid: true})
if err != nil && !errors.Is(err, model.ErrNotFound) {
return 0, err
}
if user != nil {
return 0, errors.New("用户已注册")
}
// 普通注册
if claims == nil {
var userId int64
err = s.userModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
user := &model.User{
Mobile: sql.NullString{String: mobile, Valid: true},
}
result, err := s.userModel.Insert(ctx, session, user)
if err != nil {
return err
}
userId, err = result.LastInsertId()
if err != nil {
return err
}
s.userAuthModel.Insert(ctx, session, &model.UserAuth{
UserId: userId,
AuthType: model.UserAuthTypeMobile,
AuthKey: mobile,
})
return nil
})
if err != nil {
return 0, err
}
return userId, nil
}
// 双重判断是否已经注册
if claims.UserType == model.UserTypeNormal {
return 0, errors.New("用户已注册")
}
var userId int64
// 临时转正式注册
err = s.userModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
user := &model.User{
Mobile: sql.NullString{String: mobile, Valid: true},
}
result, err := s.userModel.Insert(ctx, session, user)
if err != nil {
return err
}
userId, err = result.LastInsertId()
if err != nil {
return err
}
_, err = s.userAuthModel.Insert(ctx, session, &model.UserAuth{
UserId: userId,
AuthType: model.UserAuthTypeMobile,
AuthKey: mobile,
})
if err != nil {
return err
}
err = s.TempUserBindUser(ctx, session, userId)
if err != nil {
return err
}
return nil
})
if err != nil {
return 0, err
}
return userId, nil
}
// TempUserBindUser 临时用户绑定用户
func (s *UserService) TempUserBindUser(ctx context.Context, session sqlx.Session, normalUserID int64) error {
claims, err := ctxdata.GetClaimsFromCtx(ctx)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return err
}
if claims == nil || claims.UserType != model.UserTypeTemp {
return errors.New("无临时用户")
}
// 使用事务上下文查询临时用户
userTemp, err := s.userTempModel.FindOne(ctx, claims.UserId)
if err != nil {
return err
}
// 检查是否已经注册过
userAuth, err := s.userAuthModel.FindOneByAuthTypeAuthKey(ctx, userTemp.AuthType, userTemp.AuthKey)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return err
}
if userAuth != nil {
return errors.New("临时用户已注册")
}
if session == nil {
err := s.userAuthModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
_, err = s.userAuthModel.Insert(ctx, session, &model.UserAuth{
UserId: normalUserID,
AuthType: userTemp.AuthType,
AuthKey: userTemp.AuthKey,
})
if err != nil {
return err
}
// 重新获取最新的userTemp数据确保版本号是最新的
latestUserTemp, err := s.userTempModel.FindOne(ctx, claims.UserId)
if err != nil {
return err
}
err = s.userTempModel.DeleteSoft(ctx, session, latestUserTemp)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
} else {
_, err = s.userAuthModel.Insert(ctx, session, &model.UserAuth{
UserId: normalUserID,
AuthType: userTemp.AuthType,
AuthKey: userTemp.AuthKey,
})
if err != nil {
return err
}
// 重新获取最新的userTemp数据确保版本号是最新的
latestUserTemp, err := s.userTempModel.FindOne(ctx, claims.UserId)
if err != nil {
return err
}
err = s.userTempModel.DeleteSoft(ctx, session, latestUserTemp)
if err != nil {
return err
}
return nil
}
}
// _bak_RegisterUUIDUser 注册UUID用户返回用户ID
func (s *UserService) _bak_RegisterUUIDUser(ctx context.Context) error {
// 生成UUID
uuidStr, err := s.GenerateUUIDUserId(ctx)
if err != nil {
return err
}
err = s.userTempModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
// 创建用户临时记录
userTemp := &model.UserTemp{
AuthType: model.UserAuthTypeUUID,
AuthKey: uuidStr,
}
_, err := s.userTempModel.Insert(ctx, session, userTemp)
return err
})
if err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,217 @@
package service
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"znc-server/app/main/api/internal/config"
tianyuanapi "znc-server/app/main/api/internal/service/tianyuanapi_sdk"
"github.com/tidwall/gjson"
)
type VerificationService struct {
c config.Config
tianyuanapi *tianyuanapi.Client
apiRequestService *ApiRequestService
}
func NewVerificationService(c config.Config, tianyuanapi *tianyuanapi.Client, apiRequestService *ApiRequestService) *VerificationService {
return &VerificationService{
c: c,
tianyuanapi: tianyuanapi,
apiRequestService: apiRequestService,
}
}
// 二要素
type TwoFactorVerificationRequest struct {
Name string
IDCard string
}
type TwoFactorVerificationResp struct {
Msg string `json:"msg"`
Success bool `json:"success"`
Code int `json:"code"`
Data *TwoFactorVerificationData `json:"data"` //
}
type TwoFactorVerificationData struct {
Birthday string `json:"birthday"`
Result int `json:"result"`
Address string `json:"address"`
OrderNo string `json:"orderNo"`
Sex string `json:"sex"`
Desc string `json:"desc"`
}
// 三要素
type ThreeFactorVerificationRequest struct {
Name string
IDCard string
Mobile string
}
// VerificationResult 定义校验结果结构体
type VerificationResult struct {
Passed bool
Err error
}
// ValidationError 定义校验错误类型
type ValidationError struct {
Message string
}
func (e *ValidationError) Error() string {
return e.Message
}
func (r *VerificationService) TwoFactorVerification(request TwoFactorVerificationRequest) (*VerificationResult, error) {
appCode := r.c.Ali.Code
requestUrl := "https://kzidcardv1.market.alicloudapi.com/api-mall/api/id_card/check"
// 构造查询参数
data := url.Values{}
data.Add("name", request.Name)
data.Add("idcard", request.IDCard)
req, err := http.NewRequest(http.MethodPost, requestUrl, strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("创建请求失败: %v", err)
}
req.Header.Set("Authorization", "APPCODE "+appCode)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("请求失败: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("请求失败, 状态码: %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("响应体读取失败:%v", err)
}
var twoFactorVerificationResp TwoFactorVerificationResp
err = json.Unmarshal(respBody, &twoFactorVerificationResp)
if err != nil {
return nil, fmt.Errorf("二要素解析错误: %v", err)
}
if !twoFactorVerificationResp.Success {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "请输入有效的身份证号码"},
}, nil
}
if twoFactorVerificationResp.Code != 200 {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: twoFactorVerificationResp.Msg},
}, nil
}
if twoFactorVerificationResp.Data.Result == 1 {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "姓名与身份证不一致"},
}, nil
}
return &VerificationResult{Passed: true, Err: nil}, nil
}
func (r *VerificationService) TwoFactorVerificationWest(request TwoFactorVerificationRequest) (*VerificationResult, error) {
resp, err := r.tianyuanapi.CallInterface("YYSYBE08", map[string]interface{}{
"name": request.Name,
"id_card": request.IDCard,
})
if err != nil {
return nil, fmt.Errorf("请求失败: %v", err)
}
respBytes, err := json.Marshal(resp.Data)
if err != nil {
return nil, fmt.Errorf("转换响应失败: %v", err)
}
// 使用gjson获取resultCode
resultCode := gjson.GetBytes(respBytes, "ctidRequest.ctidAuth.resultCode")
if !resultCode.Exists() {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "获取resultCode失败"},
}, nil
}
// 获取resultCode的第一个字符
resultCodeStr := resultCode.String()
if len(resultCodeStr) == 0 {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "resultCode为空"},
}, nil
}
firstChar := string(resultCodeStr[0])
if firstChar != "0" && firstChar != "5" {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "姓名与身份证不一致"},
}, nil
}
return &VerificationResult{Passed: true, Err: nil}, nil
}
func (r *VerificationService) ThreeFactorVerification(request ThreeFactorVerificationRequest) (*VerificationResult, error) {
resp, err := r.tianyuanapi.CallInterface("YYSY09CD", map[string]interface{}{
"name": request.Name,
"id_card": request.IDCard,
"mobile_no": request.Mobile,
})
if err != nil {
return nil, fmt.Errorf("请求失败: %v", err)
}
respBytes, err := json.Marshal(resp.Data)
if err != nil {
return nil, fmt.Errorf("转换响应失败: %v", err)
}
// 使用gjson获取resultCode
resultCode := gjson.GetBytes(respBytes, "ctidRequest.ctidAuth.resultCode")
if !resultCode.Exists() {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "身份信息异常"},
}, nil
}
// 获取resultCode的第一个字符
resultCodeStr := resultCode.String()
if len(resultCodeStr) == 0 {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "身份信息异常"},
}, nil
}
firstChar := string(resultCodeStr[0])
if firstChar != "0" && firstChar != "5" {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "姓名、证件号、手机号信息不一致"},
}, nil
}
return &VerificationResult{Passed: true, Err: nil}, nil
}

View File

@@ -0,0 +1,377 @@
package service
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"znc-server/app/main/api/internal/config"
"znc-server/app/main/model"
"znc-server/common/ctxdata"
"znc-server/pkg/lzkit/lzUtils"
"github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
"github.com/wechatpay-apiv3/wechatpay-go/core/downloader"
"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/app"
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
"github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
"github.com/wechatpay-apiv3/wechatpay-go/utils"
"github.com/zeromicro/go-zero/core/logx"
)
const (
TradeStateSuccess = "SUCCESS" // 支付成功
TradeStateRefund = "REFUND" // 转入退款
TradeStateNotPay = "NOTPAY" // 未支付
TradeStateClosed = "CLOSED" // 已关闭
TradeStateRevoked = "REVOKED" // 已撤销(付款码支付)
TradeStateUserPaying = "USERPAYING" // 用户支付中(付款码支付)
TradeStatePayError = "PAYERROR" // 支付失败(其他原因,如银行返回失败)
)
// InitType 初始化类型
type InitType string
const (
InitTypePlatformCert InitType = "platform_cert" // 平台证书初始化
InitTypeWxPayPubKey InitType = "wxpay_pubkey" // 微信支付公钥初始化
)
type WechatPayService struct {
config config.Config
wechatClient *core.Client
notifyHandler *notify.Handler
userAuthModel model.UserAuthModel
}
// NewWechatPayService 创建微信支付服务实例
func NewWechatPayService(c config.Config, userAuthModel model.UserAuthModel, initType InitType) *WechatPayService {
switch initType {
case InitTypePlatformCert:
return newWechatPayServiceWithPlatformCert(c, userAuthModel)
case InitTypeWxPayPubKey:
return newWechatPayServiceWithWxPayPubKey(c, userAuthModel)
default:
logx.Errorf("不支持的初始化类型: %s", initType)
panic(fmt.Sprintf("初始化失败,服务停止: %s", initType))
}
}
// newWechatPayServiceWithPlatformCert 使用平台证书初始化微信支付服务
func newWechatPayServiceWithPlatformCert(c config.Config, userAuthModel model.UserAuthModel) *WechatPayService {
// 从配置中加载商户信息
mchID := c.Wxpay.MchID
mchCertificateSerialNumber := c.Wxpay.MchCertificateSerialNumber
mchAPIv3Key := c.Wxpay.MchApiv3Key
// 从文件中加载商户私钥
mchPrivateKey, err := utils.LoadPrivateKeyWithPath(c.Wxpay.MchPrivateKeyPath)
if err != nil {
logx.Errorf("加载商户私钥失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err)) // 记录错误并停止程序
}
// 使用商户私钥和其他参数初始化微信支付客户端
opts := []core.ClientOption{
option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
}
client, err := core.NewClient(context.Background(), opts...)
if err != nil {
logx.Errorf("创建微信支付客户端失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err)) // 记录错误并停止程序
}
// 在初始化时获取证书访问器并创建 notifyHandler
certificateVisitor := downloader.MgrInstance().GetCertificateVisitor(mchID)
notifyHandler, err := notify.NewRSANotifyHandler(mchAPIv3Key, verifiers.NewSHA256WithRSAVerifier(certificateVisitor))
if err != nil {
logx.Errorf("获取证书访问器失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
logx.Infof("微信支付客户端初始化成功(平台证书方式)")
return &WechatPayService{
config: c,
wechatClient: client,
notifyHandler: notifyHandler,
userAuthModel: userAuthModel,
}
}
// newWechatPayServiceWithWxPayPubKey 使用微信支付公钥初始化微信支付服务
func newWechatPayServiceWithWxPayPubKey(c config.Config, userAuthModel model.UserAuthModel) *WechatPayService {
// 从配置中加载商户信息
mchID := c.Wxpay.MchID
mchCertificateSerialNumber := c.Wxpay.MchCertificateSerialNumber
mchAPIv3Key := c.Wxpay.MchApiv3Key
mchPrivateKeyPath := c.Wxpay.MchPrivateKeyPath
mchPublicKeyID := c.Wxpay.MchPublicKeyID
mchPublicKeyPath := c.Wxpay.MchPublicKeyPath
// 从文件中加载商户私钥
mchPrivateKey, err := utils.LoadPrivateKeyWithPath(mchPrivateKeyPath)
if err != nil {
logx.Errorf("加载商户私钥失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
// 从文件中加载微信支付平台证书
mchPublicKey, err := utils.LoadPublicKeyWithPath(mchPublicKeyPath)
if err != nil {
logx.Errorf("加载微信支付平台证书失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
// 使用商户私钥和其他参数初始化微信支付客户端
opts := []core.ClientOption{
option.WithWechatPayPublicKeyAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchPublicKeyID, mchPublicKey),
}
client, err := core.NewClient(context.Background(), opts...)
if err != nil {
logx.Errorf("创建微信支付客户端失败: %v", err)
panic(fmt.Sprintf("初始化失败,服务停止: %v", err))
}
// 初始化 notify.Handler
certificateVisitor := downloader.MgrInstance().GetCertificateVisitor(mchID)
notifyHandler := notify.NewNotifyHandler(
mchAPIv3Key,
verifiers.NewSHA256WithRSACombinedVerifier(certificateVisitor, mchPublicKeyID, *mchPublicKey))
logx.Infof("微信支付客户端初始化成功(微信支付公钥方式)")
return &WechatPayService{
config: c,
wechatClient: client,
notifyHandler: notifyHandler,
userAuthModel: userAuthModel,
}
}
// CreateWechatAppOrder 创建微信APP支付订单
func (w *WechatPayService) CreateWechatAppOrder(ctx context.Context, amount float64, description string, outTradeNo string) (string, error) {
totalAmount := lzUtils.ToWechatAmount(amount)
// 构建支付请求参数
payRequest := app.PrepayRequest{
Appid: core.String(w.config.Wxpay.AppID),
Mchid: core.String(w.config.Wxpay.MchID),
Description: core.String(description),
OutTradeNo: core.String(outTradeNo),
NotifyUrl: core.String(w.config.Wxpay.NotifyUrl),
Amount: &app.Amount{
Total: core.Int64(totalAmount),
},
}
// 初始化 AppApiService
svc := app.AppApiService{Client: w.wechatClient}
// 发起预支付请求
resp, result, err := svc.Prepay(ctx, payRequest)
if err != nil {
return "", fmt.Errorf("微信支付订单创建失败: %v, 状态码: %d", err, result.Response.StatusCode)
}
// 返回预支付交易会话标识
return *resp.PrepayId, nil
}
// CreateWechatMiniProgramOrder 创建微信小程序支付订单
func (w *WechatPayService) CreateWechatMiniProgramOrder(ctx context.Context, amount float64, description string, outTradeNo string, openid string) (interface{}, error) {
totalAmount := lzUtils.ToWechatAmount(amount)
// 构建支付请求参数
payRequest := jsapi.PrepayRequest{
Appid: core.String(w.config.WechatMini.AppID),
Mchid: core.String(w.config.Wxpay.MchID),
Description: core.String(description),
OutTradeNo: core.String(outTradeNo),
NotifyUrl: core.String(w.config.Wxpay.NotifyUrl),
Amount: &jsapi.Amount{
Total: core.Int64(totalAmount),
},
Payer: &jsapi.Payer{
Openid: core.String(openid), // 用户的 OpenID通过前端传入
}}
// 初始化 AppApiService
svc := jsapi.JsapiApiService{Client: w.wechatClient}
// 发起预支付请求
resp, result, err := svc.PrepayWithRequestPayment(ctx, payRequest)
if err != nil {
return "", fmt.Errorf("微信支付订单创建失败: %v, 状态码: %d", err, result.Response.StatusCode)
}
// 返回预支付交易会话标识
return resp, nil
}
// CreateWechatH5Order 创建微信H5支付订单
func (w *WechatPayService) CreateWechatH5Order(ctx context.Context, amount float64, description string, outTradeNo string, openid string) (interface{}, error) {
totalAmount := lzUtils.ToWechatAmount(amount)
// 构建支付请求参数
payRequest := jsapi.PrepayRequest{
Appid: core.String(w.config.WechatH5.AppID),
Mchid: core.String(w.config.Wxpay.MchID),
Description: core.String(description),
OutTradeNo: core.String(outTradeNo),
NotifyUrl: core.String(w.config.Wxpay.NotifyUrl),
Amount: &jsapi.Amount{
Total: core.Int64(totalAmount),
},
Payer: &jsapi.Payer{
Openid: core.String(openid), // 用户的 OpenID通过前端传入
}}
// 初始化 AppApiService
svc := jsapi.JsapiApiService{Client: w.wechatClient}
// 发起预支付请求
resp, result, err := svc.PrepayWithRequestPayment(ctx, payRequest)
logx.Infof("微信h5支付订单resp: %+v, result: %+v, err: %+v", resp, result, err)
if err != nil {
return "", fmt.Errorf("微信支付订单创建失败: %v, 状态码: %d", err, result.Response.StatusCode)
}
// 返回预支付交易会话标识
return resp, nil
}
// CreateWechatOrder 创建微信支付订单(集成 APP、H5、小程序
func (w *WechatPayService) CreateWechatOrder(ctx context.Context, amount float64, description string, outTradeNo string) (interface{}, error) {
// 根据 ctx 中的 platform 判断平台
platform := ctx.Value("platform").(string)
var prepayData interface{}
var err error
switch platform {
case model.PlatformWxMini:
userID, getUidErr := ctxdata.GetUidFromCtx(ctx)
if getUidErr != nil {
return "", getUidErr
}
userAuthModel, findAuthModelErr := w.userAuthModel.FindOneByUserIdAuthType(ctx, userID, model.UserAuthTypeWxMiniOpenID)
if findAuthModelErr != nil {
return "", findAuthModelErr
}
prepayData, err = w.CreateWechatMiniProgramOrder(ctx, amount, description, outTradeNo, userAuthModel.AuthKey)
if err != nil {
return "", err
}
case model.PlatformWxH5:
userID, getUidErr := ctxdata.GetUidFromCtx(ctx)
if getUidErr != nil {
return "", getUidErr
}
userAuthModel, findAuthModelErr := w.userAuthModel.FindOneByUserIdAuthType(ctx, userID, model.UserAuthTypeWxh5OpenID)
if findAuthModelErr != nil {
return "", findAuthModelErr
}
prepayData, err = w.CreateWechatH5Order(ctx, amount, description, outTradeNo, userAuthModel.AuthKey)
if err != nil {
return "", err
}
case model.PlatformApp:
// 如果是 APP 平台,调用 APP 支付订单创建
prepayData, err = w.CreateWechatAppOrder(ctx, amount, description, outTradeNo)
default:
return "", fmt.Errorf("不支持的支付平台: %s", platform)
}
// 如果创建支付订单失败,返回错误
if err != nil {
return "", fmt.Errorf("支付订单创建失败: %v", err)
}
// 返回预支付ID
return prepayData, nil
}
// HandleWechatPayNotification 处理微信支付回调
func (w *WechatPayService) HandleWechatPayNotification(ctx context.Context, req *http.Request) (*payments.Transaction, error) {
transaction := new(payments.Transaction)
_, err := w.notifyHandler.ParseNotifyRequest(ctx, req, transaction)
if err != nil {
return nil, fmt.Errorf("微信支付通知处理失败: %v", err)
}
// 返回交易信息
return transaction, nil
}
// HandleRefundNotification 处理微信退款回调
func (w *WechatPayService) HandleRefundNotification(ctx context.Context, req *http.Request) (*refunddomestic.Refund, error) {
refund := new(refunddomestic.Refund)
_, err := w.notifyHandler.ParseNotifyRequest(ctx, req, refund)
if err != nil {
return nil, fmt.Errorf("微信退款回调通知处理失败: %v", err)
}
return refund, nil
}
// QueryOrderStatus 主动查询订单状态
func (w *WechatPayService) QueryOrderStatus(ctx context.Context, transactionID string) (*payments.Transaction, error) {
svc := jsapi.JsapiApiService{Client: w.wechatClient}
// 调用 QueryOrderById 方法查询订单状态
resp, result, err := svc.QueryOrderById(ctx, jsapi.QueryOrderByIdRequest{
TransactionId: core.String(transactionID),
Mchid: core.String(w.config.Wxpay.MchID),
})
if err != nil {
return nil, fmt.Errorf("订单查询失败: %v, 状态码: %d", err, result.Response.StatusCode)
}
return resp, nil
}
// WeChatRefund 申请微信退款
func (w *WechatPayService) WeChatRefund(ctx context.Context, outTradeNo string, refundAmount float64, totalAmount float64) error {
// 生成唯一的退款单号
outRefundNo := fmt.Sprintf("%s-refund", outTradeNo)
// 初始化退款服务
svc := refunddomestic.RefundsApiService{Client: w.wechatClient}
// 创建退款请求
resp, result, err := svc.Create(ctx, refunddomestic.CreateRequest{
OutTradeNo: core.String(outTradeNo),
OutRefundNo: core.String(outRefundNo),
NotifyUrl: core.String(w.config.Wxpay.RefundNotifyUrl),
Amount: &refunddomestic.AmountReq{
Currency: core.String("CNY"),
Refund: core.Int64(lzUtils.ToWechatAmount(refundAmount)),
Total: core.Int64(lzUtils.ToWechatAmount(totalAmount)),
},
})
if err != nil {
return fmt.Errorf("微信订单申请退款错误: %v", err)
}
// 打印退款结果
logx.Infof("退款申请成功,状态码=%d退款单号=%s微信退款单号=%s", result.Response.StatusCode, *resp.OutRefundNo, *resp.RefundId)
return nil
}
// GenerateOutTradeNo 生成唯一订单号
func (w *WechatPayService) GenerateOutTradeNo() string {
length := 16
timestamp := time.Now().UnixNano()
timeStr := strconv.FormatInt(timestamp, 10)
randomPart := strconv.Itoa(int(timestamp % 1e6))
combined := timeStr + randomPart
if len(combined) >= length {
return combined[:length]
}
for len(combined) < length {
combined += strconv.Itoa(int(timestamp % 10))
}
return combined
}