Golang如何从支付响应中获取授权ID?

Golang如何从支付响应中获取授权ID? 如何从这种类型的响应中获取授权ID

{
           "intent": "authorize",
           "payer": {
               "payment_method": "credit_card",
               "funding_instruments": [
                   {
                       "credit_card": {
                           "payer_id": "3888888888888888888",
                           "number": "xxxxxxxxxxxx8888",
                           "type": "DISCOVER",
                           "expire_month": "10",
                           "expire_year": "2028",
                           "first_name": "ABC"
                       }
                   }
               ]
           },
           "transactions": [
               {
                   "amount": {
                       "currency": "USD",
                       "total": "4.00",
                       "details": {}
                   },
                   "description": "This is the authorize payment transaction description.",
                   "related_resources": [
                       {
                           "authorization": {
                               "amount": {
                                   "currency": "USD",
                                   "total": "4.00",
                                   "details": {}
                               },
                               "create_time": "2018-10-12T11:23:51Z",
                               "update_time": "2018-10-12T11:23:53Z",
                               "state": "authorized",
                               "parent_payment": "PAY-37J37J37J37J37J37J37J37J",
                               "id": "4FR34FR34FR34FR3A",
                               "valid_until": "2018-11-10T11:23:51Z",
                               "links": [
                                   {
                                       "href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A",
                                       "rel": "self",
                                       "method": "GET"
                                   },
                                   {
                                       "href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/capture",
                                       "rel": "capture",
                                       "method": "POST"
                                   },
                                   {
                                       "href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/void",
                                       "rel": "void",
                                       "method": "POST"
                                   },
                                   {
                                       "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-37J37J37J37J37J37J37J37J",
                                       "rel": "parent_payment",
                                       "method": "GET"
                                   }
                               ]
                           }
                       }
                   ]
               }
           ],
           "id": "PAY-37J37J37J37J37J37J37J37J",
           "create_time": "2018-10-12T11:23:51Z",
           "state": "approved",
           "update_time": "2018-10-12T11:23:53Z",
           "links": [
               {
                   "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-37J37J37J37J37J37J37J37J",
                   "rel": "self",
                   "method": "GET"
               }
           ]
       }
   }
}

我需要获取这个ID “4FR34FR34FR34FR3A” 来捕获付款,在Golang中如何从这个响应中获取这个ID?


更多关于Golang如何从支付响应中获取授权ID?的实战教程也可以访问 https://www.itying.com/category-94-b0.html

6 回复

非常有用。太棒了

更多关于Golang如何从支付响应中获取授权ID?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


您的响应是JSON格式。请使用Unmarshal进行解析。

使用 https://mholt.github.io/json-to-go/ 将您的JSON字符串转换为Go结构体

我认为这不是一个好主意,因为你的代码会变得难以维护。有些人需要费很大力气才能理解循环的作用,而不是直接查看组织良好的结构体。

我正在使用 REST API 处理解码后的 JSON 数据。我们可以不使用 Unmarshal,而是通过 range 循环来实现这个功能。

for i, transactionRes := range paymentResponse.Transactions {
    obj := transactionRes.RelatedResources[i]
    id := obj.Authorization.ID
    returnData["paypal_auth_id"] = id
}

在Golang中,您需要定义相应的结构体来解析这个JSON响应,然后访问授权ID字段。以下是完整的解决方案:

package main

import (
    "encoding/json"
    "fmt"
)

// 定义响应结构体
type PaymentResponse struct {
    Intent    string `json:"intent"`
    Payer     Payer  `json:"payer"`
    Transactions []Transaction `json:"transactions"`
    ID        string `json:"id"`
    CreateTime string `json:"create_time"`
    State     string `json:"state"`
    UpdateTime string `json:"update_time"`
    Links     []Link `json:"links"`
}

type Payer struct {
    PaymentMethod string `json:"payment_method"`
    FundingInstruments []FundingInstrument `json:"funding_instruments"`
}

type FundingInstrument struct {
    CreditCard CreditCard `json:"credit_card"`
}

type CreditCard struct {
    PayerID    string `json:"payer_id"`
    Number     string `json:"number"`
    Type       string `json:"type"`
    ExpireMonth string `json:"expire_month"`
    ExpireYear  string `json:"expire_year"`
    FirstName  string `json:"first_name"`
}

type Transaction struct {
    Amount        Amount `json:"amount"`
    Description   string `json:"description"`
    RelatedResources []RelatedResource `json:"related_resources"`
}

type Amount struct {
    Currency string `json:"currency"`
    Total    string `json:"total"`
    Details  map[string]interface{} `json:"details"`
}

type RelatedResource struct {
    Authorization Authorization `json:"authorization"`
}

type Authorization struct {
    Amount      Amount `json:"amount"`
    CreateTime  string `json:"create_time"`
    UpdateTime  string `json:"update_time"`
    State       string `json:"state"`
    ParentPayment string `json:"parent_payment"`
    ID          string `json:"id"`
    ValidUntil  string `json:"valid_until"`
    Links       []Link `json:"links"`
}

type Link struct {
    Href   string `json:"href"`
    Rel    string `json:"rel"`
    Method string `json:"method"`
}

func main() {
    // 假设这是您的JSON响应数据
    jsonData := `{
        "intent": "authorize",
        "payer": {
            "payment_method": "credit_card",
            "funding_instruments": [
                {
                    "credit_card": {
                        "payer_id": "3888888888888888888",
                        "number": "xxxxxxxxxxxx8888",
                        "type": "DISCOVER",
                        "expire_month": "10",
                        "expire_year": "2028",
                        "first_name": "ABC"
                    }
                }
            ]
        },
        "transactions": [
            {
                "amount": {
                    "currency": "USD",
                    "total": "4.00",
                    "details": {}
                },
                "description": "This is the authorize payment transaction description.",
                "related_resources": [
                    {
                        "authorization": {
                            "amount": {
                                "currency": "USD",
                                "total": "4.00",
                                "details": {}
                            },
                            "create_time": "2018-10-12T11:23:51Z",
                            "update_time": "2018-10-12T11:23:53Z",
                            "state": "authorized",
                            "parent_payment": "PAY-37J37J37J37J37J37J37J37J",
                            "id": "4FR34FR34FR34FR3A",
                            "valid_until": "2018-11-10T11:23:51Z",
                            "links": [
                                {
                                    "href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A",
                                    "rel": "self",
                                    "method": "GET"
                                },
                                {
                                    "href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/capture",
                                    "rel": "capture",
                                    "method": "POST"
                                },
                                {
                                    "href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/void",
                                    "rel": "void",
                                    "method": "POST"
                                },
                                {
                                    "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-37J37J37J37J37J37J37J37J",
                                    "rel": "parent_payment",
                                    "method": "GET"
                                }
                            ]
                        }
                    }
                ]
            }
        ],
        "id": "PAY-37J37J37J37J37J37J37J37J",
        "create_time": "2018-10-12T11:23:51Z",
        "state": "approved",
        "update_time": "2018-10-12T11:23:53Z",
        "links": [
            {
                "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-37J37J37J37J37J37J37J37J",
                "rel": "self",
                "method": "GET"
            }
        ]
    }`

    var paymentResp PaymentResponse
    err := json.Unmarshal([]byte(jsonData), &paymentResp)
    if err != nil {
        fmt.Printf("解析JSON失败: %v\n", err)
        return
    }

    // 获取授权ID
    if len(paymentResp.Transactions) > 0 && 
       len(paymentResp.Transactions[0].RelatedResources) > 0 {
        authorizationID := paymentResp.Transactions[0].RelatedResources[0].Authorization.ID
        fmt.Printf("授权ID: %s\n", authorizationID)
        
        // 使用授权ID进行捕获操作
        captureURL := fmt.Sprintf("https://api.sandbox.paypal.com/v1/payments/authorization/%s/capture", authorizationID)
        fmt.Printf("捕获URL: %s\n", captureURL)
    }
}

如果您想直接从HTTP响应中解析,可以这样处理:

func getAuthorizationIDFromResponse(respBody []byte) (string, error) {
    var paymentResp PaymentResponse
    err := json.Unmarshal(respBody, &paymentResp)
    if err != nil {
        return "", fmt.Errorf("解析响应失败: %v", err)
    }

    if len(paymentResp.Transactions) == 0 {
        return "", fmt.Errorf("没有找到交易记录")
    }

    if len(paymentResp.Transactions[0].RelatedResources) == 0 {
        return "", fmt.Errorf("没有找到相关资源")
    }

    authorizationID := paymentResp.Transactions[0].RelatedResources[0].Authorization.ID
    if authorizationID == "" {
        return "", fmt.Errorf("授权ID为空")
    }

    return authorizationID, nil
}

运行上述代码将输出:

授权ID: 4FR34FR34FR34FR3A
捕获URL: https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/capture
回到顶部