This issue recommends a Go language related collection payment library – support wechat, Alipay, PayPal, QQ payment.
一、install
go get -u github.com/go-pay/gopay
View the GoPay version
import (
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/pkg/xlog"
)
func main() {
xlog.Info("GoPay Version: ", gopay.Version)
}
pay by Alipay
1、Initialize the Alipay client and configure it
Please refer to the specific API usage introduction
gopay/alipay/client_test.go
import (
"github.com/go-pay/gopay/alipay"
"github.com/go-pay/gopay/pkg/xlog"
)
// Initialize the Alipay client
// appId:Application ID
// privateKey:Application private key. PKCS1 and PKCS8 are supported
// isProd:Formal environment or not
client, err := alipay.NewClient("2016091200494382", privateKey, false)
if err != nil {
xlog.Error(err)
return
}
// Enable the Debug function to output logs. The function is disabled by default
client.DebugSwitch = gopay.DebugOn
// Set the Alipay request public parameters
// Note: The specific parameters to be set vary according to different methods. All parameters are listed here
client.SetLocation(alipay.LocationShanghai). // Set the time zone. If the time zone is not set or an error occurs, the default server time is used
SetCharset(alipay.UTF8). // Set the character encoding, do not set the default utf-8
SetSignType(alipay.RSA2). // Set the signature type. Do not set the default RSA2
SetReturnUrl("https://www.fmm.ink"). //Set the return URL
SetNotifyUrl("https://www.fmm.ink"). // Set the URL of the asynchronous notification
SetAppAuthToken() // Set third-party application authorization
// Automatic synchronous verification (Certificate mode only)
// Pass in the alipayCertPublicKey_RSA2.crt content
client.AutoVerifySign([]byte("alipayCertPublicKey_RSA2 bytes"))
// In public key certificate mode, you can use either of the following methods to import a certificate
// certification path
err := client.SetCertSnByPath("appCertPublicKey.crt", "alipayRootCert.crt", "alipayCertPublicKey_RSA2.crt")
// Certificate content
err := client.SetCertSnByContent("appCertPublicKey bytes", "alipayRootCert bytes", "alipayCertPublicKey_RSA2 bytes")
2、API method call and input (Unified acquisition transaction payment interface example)
import (
"github.com/go-pay/gopay"
)
// initialize BodyMap
bm := make(gopay.BodyMap)
bm.Set("subject", "Barcode Pay").
Set("scene", "bar_code").
Set("auth_code", "286248566432274952").
Set("out_trade_no", "GZ201909081743431443").
Set("total_amount", "0.01").
Set("timeout_express", "2m")
aliRsp, err := client.TradePay(bm)
if err != nil {
xlog.Error("err:", err)
return
}
3、Synchronous return parameter check Sign, asynchronous notification parameter parsing, check Sign, and asynchronous notification return
Asynchronous notification request parameters need to be parsed first, and then the parsed structure or BodyMap is checked (it should be noted here that http.Request.Body can only be parsed once, if you need to debug before parsing, please handle the Body reuse problem).
- Synchronously return to check the visa and manually check the visa (if automatic check is enabled, manual check is not required)
import (
"github.com/go-pay/gopay/alipay"
)
aliRsp, err := client.TradePay(bm)
if err != nil {
xlog.Error("err:", err)
return
}
// Public key mode check
// Note: APP payment, mobile website payment, computer website payment does not support synchronous return check
// aliPayPublicKey:Alipay public key obtained by Alipay platform
// signData:Parameter to be checked,aliRsp.SignData
// sign:Visa to be examined sign,aliRsp.Sign
ok, err := alipay.VerifySyncSign(aliPayPublicKey, aliRsp.SignData, aliRsp.Sign)
// Public key certificate mode check
// aliPayPublicKeyCert:Path for storing Alipay public key certificate alipayCertPublicKey_RSA2.crt Or file content[]byte
// signData:Parameter to be checked,aliRsp.SignData
// sign:Visa to be examinedsign,aliRsp.Sign
ok, err := alipay.VerifySyncSignWithCert(aliPayPublicKeyCert, aliRsp.SignData, aliRsp.Sign)
- Asynchronous notification check
import (
"github.com/go-pay/gopay/alipay"
)
// Parse the parameters of the asynchronous notification
// req:*http.Request
notifyReq, err = alipay.ParseNotifyToBodyMap(c.Request) // c.Request It's gin framing
if err != nil {
xlog.Error(err)
return
}
or
// value:url.Values
notifyReq, err = alipay.ParseNotifyByURLValues()
if err != nil {
xlog.Error(err)
return
}
//Alipay Asynchronous Notification Check (Public key mode)
ok, err = alipay.VerifySign(aliPayPublicKey, notifyReq)
//Alipay Asynchronous Notification Check (Public Key Certificate mode)
ok, err = alipay.VerifySignWithCert("alipayCertPublicKey_RSA2.crt content", notifyReq)
// ====Asynchronous notification, return Alipay platform information====
// document:https://opendocs.alipay.com/open/203/105286
// The program must be printed out after execution“success”(Without quotes)。If the merchant feedback to Alipay character is not successThese 7 characters, Alipay server will continue to re-send the notification until more than 24 hours and 22 minutes. In general, 8 notifications are completed within 25 hours (the frequency between notifications is generally:4m,10m,10m,1h,2h,6h,15h)
// This is how the gin frame returns to Alipay
c.String(http.StatusOK, "%s", "success")
// This is the way the echo frame returns to Alipay
return c.String(http.StatusOK, "success")
WeChat Pay
1、Initialize the wechat v3 client and configure it
import (
"github.com/go-pay/gopay/pkg/xlog"
"github.com/go-pay/gopay/wechat/v3"
)
// NewClientV3 Example Initialize the wechat clientv3
// mchid:Merchant ID or service provider model sp_mchid
// serialNo:Certificate serial number of merchant certificate
// apiV3Key:apiV3Key,Merchant platform acquisition
// privateKey:private key apiclient_key.pem The content after reading
client, err = wechat.NewClientV3(MchId, SerialNo, APIv3Key, PrivateKey)
if err != nil {
xlog.Error(err)
return
}
// Enable automatic synchronization return check, and regularly update the wechat platform API certificate
err = client.AutoVerifySign()
if err != nil {
xlog.Error(err)
return
}
// Enable the Debug function to output logs. The function is disabled by default
client.DebugSwitch = gopay.DebugOn
2、API method call and entry (JSAPI order example)
import (
"github.com/go-pay/gopay"
)
expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
// initialize BodyMap
bm := make(gopay.BodyMap)
bm.Set("sp_appid", "sp_appid").
Set("sp_mchid", "sp_mchid").
Set("sub_mchid", "sub_mchid").
Set("description", "Test Jsapi payment items").
Set("out_trade_no", tradeNo).
Set("time_expire", expire).
Set("notify_url", "https://www.fmm.ink").
SetBodyMap("amount", func(bm gopay.BodyMap) {
bm.Set("total", 1).
Set("currency", "CNY")
}).
SetBodyMap("payer", func(bm gopay.BodyMap) {
bm.Set("sp_openid", "asdas")
})
wxRsp, err := client.V3TransactionJsapi(bm)
if err != nil {
xlog.Error(err)
return
}
3、After placing an order, get the pay sign required for wechat mini program payment, APP payment and JSAPI payment
// mini program
applet, err := client.PaySignOfApplet("appid", "prepayid")
// app
app, err := client.PaySignOfApp("appid", "prepayid")
// jsapi
jsapi, err := client.PaySignOfJSAPI("appid", "prepayid")
4、Synchronous return parameter check Sign, asynchronous notification parameter parsing, check Sign, and asynchronous notification return
Asynchronous notification request parameters need to be parsed first, and then the parsed structure or BodyMap is checked (it should be noted here that http.Request.Body can only be parsed once, if you need to debug before parsing, please handle the Body reuse problem).
- Synchronously return to check the visa and manually check the visa (if automatic check is enabled, manual check is not required)
import (
"github.com/go-pay/gopay/wechat/v3"
"github.com/go-pay/gopay/pkg/xlog"
)
wxRsp, err := client.V3TransactionJsapi(bm)
if err != nil {
xlog.Error(err)
return
}
// wxPublicKey pass client.WxPublicKey() gain
err = wechat.V3VerifySignByPK(wxRsp.SignInfo.HeaderTimestamp, wxRsp.SignInfo.HeaderNonce, wxRsp.SignInfo.SignBody, wxRsp.SignInfo.HeaderSignature, wxPublicKey)
if err != nil {
xlog.Error(err)
return
}
- Asynchronous notification check and sensitive parameter decryption
import (
"github.com/go-pay/gopay/wechat/v3"
"github.com/go-pay/gopay/pkg/xlog"
)
notifyReq, err := wechat.V3ParseNotify()
if err != nil {
xlog.Error(err)
return
}
// wxPublicKey pass client.WxPublicKey() gain
err = notifyReq.VerifySignByPK(wxPublicKey)
if err != nil {
xlog.Error(err)
return
}
// ========Asynchronous notification decrypts sensitive information========
// Decrypt ordinary payment notifications
result, err := notifyReq.DecryptCipherText(apiV3Key)
// Declassified payment notice
result, err := notifyReq.DecryptCombineCipherText(apiV3Key)
// Refund notice decryption
result, err := notifyReq.DecryptRefundCipherText(apiV3Key)
// ========Asynchronous notification response========
// Refund notification If the http response code is 200 and the return status code is SUCCESS, the merchant will be considered to have received it successfully, otherwise it will be retried.
// Note: Too many retries will cause the wechat Pay side to backlog too many notifications and blockage, affecting other normal notifications.
// This writing is the writing of gin frame back to wechat
c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "succeed"})
// This writing is the echo frame back to wechat writing
return c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "succeed"})