golang fiber中写一个微信支付函数库
时间: 2023-12-13 20:34:12 浏览: 150
golang整合微信支付
以下是一个使用Golang Fiber框架编写的微信支付函数库的示例代码:
```go
package wechatpay
import (
"bytes"
"crypto/tls"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"sort"
"strings"
"time"
)
type WechatPay struct {
AppID string // 微信公众号或开放平台APP的唯一标识
MchID string // 商户号
Key string // 商户支付密钥
NotifyURL string // 支付结果通知地址
}
type UnifiedOrderRequest struct {
XMLName xml.Name `xml:"xml"`
AppID string `xml:"appid"`
MchID string `xml:"mch_id"`
NonceStr string `xml:"nonce_str"`
Body string `xml:"body"`
OutTradeNo string `xml:"out_trade_no"`
TotalFee int `xml:"total_fee"`
SpbillCreateIP string `xml:"spbill_create_ip"`
NotifyURL string `xml:"notify_url"`
TradeType string `xml:"trade_type"`
OpenID string `xml:"openid"`
Sign string `xml:"sign"`
}
type UnifiedOrderResponse struct {
XMLName xml.Name `xml:"xml"`
ReturnCode string `xml:"return_code"`
ReturnMsg string `xml:"return_msg"`
AppID string `xml:"appid"`
MchID string `xml:"mch_id"`
NonceStr string `xml:"nonce_str"`
Sign string `xml:"sign"`
ResultCode string `xml:"result_code"`
PrepayID string `xml:"prepay_id"`
TradeType string `xml:"trade_type"`
}
func (wp *WechatPay) UnifiedOrder(body, outTradeNo, spbillCreateIP, tradeType, openID string, totalFee int) (*UnifiedOrderResponse, error) {
nonceStr := fmt.Sprintf("%d", time.Now().UnixNano())
req := &UnifiedOrderRequest{
AppID: wp.AppID,
MchID: wp.MchID,
NonceStr: nonceStr,
Body: body,
OutTradeNo: outTradeNo,
TotalFee: totalFee,
SpbillCreateIP: spbillCreateIP,
NotifyURL: wp.NotifyURL,
TradeType: tradeType,
OpenID: openID,
}
req.Sign = wp.sign(req)
buf := bytes.NewBuffer(nil)
xml.NewEncoder(buf).Encode(req)
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
resp, err := client.Post("https://api.mch.weixin.qq.com/pay/unifiedorder", "application/xml;charset=utf-8", buf)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var unifiedOrderResp UnifiedOrderResponse
err = xml.Unmarshal(respBody, &unifiedOrderResp)
if err != nil {
return nil, err
}
return &unifiedOrderResp, nil
}
func (wp *WechatPay) sign(req *UnifiedOrderRequest) string {
m := make(map[string]string)
m["appid"] = req.AppID
m["mch_id"] = req.MchID
m["nonce_str"] = req.NonceStr
m["body"] = req.Body
m["out_trade_no"] = req.OutTradeNo
m["total_fee"] = fmt.Sprintf("%d", req.TotalFee)
m["spbill_create_ip"] = req.SpbillCreateIP
m["notify_url"] = req.NotifyURL
m["trade_type"] = req.TradeType
m["openid"] = req.OpenID
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
for _, k := range keys {
v := m[k]
if v != "" {
buf.WriteString(k)
buf.WriteString("=")
buf.WriteString(v)
buf.WriteString("&")
}
}
buf.WriteString("key=")
buf.WriteString(wp.Key)
return strings.ToUpper(fmt.Sprintf("%x", md5.Sum(buf.Bytes())))
}
```
阅读全文