Home > Article > Backend Development > How to use Golang to implement the Alipay interface of a web application
With the popularization of mobile Internet, the popularity of online shopping and mobile payment, Alipay has become more and more an indispensable part of people's lives, and Alipay's interface has become one of the skills that developers must master. This article will introduce how to use Golang to implement the Alipay interface of web applications.
First, we need to register an account on Alipay's developer platform and create an application. When creating an application, you need to fill in the application name, application type, application callback address and other information, and generate the application ID and private key. This information will be used in subsequent interface calls.
Next, we need to use Golang to write code to call Alipay’s interface. First, we need to introduce the necessary packages:
import ( "bytes" "crypto" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "sort" "strings" "time" )
Next, we need to define some variables. Among them, the values of variables such as appId, privateKey, publicKey, gatewayUrl, charset, signType, and format need to be modified according to your application information.
const ( appId = "xxx" privateKey = `xxx` publicKey = `xxx` gatewayUrl = "https://openapi.alipay.com/gateway.do" charset = "utf-8" signType = "RSA2" format = "json" )
Among them, privateKey and publicKey need to be replaced with the application private key and Alipay public key obtained from the Alipay developer platform. For security reasons, they are stored in constants. In fact, they should be stored in file or database.
Next, we need to define some structures for parsing the JSON data returned by the Alipay interface:
type AlipayResponse struct { Code string `json:"code"` Msg string `json:"msg"` SubCode string `json:"sub_code"` SubMsg string `json:"sub_msg"` } type TradePrecreateResponse struct { AlipayResponse OutTradeNo string `json:"out_trade_no"` QrCode string `json:"qr_code"` }
Only one TradePrecreateResponse structure is defined here, which is used to parse Alipay to create reservations JSON data returned by a single interface.
Next, we need to define some functions. First, we need to define a function for generating signatures.
func generateSign(params url.Values) string { keys := make([]string, 0, len(params)) for key := range params { keys = append(keys, key) } sort.Strings(keys) var sortedParams bytes.Buffer for _, key := range keys { values := params[key] value := "" if len(values) > 0 { value = values[0] } sortedParams.WriteString(key) sortedParams.WriteString("=") sortedParams.WriteString(value) sortedParams.WriteString("&") } sortedParams.Truncate(sortedParams.Len() - 1) h := crypto.SHA256.New() h.Write(sortedParams.Bytes()) privateKeyByte := []byte(privateKey) block, _ := pem.Decode(privateKeyByte) privateKey, _ := x509.ParsePKCS8PrivateKey(block.Bytes) signature, err := rsa.SignPKCS1v15(nil, privateKey.(*rsa.PrivateKey), crypto.SHA256, h.Sum(nil)) if err != nil { panic(err) } return base64.StdEncoding.EncodeToString(signature) }
This function first sorts the parameters in lexicographic order, then uses the SHA256 algorithm to calculate the digest of the parameters, then uses the application private key to sign the digest, and finally base64 encodes the signature.
Next, we need to define a function to send a request to the Alipay interface:
func doRequest(apiName string, bizContent map[string]interface{}) (string, error) { var ( response *http.Response err error ) params := url.Values{} params.Set("app_id", appId) params.Set("method", apiName) params.Set("version", "1.0") params.Set("format", format) params.Set("charset", charset) params.Set("sign_type", signType) params.Set("timestamp", time.Now().Format("2006-01-02 15:04:05")) params.Set("biz_content", toJsonString(bizContent)) params.Set("sign", generateSign(params)) url := gatewayUrl + "?" + params.Encode() if response, err = http.Get(url); err != nil { return "", err } defer response.Body.Close() if body, err := ioutil.ReadAll(response.Body); err != nil { return "", err } else { return string(body), nil } }
This function first organizes the parameters into a URL string and uses the generateSign function to generate a signature. After that, send this URL string to Alipay's interface and wait for Alipay's return result. Finally, the returned result is converted to a string and returned.
At this point, we have completed the request for the Alipay interface. The next step is how to call this function to achieve the function of creating a pre-order interface. The following is an example function:
func tradePrecreate(subject, outTradeNo string, totalAmount float32) (*TradePrecreateResponse, error) { bizContent := make(map[string]interface{}) bizContent["out_trade_no"] = outTradeNo bizContent["total_amount"] = fmt.Sprintf("%.2f", totalAmount) bizContent["subject"] = subject bizContent["timeout_express"] = "30m" responseStr, err := doRequest("alipay.trade.precreate", bizContent) if err != nil { return nil, err } var response TradePrecreateResponse if err := json.Unmarshal([]byte(responseStr), &response); err != nil { return nil, err } if response.Code != "10000" { return nil, fmt.Errorf("%s (%s)", response.Msg, response.SubMsg) } return &response, nil }
This function first organizes some parameters, such as merchant order number, order amount, order title, etc., then calls the doRequest function to send the request, and parses the return result. If the code in the returned result is 10000, it means that the request was successful, otherwise it means that the request failed, and in this case, the error message needs to be returned.
Finally, we can use this function in the web application to implement the Alipay interface. For example, in the Go language web framework gin, you can call the above function like this:
func createOrder(c *gin.Context) { subject := "Test Order" outTradeNo := "12345" totalAmount := 1.00 response, err := tradePrecreate(subject, outTradeNo, totalAmount) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"qr_code": response.QrCode}) }
This function will generate a merchant order, then call the tradePrecreate function to generate a pre-order, and return a QR code with JSON response.
Finally, summarize the above steps: First, you need to register an account on the Alipay developer platform and create an application, and generate an application ID and private key; then, use Golang to write code to call Alipay's interface and define Some structures, functions and variables; ultimately, these functions are used in the web application to implement the Alipay interface.
The above are the steps and methods for using Golang to implement the Alipay interface of web applications. I hope it will be helpful to you.
The above is the detailed content of How to use Golang to implement the Alipay interface of a web application. For more information, please follow other related articles on the PHP Chinese website!