68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package pay
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"strings"
|
|
"time"
|
|
|
|
commonpb "gitea.haiyihy.com/hy/chatappcommon/proto"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// Service 实现支付下单逻辑,当前只返回模拟结果,不写数据库。
|
|
type Service struct{}
|
|
|
|
// New 创建支付服务。
|
|
func New() *Service {
|
|
return &Service{}
|
|
}
|
|
|
|
// Pay 校验支付参数并返回模拟支付结果。
|
|
func (s *Service) Pay(_ context.Context, request *commonpb.PayRequest) (*commonpb.PayResponse, error) {
|
|
orderNo := strings.TrimSpace(request.GetOrderNo())
|
|
userID := strings.TrimSpace(request.GetUserId())
|
|
amount := strings.TrimSpace(request.GetAmount())
|
|
currency := strings.TrimSpace(request.GetCurrency())
|
|
payMethod := strings.TrimSpace(request.GetPayMethod())
|
|
subject := strings.TrimSpace(request.GetSubject())
|
|
|
|
if orderNo == "" {
|
|
return nil, status.Error(codes.InvalidArgument, "order_no is required")
|
|
}
|
|
if userID == "" {
|
|
return nil, status.Error(codes.InvalidArgument, "user_id is required")
|
|
}
|
|
if amount == "" {
|
|
return nil, status.Error(codes.InvalidArgument, "amount is required")
|
|
}
|
|
if currency == "" {
|
|
currency = "USD"
|
|
}
|
|
if payMethod == "" {
|
|
payMethod = "unknown"
|
|
}
|
|
|
|
return &commonpb.PayResponse{
|
|
PaymentId: "pay_" + randomID(),
|
|
OrderNo: orderNo,
|
|
UserId: userID,
|
|
Status: "processing",
|
|
Amount: amount,
|
|
Currency: currency,
|
|
PayMethod: payMethod,
|
|
Subject: subject,
|
|
CreatedAt: time.Now().UTC().Format(time.RFC3339),
|
|
}, nil
|
|
}
|
|
|
|
func randomID() string {
|
|
buffer := make([]byte, 8)
|
|
if _, err := rand.Read(buffer); err == nil {
|
|
return hex.EncodeToString(buffer)
|
|
}
|
|
return "fallback"
|
|
}
|