Files
qnc-server-v3/app/main/api/internal/logic/pay/xpayadmindeliverlogic.go
2026-06-06 11:52:06 +08:00

100 lines
2.7 KiB
Go

package pay
import (
"context"
"net/http"
"strings"
"qnc-server/app/main/api/internal/svc"
"qnc-server/app/main/api/internal/types"
"qnc-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type XpayAdminDeliverLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewXpayAdminDeliverLogic(ctx context.Context, svcCtx *svc.ServiceContext) *XpayAdminDeliverLogic {
return &XpayAdminDeliverLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
type XpayAdminDeliverResp struct {
Credited bool `json:"credited"`
Notified bool `json:"notified"`
WechatDetail string `json:"wechat_detail"`
Errors []string `json:"errors"`
}
func (l *XpayAdminDeliverLogic) XpayAdminDeliver(req *types.XpayAdminDeliverReq, r *http.Request) (*XpayAdminDeliverResp, error) {
auth := r.Header.Get("Authorization")
token := strings.TrimPrefix(auth, "Bearer ")
if token == "" || token != l.svcCtx.Config.WechatXpay.AdminToken {
return nil, errors.Wrapf(xerr.NewErrMsg("未授权"), "")
}
order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
}
resp := &XpayAdminDeliverResp{WechatDetail: "ok"}
if order.Status == "paid" {
resp.Credited = false
return resp, nil
}
openid, err := l.svcCtx.XpayService.GetWxMiniOpenID(l.ctx, l.svcCtx.UserAuthModel, order.UserId)
if err != nil {
resp.Errors = append(resp.Errors, err.Error())
return resp, nil
}
sessionKey, err := l.svcCtx.XpayService.GetSessionKey(l.ctx, order.UserId)
if err != nil {
resp.Errors = append(resp.Errors, "session_key 不可用: "+err.Error())
return resp, nil
}
status, qErr := l.svcCtx.XpayService.QueryOrder(l.ctx, openid, order.OrderNo, sessionKey)
if qErr != nil {
resp.Errors = append(resp.Errors, qErr.Error())
resp.WechatDetail = qErr.Error()
return resp, nil
}
if !serviceIsPaid(status.Status) {
resp.Errors = append(resp.Errors, "微信侧订单未支付")
return resp, nil
}
credited, fulfillErr := fulfillQueryOrderPaid(l.ctx, l.svcCtx, order, "", status.PaidFee)
resp.Credited = credited
if fulfillErr != nil {
resp.Errors = append(resp.Errors, fulfillErr.Error())
}
if notifyErr := l.svcCtx.XpayService.NotifyProvideGoods(l.ctx, openid, order.OrderNo, "", sessionKey); notifyErr != nil {
resp.Notified = false
resp.WechatDetail = notifyErr.Error()
resp.Errors = append(resp.Errors, notifyErr.Error())
} else {
resp.Notified = true
_ = l.svcCtx.XpayService.MarkNotified(l.ctx, order.OrderNo)
}
return resp, nil
}
func serviceIsPaid(status int) bool {
return status == 2 || status == 3 || status == 4
}