接收到未知的响应主体

huangapple go评论88阅读模式
英文:

Receiving unknown response body

问题

我正在实现Authorize.net信用卡API。无论交易成功与否,该API始终返回200响应代码。但是,对于成功的交易,它会返回一个响应体,而对于拒绝的交易,它会返回另一个响应体。

以下是我遇到的问题,我应该使用哪个结构体?我考虑尝试使用interface{},然后尝试将其转换为结构体。

err := json.Unmarshal(b, &whichStructToUse)
	if err != nil {
		panic(err.Error())
	}

在我不知道要使用哪个结构体的情况下,如何解析响应?

英文:

I am implementing the Authorize.net credit card API. The API always gives me a 200 response code regardless if the transaction is successful or it is declined. But it gives the one response body for successful transaction and a different one for declined transaction.

type AuthorizeApprovedResponse struct {
	TransactionResponse struct {
		ResponseCode   string `json:"responseCode"`
		AuthCode       string `json:"authCode"`
		AvsResultCode  string `json:"avsResultCode"`
		CvvResultCode  string `json:"cvvResultCode"`
		CavvResultCode string `json:"cavvResultCode"`
		TransID        string `json:"transId"`
		RefTransID     string `json:"refTransID"`
		TransHash      string `json:"transHash"`
		TestRequest    string `json:"testRequest"`
		AccountNumber  string `json:"accountNumber"`
		AccountType    string `json:"accountType"`
		Messages       []struct {
			Code        string `json:"code"`
			Description string `json:"description"`
		} `json:"messages"`
		UserFields []struct {
			Name  string `json:"name"`
			Value string `json:"value"`
		} `json:"userFields"`
		TransHashSha2                          string `json:"transHashSha2"`
		SupplementalDataQualificationIndicator int    `json:"SupplementalDataQualificationIndicator"`
		NetworkTransID                         string `json:"networkTransId"`
	} `json:"transactionResponse"`
	RefID    string `json:"refId"`
	Messages struct {
		ResultCode string `json:"resultCode"`
		Message    []struct {
			Code string `json:"code"`
			Text string `json:"text"`
		} `json:"message"`
	} `json:"messages"`
}

type AuthorizeDeclinedResponse struct {
	TransactionResponse struct {
		ResponseCode   string `json:"responseCode"`
		AuthCode       string `json:"authCode"`
		AvsResultCode  string `json:"avsResultCode"`
		CvvResultCode  string `json:"cvvResultCode"`
		CavvResultCode string `json:"cavvResultCode"`
		TransID        string `json:"transId"`
		RefTransID     string `json:"refTransID"`
		TransHash      string `json:"transHash"`
		TestRequest    string `json:"testRequest"`
		AccountNumber  string `json:"accountNumber"`
		AccountType    string `json:"accountType"`
		Errors         []struct {
			ErrorCode string `json:"errorCode"`
			ErrorText string `json:"errorText"`
		} `json:"errors"`
		UserFields []struct {
			Name  string `json:"name"`
			Value string `json:"value"`
		} `json:"userFields"`
		TransHashSha2                          string `json:"transHashSha2"`
		SupplementalDataQualificationIndicator int    `json:"SupplementalDataQualificationIndicator"`
		NetworkTransID                         string `json:"networkTransId"`
	} `json:"transactionResponse"`
	RefID    string `json:"refId"`
	Messages struct {
		ResultCode string `json:"resultCode"`
		Message    []struct {
			Code string `json:"code"`
			Text string `json:"text"`
		} `json:"message"`
	} `json:"messages"`
}

Here is my problem, which struct to use. I was thinking of trying an interface{} and then try to cast it to a struct?

err := json.Unmarshal(b, &whichStructToUse)
	if err != nil {
		panic(err.Error())
	}

Any advice on how to Unmarshal the response when I don't know which struct to use?

答案1

得分: 2

API无论交易成功还是被拒绝,都会返回200响应代码。

我理解你的痛苦。

这两种响应之间只有一个区别,成功的响应中有Messages,失败的响应中有Errors。将它们合并起来。

type CommonResponse struct {
    TransactionResponse struct {
        ResponseCode   string `json:"responseCode"`
        AuthCode       string `json:"authCode"`
        AvsResultCode  string `json:"avsResultCode"`
        CvvResultCode  string `json:"cvvResultCode"`
        CavvResultCode string `json:"cavvResultCode"`
        TransID        string `json:"transId"`
        RefTransID     string `json:"refTransID"`
        TransHash      string `json:"transHash"`
        TestRequest    string `json:"testRequest"`
        AccountNumber  string `json:"accountNumber"`
        AccountType    string `json:"accountType"`
        Messages       []struct {
            Code        string `json:"code"`
            Description string `json:"description"`
        } `json:"messages"`
        Errors         []struct {
            ErrorCode string `json:"errorCode"`
            ErrorText string `json:"errorText"`
        } `json:"errors"`
        UserFields []struct {
            Name  string `json:"name"`
            Value string `json:"value"`
        } `json:"userFields"`
        TransHashSha2                          string `json:"transHashSha2"`
        SupplementalDataQualificationIndicator int    `json:"SupplementalDataQualificationIndicator"`
        NetworkTransID                         string `json:"networkTransId"`
    } `json:"transactionResponse"`
    RefID    string `json:"refId"`
    Messages struct {
        ResultCode string `json:"resultCode"`
        Message    []struct {
            Code string `json:"code"`
            Text string `json:"text"`
        } `json:"message"`
    } `json:"messages"`
}

然后使用该结构进行解组并检查是否存在错误。

var response CommonResponse
json.Unmarshal([]byte(jsonString), &response)
if len(response.Errors) == 0 {
    fmt.Println("成功!")
} else {
    fmt.Println("错误!")
}

对于更一般的情况,你可以解组到一个map[string]interface{}中。

var result map[string]interface{}
json.Unmarshal([]byte(jsonString), &result)

演示

英文:

> The API always gives me a 200 response code regardless if the transaction is successful or it is declined.

I feel your pain.

There's only one difference between the two responses, success has Messages and failure has Errors. Combine them.

type CommonResponse struct {
    TransactionResponse struct {
        ResponseCode   string `json:"responseCode"`
        AuthCode       string `json:"authCode"`
        AvsResultCode  string `json:"avsResultCode"`
        CvvResultCode  string `json:"cvvResultCode"`
        CavvResultCode string `json:"cavvResultCode"`
        TransID        string `json:"transId"`
        RefTransID     string `json:"refTransID"`
        TransHash      string `json:"transHash"`
        TestRequest    string `json:"testRequest"`
        AccountNumber  string `json:"accountNumber"`
        AccountType    string `json:"accountType"`
        Messages       []struct {
            Code        string `json:"code"`
            Description string `json:"description"`
        } `json:"messages"`
        Errors         []struct {
            ErrorCode string `json:"errorCode"`
            ErrorText string `json:"errorText"`
        } `json:"errors"`
        UserFields []struct {
            Name  string `json:"name"`
            Value string `json:"value"`
        } `json:"userFields"`
        TransHashSha2                          string `json:"transHashSha2"`
        SupplementalDataQualificationIndicator int    `json:"SupplementalDataQualificationIndicator"`
        NetworkTransID                         string `json:"networkTransId"`
    } `json:"transactionResponse"`
    RefID    string `json:"refId"`
    Messages struct {
        ResultCode string `json:"resultCode"`
        Message    []struct {
            Code string `json:"code"`
            Text string `json:"text"`
        } `json:"message"`
    } `json:"messages"`
}

Then use that to unmarshall and check for Errors.

	var response CommonResponse;
    json.Unmarshal([]byte(jsonString), &response)
	if len(response.Error) == 0 {
		fmt.Println("Success!")
	} else {
		fmt.Println("Error!")
	}

For the more general case, you can unmarshall to a map[string]interface{}.

var result map[string]interface{}
json.Unmarshal([]byte(jsonString), &result)

Demonstration.

huangapple
  • 本文由 发表于 2022年10月27日 05:18:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/74214338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定