自己花了点时间把微信支付接口用golang封装了一下,以便以后需要接微信支付的时候可以直接拿来用。之前在网上看了很多写得NB微信SDK,自己也想尝试一下,于是做了api的简单封装。
TODO: 公众号开发api
地址: Github
package main
import (
"fmt"
dev "github.com/hong008/wechat-sdk"
)
func main() {
var appId, mchId, apiKey, apiSecret string
client := dev.NewPayer(dev.WithAppId(appId), dev.WithMchId(mchId), dev.WithApiKey(apiKey), dev.WithSecret(apiSecret))
//unified order
param := dev.NewParam()
param.Add("nonce_str", "yourNonceStr")
param.Add("body", "yourBody")
param.Add("out_trade_no", "yourOutTradeNo")
param.Add("total_fee", 1)
param.Add("spbill_create_ip", "yourIp")
param.Add("notify_url", "yourUrl")
param.Add("trade_type", "JSAPI")
result, err := client.UnifiedOrder(param)
if err != nil {
handleErr(err)
}
appId, _ := result.GetString("apppid")
prepayId, _ := result.GetString("prepay_id")
param = dev.NewParam()
param.Add("appId", appId)
param.Add("timeStamp", time.Now().Unix())
param.Add("nonceStr", "nonceStr")
param.Add("package", "prepay_id="+prepayId)
param.Add("signType", "MD5")
//use to evoke wechat pay
sign := param.Sign("MD5")
//download bill
param = dev.NewParam()
param.Add("nonce_str", "yourNonceStr")
param.Add("bill_date", "yourDate")
param.Add("bill_type", "ALL")
param.Add("tar_type", "GZIP")
err := client.DownloadBill(param, "./bill")
if err != nil {
handleErr(err)
}
//get phone for mini program user
result, err := client.GetUserPhoneForMini("code", "encryptedData", "iv")
if err != nil {
handleErr(err)
}
var phone string
if countryCode := result.Get("countryCode"); countryCode != nil && countryCode.(string) == "86" {
purePhone := result.Get("purePhoneNumber")
phone = purePhone.(string)
} else {
phoneNumber := result.Get("phoneNumber")
phone = phoneNumber.(string)
}
fmt.Printf("user phone is %s\n", phone)
}
package main
import (
"fmt"
"net/http"
dev "github.com/hong008/wechat-sdk"
)
func main() {
var appId, mchId, apiKey, apiSecret string
client := dev.NewPayer(dev.WithAppId(appId), dev.WithMchId(mchId), dev.WithApiKey(apiKey), dev.WithSecret(apiSecret))
//handle refund notify
http.HandleFunc("/refund_notify", func(writer http.ResponseWriter, request *http.Request) {
defer request.Body.Close()
result, err := client.RefundNotify(request.Body)
if err != nil {
handleErr(err)
}
fmt.Printf("RefundNotify Result = %v\n", result.Data())
})
http.ListenAndServe(":8810", nil)
}
有疑问加站长微信联系(非本文作者)