first commit
This commit is contained in:
186
app/user/cmd/api/internal/service/alipayService.go
Normal file
186
app/user/cmd/api/internal/service/alipayService.go
Normal file
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
mathrand "math/rand"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
"tydata-server/pkg/lzkit/lzUtils"
|
||||
)
|
||||
|
||||
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))
|
||||
}
|
||||
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, brand string) (string, error) {
|
||||
var returnURL string
|
||||
if brand == "tyc" {
|
||||
returnURL = "https://www.tianyuancha.com/report"
|
||||
} else {
|
||||
returnURL = a.config.ReturnURL
|
||||
}
|
||||
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: 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, brand string) (string, error) {
|
||||
// 根据 ctx 中的 platform 判断平台
|
||||
platform, platformOk := ctx.Value("platform").(string)
|
||||
if !platformOk {
|
||||
return "", fmt.Errorf("无的支付平台: %s", platform)
|
||||
}
|
||||
switch platform {
|
||||
case "app":
|
||||
// 调用App支付的创建方法
|
||||
return a.CreateAlipayAppOrder(amount, subject, outTradeNo)
|
||||
case "h5":
|
||||
// 调用H5支付的创建方法,并传入 returnUrl
|
||||
return a.CreateAlipayH5Order(amount, subject, outTradeNo, brand)
|
||||
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("%s-refund", 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)
|
||||
}
|
||||
|
||||
// GenerateOutTradeNo 生成唯一订单号的函数
|
||||
func (a *AliPayService) GenerateOutTradeNo() string {
|
||||
length := 16
|
||||
// 获取当前时间戳
|
||||
timestamp := time.Now().UnixNano()
|
||||
|
||||
// 转换为字符串
|
||||
timeStr := strconv.FormatInt(timestamp, 10)
|
||||
|
||||
// 生成随机数
|
||||
mathrand.Seed(time.Now().UnixNano())
|
||||
randomPart := strconv.Itoa(mathrand.Intn(1000000))
|
||||
|
||||
// 组合时间戳和随机数
|
||||
combined := timeStr + randomPart
|
||||
|
||||
// 如果长度超出指定值,则截断;如果不够,则填充随机字符
|
||||
if len(combined) >= length {
|
||||
return combined[:length]
|
||||
}
|
||||
|
||||
// 如果长度不够,填充0
|
||||
for len(combined) < length {
|
||||
combined += strconv.Itoa(mathrand.Intn(10)) // 填充随机数
|
||||
}
|
||||
|
||||
return combined
|
||||
}
|
||||
938
app/user/cmd/api/internal/service/apirequestService.go
Normal file
938
app/user/cmd/api/internal/service/apirequestService.go
Normal file
@@ -0,0 +1,938 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
"tydata-server/app/user/model"
|
||||
"tydata-server/pkg/lzkit/crypto"
|
||||
)
|
||||
|
||||
type ApiRequestService struct {
|
||||
config config.Config
|
||||
westDexService *WestDexService
|
||||
yushanService *YushanService
|
||||
featureModel model.FeatureModel
|
||||
productFeatureModel model.ProductFeatureModel
|
||||
}
|
||||
|
||||
// NewApiRequestService 是一个构造函数,用于初始化 ApiRequestService
|
||||
func NewApiRequestService(c config.Config, westDexService *WestDexService, yushanService *YushanService, featureModel model.FeatureModel, productFeatureModel model.ProductFeatureModel) *ApiRequestService {
|
||||
return &ApiRequestService{
|
||||
config: c,
|
||||
featureModel: featureModel,
|
||||
productFeatureModel: productFeatureModel,
|
||||
westDexService: westDexService,
|
||||
yushanService: yushanService,
|
||||
}
|
||||
}
|
||||
|
||||
type APIResponseData struct {
|
||||
ApiID string `json:"apiID"`
|
||||
Data json.RawMessage `json:"data"` // 这里用 RawMessage 来存储原始的 data
|
||||
Success bool `json:"success"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ProcessRequests 处理请求
|
||||
func (a *ApiRequestService) ProcessRequests(params []byte, productID int64) ([]byte, error) {
|
||||
var ctx, cancel = context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
build := a.productFeatureModel.SelectBuilder().Where(squirrel.Eq{
|
||||
"product_id": productID,
|
||||
})
|
||||
productFeatureList, findProductFeatureErr := a.productFeatureModel.FindAll(ctx, build, "")
|
||||
if findProductFeatureErr != nil {
|
||||
return nil, findProductFeatureErr
|
||||
}
|
||||
var featureIDs []int64
|
||||
for _, pf := range productFeatureList {
|
||||
featureIDs = append(featureIDs, pf.FeatureId)
|
||||
}
|
||||
if len(featureIDs) == 0 {
|
||||
return nil, errors.New("featureIDs 是空的")
|
||||
}
|
||||
builder := a.featureModel.SelectBuilder().Where(squirrel.Eq{"id": featureIDs})
|
||||
featureList, findFeatureErr := a.featureModel.FindAll(ctx, builder, "")
|
||||
if findFeatureErr != nil {
|
||||
return nil, findFeatureErr
|
||||
}
|
||||
if len(featureList) == 0 {
|
||||
return nil, errors.New("处理请求错误,产品无对应接口功能")
|
||||
}
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
resultsCh = make(chan APIResponseData, len(featureList))
|
||||
errorsCh = make(chan error, len(featureList))
|
||||
errorCount int32
|
||||
errorLimit = 1
|
||||
)
|
||||
|
||||
for i, feature := range featureList {
|
||||
wg.Add(1)
|
||||
go func(i int, feature *model.Feature) {
|
||||
defer wg.Done()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
result := APIResponseData{
|
||||
ApiID: feature.ApiId,
|
||||
Success: false,
|
||||
}
|
||||
// 请求参数预处理
|
||||
resp, preprocessErr := a.PreprocessRequestApi(params, feature.ApiId)
|
||||
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
||||
if preprocessErr != nil {
|
||||
result.Timestamp = timestamp
|
||||
result.Error = preprocessErr.Error()
|
||||
result.Data = resp
|
||||
resultsCh <- result
|
||||
errorsCh <- fmt.Errorf("请求失败: %v", preprocessErr)
|
||||
atomic.AddInt32(&errorCount, 1)
|
||||
if atomic.LoadInt32(&errorCount) >= int32(errorLimit) {
|
||||
cancel()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
result.Data = resp
|
||||
result.Success = true
|
||||
result.Timestamp = timestamp
|
||||
resultsCh <- result
|
||||
}(i, feature)
|
||||
}
|
||||
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(resultsCh)
|
||||
close(errorsCh)
|
||||
}()
|
||||
// 收集所有结果并合并
|
||||
var responseData []APIResponseData
|
||||
for result := range resultsCh {
|
||||
responseData = append(responseData, result)
|
||||
}
|
||||
if atomic.LoadInt32(&errorCount) >= int32(errorLimit) {
|
||||
var allErrors []error
|
||||
for err := range errorsCh {
|
||||
allErrors = append(allErrors, err)
|
||||
}
|
||||
return nil, fmt.Errorf("请求失败次数超过 %d 次: %v", errorLimit, allErrors)
|
||||
}
|
||||
|
||||
combinedResponse, err := json.Marshal(responseData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("响应数据转 JSON 失败: %+v", err)
|
||||
}
|
||||
|
||||
return combinedResponse, nil
|
||||
}
|
||||
|
||||
// ------------------------------------请求处理器--------------------------
|
||||
var requestProcessors = map[string]func(*ApiRequestService, []byte) ([]byte, error){
|
||||
"G09SC02": (*ApiRequestService).ProcessG09SC02Request,
|
||||
"G27BJ05": (*ApiRequestService).ProcessG27BJ05Request,
|
||||
"G26BJ05": (*ApiRequestService).ProcessG26BJ05Request,
|
||||
"G34BJ03": (*ApiRequestService).ProcessG34BJ03Request,
|
||||
"G35SC01": (*ApiRequestService).ProcessG35SC01Request,
|
||||
"G28BJ05": (*ApiRequestService).ProcessG28BJ05Request,
|
||||
"G05HZ01": (*ApiRequestService).ProcessG05HZ01Request,
|
||||
"Q23SC01": (*ApiRequestService).ProcessQ23SC01Request,
|
||||
"G15BJ02": (*ApiRequestService).ProcessG15BJ02Request,
|
||||
"G17BJ02": (*ApiRequestService).ProcessG17BJ02Request,
|
||||
"G08SC02": (*ApiRequestService).ProcessG08SC02Request,
|
||||
"KZEYS": (*ApiRequestService).ProcessKZEYSRequest,
|
||||
"P_C_B332": (*ApiRequestService).ProcessP_C_B332Request,
|
||||
"FIN019": (*ApiRequestService).ProcessFIN019Request,
|
||||
"CAR061": (*ApiRequestService).ProcessCAR061Request,
|
||||
"G10SC02": (*ApiRequestService).ProcessG10SC02Request,
|
||||
"G03HZ01": (*ApiRequestService).ProcessG03HZ01Request,
|
||||
"G02BJ02": (*ApiRequestService).ProcessG02BJ02Request,
|
||||
"G19BJ02": (*ApiRequestService).ProcessG19BJ02Request,
|
||||
"G20GZ01": (*ApiRequestService).ProcessG20GZ01Request,
|
||||
}
|
||||
|
||||
// PreprocessRequestApi 调用指定的请求处理函数
|
||||
func (a *ApiRequestService) PreprocessRequestApi(params []byte, apiID string) ([]byte, error) {
|
||||
if processor, exists := requestProcessors[apiID]; exists {
|
||||
return processor(a, params) // 调用 ApiRequestService 方法
|
||||
}
|
||||
|
||||
return nil, errors.New("api请求, 未找到相应的处理程序")
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG09SC02Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() {
|
||||
return nil, errors.New("api请求, G09SC02, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"certNumMan": a.westDexService.Encrypt(idCard.String()),
|
||||
"nameMan": a.westDexService.Encrypt(name.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G09SC02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
result := gjson.GetBytes(resp, "data.0.maritalStatus")
|
||||
|
||||
if result.Exists() {
|
||||
responseMap := map[string]string{"status": result.String()}
|
||||
jsonResponse, err := json.Marshal(responseMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return jsonResponse, nil
|
||||
} else {
|
||||
return nil, errors.New("查询为空")
|
||||
}
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG27BJ05Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() || !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G27BJ05, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"id": a.westDexService.Encrypt(idCard.String()),
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"cell": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G27BJ05", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 获取 code 字段
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
if !codeResult.Exists() {
|
||||
return nil, fmt.Errorf("code 字段不存在")
|
||||
}
|
||||
if codeResult.String() != "00" {
|
||||
return nil, fmt.Errorf("未匹配到相关结果")
|
||||
}
|
||||
|
||||
// 获取 data 字段
|
||||
dataResult := gjson.GetBytes(resp, "data")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("data 字段不存在")
|
||||
}
|
||||
|
||||
// 将 data 字段解析为 map
|
||||
var dataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(dataResult.Raw), &dataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
// 删除指定字段
|
||||
delete(dataMap, "swift_number")
|
||||
delete(dataMap, "DataStrategy")
|
||||
|
||||
// 重新编码为 JSON
|
||||
modifiedData, err := json.Marshal(dataMap)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("编码修改后的 data 失败: %v", err)
|
||||
}
|
||||
return modifiedData, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG26BJ05Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() || !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G26BJ05, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"id": a.westDexService.Encrypt(idCard.String()),
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"cell": a.westDexService.Encrypt(mobile.String()),
|
||||
"time_range": 5,
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G26BJ05", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
if !codeResult.Exists() {
|
||||
return nil, fmt.Errorf("code 字段不存在")
|
||||
}
|
||||
if codeResult.String() != "00" {
|
||||
return nil, fmt.Errorf("未匹配到相关结果")
|
||||
}
|
||||
|
||||
// 获取 data 字段
|
||||
dataResult := gjson.GetBytes(resp, "data")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("data 字段不存在")
|
||||
}
|
||||
|
||||
// 将 data 字段解析为 map
|
||||
var dataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(dataResult.Raw), &dataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
// 删除指定字段
|
||||
delete(dataMap, "swift_number")
|
||||
delete(dataMap, "DataStrategy")
|
||||
|
||||
// 重新编码为 JSON
|
||||
modifiedData, err := json.Marshal(dataMap)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("编码修改后的 data 失败: %v", err)
|
||||
}
|
||||
return modifiedData, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG34BJ03Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() {
|
||||
return nil, errors.New("api请求, G34BJ03, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"id_card": a.westDexService.Encrypt(idCard.String()),
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G34BJ03", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
dataResult := gjson.GetBytes(resp, "negative_info.data.risk_level")
|
||||
if dataResult.Exists() {
|
||||
// 如果字段存在,构造包含 "status" 的 JSON 响应
|
||||
responseMap := map[string]string{"risk_level": dataResult.String()}
|
||||
jsonResponse, err := json.Marshal(responseMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return jsonResponse, nil
|
||||
} else {
|
||||
return nil, errors.New("查询为空")
|
||||
}
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG35SC01Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() {
|
||||
return nil, errors.New("api请求, G35SC01, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"idcard": a.westDexService.Encrypt(idCard.String()),
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"inquired_auth": a.westDexService.GetDateRange(),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G35SC01", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 第一步:提取外层的 data 字段
|
||||
dataResult := gjson.GetBytes(resp, "data")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("外层 data 字段不存在")
|
||||
}
|
||||
|
||||
// 第二步:解析外层 data 的 JSON 字符串
|
||||
var outerDataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(dataResult.String()), &outerDataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析外层 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
// 第三步:提取内层的 data 字段
|
||||
innerData, ok := outerDataMap["data"].(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("内层 data 字段不存在或类型错误")
|
||||
}
|
||||
|
||||
if innerData == "" || innerData == "{}" || innerData == "[]" {
|
||||
innerData = "{}"
|
||||
}
|
||||
|
||||
// 第四步:解析内层 data 的 JSON 字符串
|
||||
var finalDataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(innerData), &finalDataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析内层 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
finalDataBytes, err := json.Marshal(finalDataMap)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("编码最终的 JSON 对象失败: %v", err)
|
||||
}
|
||||
|
||||
return finalDataBytes, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG28BJ05Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() || !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G28BJ05, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"id": a.westDexService.Encrypt(idCard.String()),
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"cell": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G28BJ05", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 获取 code 字段
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
if !codeResult.Exists() {
|
||||
return nil, fmt.Errorf("code 字段不存在")
|
||||
}
|
||||
if codeResult.String() != "00" {
|
||||
return nil, fmt.Errorf("未匹配到相关结果")
|
||||
}
|
||||
|
||||
// 获取 data 字段
|
||||
dataResult := gjson.GetBytes(resp, "data")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("data 字段不存在")
|
||||
}
|
||||
|
||||
// 将 data 字段解析为 map
|
||||
var dataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(dataResult.Raw), &dataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
// 删除指定字段
|
||||
delete(dataMap, "swift_number")
|
||||
delete(dataMap, "DataStrategy")
|
||||
|
||||
// 重新编码为 JSON
|
||||
modifiedData, err := json.Marshal(dataMap)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("编码修改后的 data 失败: %v", err)
|
||||
}
|
||||
return modifiedData, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG05HZ01Request(params []byte) ([]byte, error) {
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !idCard.Exists() {
|
||||
return nil, errors.New("api请求, G05HZ01, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"pid": crypto.Md5Encrypt(idCard.String()),
|
||||
}
|
||||
resp, callApiErr := a.westDexService.G05HZ01CallAPI("G05HZ01", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 处理股东人企关系的响应数据
|
||||
code := gjson.GetBytes(resp, "code")
|
||||
if !code.Exists() {
|
||||
return nil, fmt.Errorf("响应中缺少 code 字段")
|
||||
}
|
||||
|
||||
// 判断 code 是否等于 "0000"
|
||||
if code.String() == "0000" {
|
||||
// 获取 data 字段的值
|
||||
data := gjson.GetBytes(resp, "data")
|
||||
if !data.Exists() {
|
||||
return nil, fmt.Errorf("响应中缺少 data 字段")
|
||||
}
|
||||
// 返回 data 字段的内容
|
||||
return []byte(data.Raw), nil
|
||||
}
|
||||
|
||||
// code 不等于 "0000",返回错误
|
||||
return nil, fmt.Errorf("响应code错误%s", code.String())
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessQ23SC01Request(params []byte) ([]byte, error) {
|
||||
entName := gjson.GetBytes(params, "ent_name")
|
||||
entCode := gjson.GetBytes(params, "ent_code")
|
||||
|
||||
if !entName.Exists() || !entCode.Exists() {
|
||||
return nil, errors.New("api请求, Q23SC01, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"uscc": a.westDexService.Encrypt(entCode.String()),
|
||||
"org_name": a.westDexService.Encrypt(entName.String()),
|
||||
"inquired_auth": a.westDexService.GetDateRange(),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("Q23SC01", request)
|
||||
logx.Infof("企业涉诉返回%+v", string(resp))
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 第一步:提取外层的 data 字段
|
||||
dataResult := gjson.GetBytes(resp, "data")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("外层 data 字段不存在")
|
||||
}
|
||||
|
||||
// 第二步:解析外层 data 的 JSON 字符串
|
||||
var outerDataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(dataResult.String()), &outerDataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析外层 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
// 第三步:提取内层的 data 字段
|
||||
innerData, ok := outerDataMap["data"].(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("内层 data 字段不存在或类型错误")
|
||||
}
|
||||
|
||||
// 第四步:解析内层 data 的 JSON 字符串
|
||||
var finalDataMap map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(innerData), &finalDataMap); err != nil {
|
||||
return nil, fmt.Errorf("解析内层 data 字段失败: %v", err)
|
||||
}
|
||||
|
||||
// 将最终的 JSON 对象编码为字节数组返回
|
||||
finalDataBytes, err := json.Marshal(finalDataMap)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("编码最终的 JSON 对象失败: %v", err)
|
||||
}
|
||||
|
||||
statusResult := gjson.GetBytes(finalDataBytes, "status.status")
|
||||
if statusResult.Exists() || statusResult.Int() == -1 {
|
||||
return nil, fmt.Errorf("企业涉诉为空: %+v", finalDataBytes)
|
||||
}
|
||||
return finalDataBytes, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG15BJ02Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() || !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G15BJ02, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"idNo": a.westDexService.Encrypt(idCard.String()),
|
||||
"phone": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G15BJ02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
dataResult := gjson.GetBytes(resp, "data.code")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("code 字段不存在")
|
||||
}
|
||||
code := dataResult.Int()
|
||||
// 处理允许的 code 值
|
||||
if code == 1000 || code == 1003 || code == 1004 || code == 1005 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("三要素核验失败: %+v", resp)
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG17BJ02Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !name.Exists() || !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G17BJ02, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"phone": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G17BJ02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
dataResult := gjson.GetBytes(resp, "data.code")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("code 字段不存在")
|
||||
}
|
||||
code := dataResult.Int()
|
||||
// 处理允许的 code 值
|
||||
if code == 1000 || code == 1001 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("手机二要素核验失败: %+v", resp)
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG08SC02Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() {
|
||||
return nil, errors.New("api请求, G08SC02, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"xm": a.westDexService.Encrypt(name.String()),
|
||||
"gmsfzhm": a.westDexService.Encrypt(idCard.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G08SC02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessKZEYSRequest(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !name.Exists() || !idCard.Exists() {
|
||||
return nil, errors.New("api请求, KZEYS, 获取相关参数失败")
|
||||
}
|
||||
|
||||
appCode := a.config.Ali.Code
|
||||
requestUrl := "https://kzidcardv1.market.alicloudapi.com/api-mall/api/id_card/check"
|
||||
|
||||
// 构造查询参数
|
||||
data := url.Values{}
|
||||
data.Add("name", name.String())
|
||||
data.Add("idcard", idCard.String())
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, requestUrl, strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("KZEYS 创建请求失败: %+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("KZEYS 请求失败: %+v", err)
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("KZEYS 请求失败, 状态码: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("KZEYS 响应体读取失败:%v", err)
|
||||
}
|
||||
// 使用 gjson 解析 JSON 数据
|
||||
code := gjson.GetBytes(respBody, "code").Int()
|
||||
if code != 200 {
|
||||
msg := gjson.GetBytes(respBody, "msg").String()
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return nil, fmt.Errorf("KZEYS 响应失败: %s", msg)
|
||||
}
|
||||
|
||||
respData := gjson.GetBytes(respBody, "data")
|
||||
if !respData.Exists() {
|
||||
return nil, fmt.Errorf("KZEYS 响应, data 字段不存在")
|
||||
}
|
||||
dataRaw := respData.Raw
|
||||
// 成功返回
|
||||
return []byte(dataRaw), nil
|
||||
}
|
||||
|
||||
// 人车核验
|
||||
func (a *ApiRequestService) ProcessP_C_B332Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
carType := gjson.GetBytes(params, "car_type")
|
||||
carLicense := gjson.GetBytes(params, "car_license")
|
||||
if !name.Exists() || !carType.Exists() || !carLicense.Exists() {
|
||||
return nil, errors.New("api请求, P_C_B332, 获取相关参数失败: car_number")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"name": name.String(),
|
||||
"carType": carType.String(),
|
||||
"carNumber": carLicense.String(),
|
||||
}
|
||||
resp, err := a.yushanService.request("P_C_B332", request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("人车核验查询失败: %+v", err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 银行卡黑名单
|
||||
func (a *ApiRequestService) ProcessFIN019Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
bankCard := gjson.GetBytes(params, "bank_card")
|
||||
if !name.Exists() || !idCard.Exists() || !mobile.Exists() || !bankCard.Exists() {
|
||||
return nil, errors.New("api请求, FIN019, 获取相关参数失败: car_number")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"name": name.String(),
|
||||
"cardNo": idCard.String(),
|
||||
"mobile": mobile.String(),
|
||||
"cardld": bankCard.String(),
|
||||
}
|
||||
resp, err := a.yushanService.request("FIN019", request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("银行卡黑名单查询失败: %+v", err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 名下车辆
|
||||
func (a *ApiRequestService) ProcessCAR061Request(params []byte) ([]byte, error) {
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
|
||||
if !idCard.Exists() {
|
||||
return nil, errors.New("api请求, CAR061, 获取相关参数失败")
|
||||
}
|
||||
request := map[string]interface{}{
|
||||
"cardNo": idCard.String(),
|
||||
}
|
||||
resp, err := a.yushanService.request("CAR061", request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("名下车辆查询失败: %+v", err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (a *ApiRequestService) ProcessG10SC02Request(params []byte) ([]byte, error) {
|
||||
// 提取男方和女方信息
|
||||
nameMan := gjson.GetBytes(params, "nameMan")
|
||||
idCardMan := gjson.GetBytes(params, "idCardMan")
|
||||
nameWoman := gjson.GetBytes(params, "nameWoman")
|
||||
idCardWoman := gjson.GetBytes(params, "idCardWoman")
|
||||
|
||||
// 校验是否存在必要参数
|
||||
if !nameMan.Exists() || !idCardMan.Exists() || !nameWoman.Exists() || !idCardWoman.Exists() {
|
||||
return nil, errors.New("请求参数缺失:需要提供男方和女方的姓名及身份证号")
|
||||
}
|
||||
|
||||
// 构造请求数据
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"certNumMan": a.westDexService.Encrypt(idCardMan.String()),
|
||||
"nameMan": a.westDexService.Encrypt(nameMan.String()),
|
||||
"certNumWoman": a.westDexService.Encrypt(idCardWoman.String()),
|
||||
"nameWoman": a.westDexService.Encrypt(nameWoman.String()),
|
||||
},
|
||||
}
|
||||
|
||||
// 调用 API
|
||||
resp, callApiErr := a.westDexService.CallAPI("G10SC02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
|
||||
// 解析响应数据
|
||||
code := gjson.GetBytes(resp, "code").String()
|
||||
|
||||
// 状态码校验
|
||||
if code != "200" {
|
||||
return nil, fmt.Errorf("婚姻查询失败:%s", string(resp))
|
||||
}
|
||||
|
||||
result := gjson.GetBytes(resp, "data.0.maritalStatus")
|
||||
|
||||
if result.Exists() {
|
||||
responseMap := map[string]string{"status": result.String()}
|
||||
jsonResponse, err := json.Marshal(responseMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return jsonResponse, nil
|
||||
} else {
|
||||
return nil, errors.New("查询为空")
|
||||
}
|
||||
}
|
||||
|
||||
// 手机号码风险
|
||||
func (a *ApiRequestService) ProcessG03HZ01Request(params []byte) ([]byte, error) {
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G03HZ01, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"mobile": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G03HZ01", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 获取 code 字段
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
if !codeResult.Exists() || codeResult.String() != "0000" {
|
||||
return nil, fmt.Errorf("查询手机号码风险失败, %s", string(resp))
|
||||
}
|
||||
data := gjson.GetBytes(resp, "data.data")
|
||||
if !data.Exists() {
|
||||
return nil, fmt.Errorf("查询手机号码风险失败, %s", string(resp))
|
||||
}
|
||||
return []byte(data.Raw), nil
|
||||
}
|
||||
|
||||
// 手机在网时长
|
||||
func (a *ApiRequestService) ProcessG02BJ02Request(params []byte) ([]byte, error) {
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
|
||||
if !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G02BJ02, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"phone": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G02BJ02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 获取 code 字段
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
validCodes := map[string]bool{"1006": true, "1007": true, "1008": true, "1009": true, "1010": true}
|
||||
if !validCodes[codeResult.String()] {
|
||||
return nil, fmt.Errorf("查询手机在网时长失败, %s", string(resp))
|
||||
}
|
||||
data := gjson.GetBytes(resp, "data")
|
||||
if !data.Exists() {
|
||||
return nil, fmt.Errorf("查询手机在网时长失败, %s", string(resp))
|
||||
}
|
||||
return []byte(data.Raw), nil
|
||||
}
|
||||
|
||||
// 手机二次卡
|
||||
func (a *ApiRequestService) ProcessG19BJ02Request(params []byte) ([]byte, error) {
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
startDate := gjson.GetBytes(params, "startDate")
|
||||
if !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G19BJ02, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"phone": a.westDexService.Encrypt(mobile.String()),
|
||||
"startDate": startDate.String(),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G19BJ02", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 获取 code 字段
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
if !codeResult.Exists() || (codeResult.String() != "1025" && codeResult.String() != "1026") {
|
||||
return nil, fmt.Errorf("手机二次卡失败, %s", string(resp))
|
||||
}
|
||||
data := gjson.GetBytes(resp, "data")
|
||||
if !data.Exists() {
|
||||
return nil, fmt.Errorf("手机二次卡失败, %s", string(resp))
|
||||
}
|
||||
return []byte(data.Raw), nil
|
||||
}
|
||||
|
||||
// 银行卡四要素
|
||||
func (a *ApiRequestService) ProcessG20GZ01Request(params []byte) ([]byte, error) {
|
||||
name := gjson.GetBytes(params, "name")
|
||||
idCard := gjson.GetBytes(params, "id_card")
|
||||
mobile := gjson.GetBytes(params, "mobile")
|
||||
bankCard := gjson.GetBytes(params, "bank_card")
|
||||
|
||||
if !mobile.Exists() {
|
||||
return nil, errors.New("api请求, G20GZ01, 获取相关参数失败")
|
||||
}
|
||||
|
||||
request := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"name": a.westDexService.Encrypt(name.String()),
|
||||
"idcard": a.westDexService.Encrypt(idCard.String()),
|
||||
"acc_no": a.westDexService.Encrypt(bankCard.String()),
|
||||
"mobile": a.westDexService.Encrypt(mobile.String()),
|
||||
},
|
||||
}
|
||||
resp, callApiErr := a.westDexService.CallAPI("G20GZ01", request)
|
||||
if callApiErr != nil {
|
||||
return nil, callApiErr
|
||||
}
|
||||
// 获取 code 字段
|
||||
codeResult := gjson.GetBytes(resp, "code")
|
||||
if !codeResult.Exists() || codeResult.String() != "10000" {
|
||||
return nil, fmt.Errorf("银行卡四要素失败, %s", string(resp))
|
||||
}
|
||||
data := gjson.GetBytes(resp, "data")
|
||||
if !data.Exists() {
|
||||
return nil, fmt.Errorf("银行卡四要素失败, %s", string(resp))
|
||||
}
|
||||
// 解析 data.Raw 字符串为接口类型
|
||||
var parsedData interface{}
|
||||
err := json.Unmarshal([]byte(data.String()), &parsedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 data 失败: %v", err)
|
||||
}
|
||||
|
||||
// 将解析后的数据重新编码为 []byte
|
||||
resultBytes, err := json.Marshal(parsedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("重新编码 data 失败: %v", err)
|
||||
}
|
||||
|
||||
return resultBytes, nil
|
||||
}
|
||||
168
app/user/cmd/api/internal/service/applepayService.go
Normal file
168
app/user/cmd/api/internal/service/applepayService.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
59
app/user/cmd/api/internal/service/asynqService.go
Normal file
59
app/user/cmd/api/internal/service/asynqService.go
Normal file
@@ -0,0 +1,59 @@
|
||||
// asynq_service.go
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
"tydata-server/app/user/cmd/api/internal/types"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
189
app/user/cmd/api/internal/service/verificationService.go
Normal file
189
app/user/cmd/api/internal/service/verificationService.go
Normal file
@@ -0,0 +1,189 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/tidwall/gjson"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
"tydata-server/pkg/lzkit/crypto"
|
||||
)
|
||||
|
||||
type VerificationService struct {
|
||||
c config.Config
|
||||
westDexService *WestDexService
|
||||
}
|
||||
|
||||
func NewVerificationService(c config.Config, westDexService *WestDexService) *VerificationService {
|
||||
return &VerificationService{
|
||||
c: c,
|
||||
westDexService: westDexService,
|
||||
}
|
||||
}
|
||||
|
||||
// 二要素
|
||||
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) ThreeFactorVerification(request ThreeFactorVerificationRequest) (*VerificationResult, error) {
|
||||
westName, err := crypto.WestDexEncrypt(request.Name, r.c.WestConfig.Key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
westIDCard, err := crypto.WestDexEncrypt(request.IDCard, r.c.WestConfig.Key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
westPhone, err := crypto.WestDexEncrypt(request.Mobile, r.c.WestConfig.Key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
threeElementsReq := map[string]interface{}{
|
||||
"data": map[string]interface{}{
|
||||
"name": westName,
|
||||
"idNo": westIDCard,
|
||||
"phone": westPhone,
|
||||
},
|
||||
}
|
||||
resp, err := r.westDexService.CallAPI("G15BJ02", threeElementsReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dataResult := gjson.GetBytes(resp, "data.code")
|
||||
if !dataResult.Exists() {
|
||||
return nil, fmt.Errorf("code 字段不存在")
|
||||
}
|
||||
code := dataResult.Int()
|
||||
switch code {
|
||||
case 1000:
|
||||
case 1002:
|
||||
return &VerificationResult{
|
||||
Passed: false,
|
||||
Err: &ValidationError{Message: "姓名、证件号、手机号信息不一致"},
|
||||
}, nil
|
||||
case 1003:
|
||||
return &VerificationResult{
|
||||
Passed: false,
|
||||
Err: &ValidationError{Message: "姓名、证件号、手机号信息不一致"},
|
||||
}, nil
|
||||
case 1004:
|
||||
return &VerificationResult{
|
||||
Passed: false,
|
||||
Err: &ValidationError{Message: "姓名不正确"},
|
||||
}, nil
|
||||
case 1005:
|
||||
return &VerificationResult{
|
||||
Passed: false,
|
||||
Err: &ValidationError{Message: "证件号码不正确"},
|
||||
}, nil
|
||||
default:
|
||||
dataResultMsg := gjson.GetBytes(resp, "data.msg")
|
||||
if !dataResultMsg.Exists() {
|
||||
return nil, fmt.Errorf("msg字段不存在")
|
||||
}
|
||||
return nil, fmt.Errorf("三要素核验错误状态响应: %s", dataResultMsg.String())
|
||||
}
|
||||
|
||||
return &VerificationResult{Passed: true, Err: nil}, nil
|
||||
}
|
||||
247
app/user/cmd/api/internal/service/wechatpayService.go
Normal file
247
app/user/cmd/api/internal/service/wechatpayService.go
Normal file
@@ -0,0 +1,247 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
"tydata-server/pkg/lzkit/lzUtils"
|
||||
)
|
||||
|
||||
const (
|
||||
TradeStateSuccess = "SUCCESS" // 支付成功
|
||||
TradeStateRefund = "REFUND" // 转入退款
|
||||
TradeStateNotPay = "NOTPAY" // 未支付
|
||||
TradeStateClosed = "CLOSED" // 已关闭
|
||||
TradeStateRevoked = "REVOKED" // 已撤销(付款码支付)
|
||||
TradeStateUserPaying = "USERPAYING" // 用户支付中(付款码支付)
|
||||
TradeStatePayError = "PAYERROR" // 支付失败(其他原因,如银行返回失败)
|
||||
)
|
||||
|
||||
type WechatPayService struct {
|
||||
config config.WxpayConfig
|
||||
wechatClient *core.Client
|
||||
notifyHandler *notify.Handler
|
||||
}
|
||||
|
||||
// NewWechatPayService 初始化微信支付服务
|
||||
func NewWechatPayService(c config.Config) *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)) // 记录错误并停止程序
|
||||
}
|
||||
return &WechatPayService{
|
||||
config: c.Wxpay,
|
||||
wechatClient: client,
|
||||
notifyHandler: notifyHandler,
|
||||
}
|
||||
}
|
||||
|
||||
// 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.AppID),
|
||||
Mchid: core.String(w.config.MchID),
|
||||
Description: core.String(description),
|
||||
OutTradeNo: core.String(outTradeNo),
|
||||
NotifyUrl: core.String(w.config.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) (string, error) {
|
||||
totalAmount := lzUtils.ToWechatAmount(amount)
|
||||
|
||||
// 构建支付请求参数
|
||||
payRequest := jsapi.PrepayRequest{
|
||||
Appid: core.String(w.config.AppID),
|
||||
Mchid: core.String(w.config.MchID),
|
||||
Description: core.String(description),
|
||||
OutTradeNo: core.String(outTradeNo),
|
||||
NotifyUrl: core.String(w.config.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.PrepayId, nil
|
||||
}
|
||||
|
||||
// CreateWechatOrder 创建微信支付订单(集成 APP、H5、小程序)
|
||||
func (w *WechatPayService) CreateWechatOrder(ctx context.Context, amount float64, description string, outTradeNo string) (string, error) {
|
||||
// 根据 ctx 中的 platform 判断平台
|
||||
platform := ctx.Value("platform").(string)
|
||||
|
||||
var prepayId string
|
||||
var err error
|
||||
|
||||
switch platform {
|
||||
case "mp-weixin":
|
||||
// 如果是小程序平台,调用小程序支付订单创建
|
||||
prepayId, err = w.CreateWechatMiniProgramOrder(ctx, amount, description, outTradeNo, "asdasd")
|
||||
case "app":
|
||||
// 如果是 APP 平台,调用 APP 支付订单创建
|
||||
prepayId, err = w.CreateWechatAppOrder(ctx, amount, description, outTradeNo)
|
||||
default:
|
||||
return "", fmt.Errorf("不支持的支付平台: %s", platform)
|
||||
}
|
||||
|
||||
// 如果创建支付订单失败,返回错误
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("支付订单创建失败: %v", err)
|
||||
}
|
||||
|
||||
// 返回预支付ID
|
||||
return prepayId, 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.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.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
|
||||
}
|
||||
199
app/user/cmd/api/internal/service/westdexService.go
Normal file
199
app/user/cmd/api/internal/service/westdexService.go
Normal file
@@ -0,0 +1,199 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/pkg/errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
"tydata-server/pkg/lzkit/crypto"
|
||||
)
|
||||
|
||||
type WestResp struct {
|
||||
Message string `json:"message"`
|
||||
Code string `json:"code"`
|
||||
Data string `json:"data"`
|
||||
ID string `json:"id"`
|
||||
ErrorCode *int `json:"error_code"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
type G05HZ01WestResp struct {
|
||||
Message string `json:"message"`
|
||||
Code string `json:"code"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
ID string `json:"id"`
|
||||
ErrorCode *int `json:"error_code"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
type WestDexService struct {
|
||||
config config.WestConfig
|
||||
}
|
||||
|
||||
// NewWestDexService 是一个构造函数,用于初始化 WestDexService
|
||||
func NewWestDexService(c config.Config) *WestDexService {
|
||||
return &WestDexService{
|
||||
config: c.WestConfig,
|
||||
}
|
||||
}
|
||||
|
||||
// CallAPI 调用西部数据的 API
|
||||
func (w *WestDexService) CallAPI(code string, reqData map[string]interface{}) (resp []byte, err error) {
|
||||
// 生成当前的13位时间戳
|
||||
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
|
||||
|
||||
// 构造请求URL
|
||||
reqUrl := fmt.Sprintf("%s/%s/%s?timestamp=%s", w.config.Url, w.config.SecretId, code, timestamp)
|
||||
|
||||
jsonData, marshalErr := json.Marshal(reqData)
|
||||
if marshalErr != nil {
|
||||
return nil, marshalErr
|
||||
}
|
||||
|
||||
// 创建HTTP POST请求
|
||||
req, newRequestErr := http.NewRequest("POST", reqUrl, bytes.NewBuffer(jsonData))
|
||||
if newRequestErr != nil {
|
||||
return nil, newRequestErr
|
||||
}
|
||||
|
||||
// 设置请求头
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// 发送请求
|
||||
client := &http.Client{}
|
||||
httpResp, clientDoErr := client.Do(req)
|
||||
if clientDoErr != nil {
|
||||
return nil, clientDoErr
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
closeErr := Body.Close()
|
||||
if closeErr != nil {
|
||||
|
||||
}
|
||||
}(httpResp.Body)
|
||||
|
||||
// 检查请求是否成功
|
||||
if httpResp.StatusCode == 200 {
|
||||
// 读取响应体
|
||||
bodyBytes, ReadErr := io.ReadAll(httpResp.Body)
|
||||
if ReadErr != nil {
|
||||
return nil, ReadErr
|
||||
}
|
||||
|
||||
// 手动调用 json.Unmarshal 触发自定义的 UnmarshalJSON 方法
|
||||
var westDexResp WestResp
|
||||
UnmarshalErr := json.Unmarshal(bodyBytes, &westDexResp)
|
||||
if UnmarshalErr != nil {
|
||||
return nil, UnmarshalErr
|
||||
}
|
||||
if westDexResp.Code != "00000" {
|
||||
if westDexResp.Data == "" {
|
||||
return nil, errors.New(westDexResp.Message)
|
||||
}
|
||||
decryptedData, DecryptErr := crypto.WestDexDecrypt(westDexResp.Data, w.config.Key)
|
||||
if DecryptErr != nil {
|
||||
return nil, DecryptErr
|
||||
}
|
||||
return decryptedData, errors.New(westDexResp.Message)
|
||||
log.Println(string(decryptedData))
|
||||
}
|
||||
if westDexResp.Data == "" {
|
||||
return nil, errors.New(westDexResp.Message)
|
||||
}
|
||||
// 解密响应数据
|
||||
decryptedData, DecryptErr := crypto.WestDexDecrypt(westDexResp.Data, w.config.Key)
|
||||
if DecryptErr != nil {
|
||||
return nil, DecryptErr
|
||||
}
|
||||
// 输出解密后的数据
|
||||
log.Println(string(decryptedData))
|
||||
|
||||
return decryptedData, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("西部请求失败Code: %d", httpResp.StatusCode)
|
||||
}
|
||||
|
||||
// CallAPI 调用西部数据的 API
|
||||
func (w *WestDexService) G05HZ01CallAPI(code string, reqData map[string]interface{}) (resp []byte, err error) {
|
||||
// 生成当前的13位时间戳
|
||||
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
|
||||
|
||||
// 构造请求URL
|
||||
reqUrl := fmt.Sprintf("%s/%s/%s?timestamp=%s", w.config.Url, w.config.SecretSecondId, code, timestamp)
|
||||
|
||||
jsonData, marshalErr := json.Marshal(reqData)
|
||||
if marshalErr != nil {
|
||||
return nil, marshalErr
|
||||
}
|
||||
|
||||
// 创建HTTP POST请求
|
||||
req, newRequestErr := http.NewRequest("POST", reqUrl, bytes.NewBuffer(jsonData))
|
||||
if newRequestErr != nil {
|
||||
return nil, newRequestErr
|
||||
}
|
||||
|
||||
// 设置请求头
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// 发送请求
|
||||
client := &http.Client{}
|
||||
httpResp, clientDoErr := client.Do(req)
|
||||
if clientDoErr != nil {
|
||||
return nil, clientDoErr
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
closeErr := Body.Close()
|
||||
if closeErr != nil {
|
||||
|
||||
}
|
||||
}(httpResp.Body)
|
||||
|
||||
// 检查请求是否成功
|
||||
if httpResp.StatusCode == 200 {
|
||||
// 读取响应体
|
||||
bodyBytes, ReadErr := io.ReadAll(httpResp.Body)
|
||||
if ReadErr != nil {
|
||||
return nil, ReadErr
|
||||
}
|
||||
|
||||
// 手动调用 json.Unmarshal 触发自定义的 UnmarshalJSON 方法
|
||||
var westDexResp G05HZ01WestResp
|
||||
UnmarshalErr := json.Unmarshal(bodyBytes, &westDexResp)
|
||||
if UnmarshalErr != nil {
|
||||
return nil, UnmarshalErr
|
||||
}
|
||||
if westDexResp.Code != "0000" {
|
||||
if westDexResp.Data == nil {
|
||||
return nil, errors.New(westDexResp.Message)
|
||||
} else {
|
||||
return westDexResp.Data, errors.New(string(westDexResp.Data))
|
||||
}
|
||||
}
|
||||
if westDexResp.Data == nil {
|
||||
return nil, errors.New(westDexResp.Message)
|
||||
}
|
||||
return westDexResp.Data, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("西部请求失败Code: %d", httpResp.StatusCode)
|
||||
}
|
||||
|
||||
func (w *WestDexService) Encrypt(data string) string {
|
||||
encryptedValue, err := crypto.WestDexEncrypt(data, w.config.Key)
|
||||
if err != nil {
|
||||
panic("WestDexEncrypt error: " + err.Error())
|
||||
}
|
||||
return encryptedValue
|
||||
}
|
||||
|
||||
// GetDateRange 返回今天到明天的日期范围,格式为 "yyyyMMdd-yyyyMMdd"
|
||||
func (w *WestDexService) GetDateRange() string {
|
||||
today := time.Now().Format("20060102") // 获取今天的日期
|
||||
tomorrow := time.Now().Add(24 * time.Hour).Format("20060102") // 获取明天的日期
|
||||
return fmt.Sprintf("%s-%s", today, tomorrow) // 拼接日期范围并返回
|
||||
}
|
||||
186
app/user/cmd/api/internal/service/yushanService.go
Normal file
186
app/user/cmd/api/internal/service/yushanService.go
Normal file
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/tidwall/gjson"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"tydata-server/app/user/cmd/api/internal/config"
|
||||
)
|
||||
|
||||
type YushanService struct {
|
||||
config config.YushanConfig
|
||||
}
|
||||
|
||||
func NewYushanService(c config.Config) *YushanService {
|
||||
return &YushanService{
|
||||
config: c.YushanConfig,
|
||||
}
|
||||
}
|
||||
|
||||
func (y *YushanService) request(prodID string, params map[string]interface{}) ([]byte, error) {
|
||||
// 获取当前时间戳
|
||||
unixMilliseconds := time.Now().UnixNano() / int64(time.Millisecond)
|
||||
|
||||
// 生成请求序列号
|
||||
requestSN, _ := y.GenerateRandomString()
|
||||
|
||||
// 构建请求数据
|
||||
reqData := map[string]interface{}{
|
||||
"prod_id": prodID,
|
||||
"req_time": unixMilliseconds,
|
||||
"request_sn": requestSN,
|
||||
"req_data": params,
|
||||
}
|
||||
|
||||
// 将请求数据转换为 JSON 字节数组
|
||||
messageBytes, err := json.Marshal(reqData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 获取 API 密钥
|
||||
key, err := hex.DecodeString(y.config.ApiKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 使用 AES CBC 加密请求数据
|
||||
cipherText := y.AES_CBC_Encrypt(messageBytes, key)
|
||||
|
||||
// 将加密后的数据编码为 Base64 字符串
|
||||
content := base64.StdEncoding.EncodeToString(cipherText)
|
||||
|
||||
// 发起 HTTP 请求
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("POST", y.config.Url, strings.NewReader(content))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("ACCT_ID", y.config.AcctID)
|
||||
|
||||
// 执行请求
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// 读取响应体
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var respData []byte
|
||||
|
||||
if IsJSON(string(body)) {
|
||||
respData = body
|
||||
} else {
|
||||
sDec, err := base64.StdEncoding.DecodeString(string(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
respData = y.AES_CBC_Decrypt(sDec, key)
|
||||
}
|
||||
retCode := gjson.GetBytes(respData, "retcode").String()
|
||||
|
||||
if retCode == "100000" {
|
||||
// retcode 为 100000,表示查询为空
|
||||
return nil, fmt.Errorf("羽山请求查空: %s", string(respData))
|
||||
} else if retCode == "000000" {
|
||||
// retcode 为 000000,表示有数据,返回 retdata
|
||||
retData := gjson.GetBytes(respData, "retdata")
|
||||
if !retData.Exists() {
|
||||
return nil, fmt.Errorf("羽山请求retdata为空: %s", string(respData))
|
||||
}
|
||||
return []byte(retData.Raw), nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("羽山请求未知的状态码: %s", string(respData))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 判断字符串是否为 JSON 格式
|
||||
func IsJSON(s string) bool {
|
||||
var js interface{}
|
||||
return json.Unmarshal([]byte(s), &js) == nil
|
||||
}
|
||||
|
||||
// GenerateRandomString 生成一个32位的随机字符串订单号
|
||||
func (y *YushanService) GenerateRandomString() (string, error) {
|
||||
// 创建一个16字节的数组
|
||||
bytes := make([]byte, 16)
|
||||
// 读取随机字节到数组中
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 将字节数组编码为16进制字符串
|
||||
return hex.EncodeToString(bytes), nil
|
||||
}
|
||||
|
||||
// AEC加密(CBC模式)
|
||||
func (y *YushanService) AES_CBC_Encrypt(plainText []byte, key []byte) []byte {
|
||||
//指定加密算法,返回一个AES算法的Block接口对象
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
//进行填充
|
||||
plainText = Padding(plainText, block.BlockSize())
|
||||
//指定初始向量vi,长度和block的块尺寸一致
|
||||
iv := []byte("0000000000000000")
|
||||
//指定分组模式,返回一个BlockMode接口对象
|
||||
blockMode := cipher.NewCBCEncrypter(block, iv)
|
||||
//加密连续数据库
|
||||
cipherText := make([]byte, len(plainText))
|
||||
blockMode.CryptBlocks(cipherText, plainText)
|
||||
//返回base64密文
|
||||
return cipherText
|
||||
}
|
||||
|
||||
// AEC解密(CBC模式)
|
||||
func (y *YushanService) AES_CBC_Decrypt(cipherText []byte, key []byte) []byte {
|
||||
//指定解密算法,返回一个AES算法的Block接口对象
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
//指定初始化向量IV,和加密的一致
|
||||
iv := []byte("0000000000000000")
|
||||
//指定分组模式,返回一个BlockMode接口对象
|
||||
blockMode := cipher.NewCBCDecrypter(block, iv)
|
||||
//解密
|
||||
plainText := make([]byte, len(cipherText))
|
||||
blockMode.CryptBlocks(plainText, cipherText)
|
||||
//删除填充
|
||||
plainText = UnPadding(plainText)
|
||||
return plainText
|
||||
} // 对明文进行填充
|
||||
func Padding(plainText []byte, blockSize int) []byte {
|
||||
//计算要填充的长度
|
||||
n := blockSize - len(plainText)%blockSize
|
||||
//对原来的明文填充n个n
|
||||
temp := bytes.Repeat([]byte{byte(n)}, n)
|
||||
plainText = append(plainText, temp...)
|
||||
return plainText
|
||||
}
|
||||
|
||||
// 对密文删除填充
|
||||
func UnPadding(cipherText []byte) []byte {
|
||||
//取出密文最后一个字节end
|
||||
end := cipherText[len(cipherText)-1]
|
||||
//删除填充
|
||||
cipherText = cipherText[:len(cipherText)-int(end)]
|
||||
return cipherText
|
||||
}
|
||||
Reference in New Issue
Block a user