Go language collection payment library – Support wechat, Alipay, PayPal, QQ payment

Go language collection payment library – Support wechat, Alipay, PayPal, QQ payment

2022-09-02 0 10,094
Resource Number 38021 Last Updated 2025-02-24
¥ 0USD Upgrade VIP
Download Now Matters needing attention
Can't download? Please contact customer service to submit a link error!
Value-added Service: Installation Guide Environment Configuration Secondary Development Template Modification Source Code Installation

This issue recommends a Go language related collection payment library – support wechat, Alipay, PayPal, QQ payment.

Go language 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"})
资源下载此资源为免费资源立即下载
Telegram:@John_Software

Disclaimer: This article is published by a third party and represents the views of the author only and has nothing to do with this website. This site does not make any guarantee or commitment to the authenticity, completeness and timeliness of this article and all or part of its content, please readers for reference only, and please verify the relevant content. The publication or republication of articles by this website for the purpose of conveying more information does not mean that it endorses its views or confirms its description, nor does it mean that this website is responsible for its authenticity.

Ictcoder Free source code Go language collection payment library – Support wechat, Alipay, PayPal, QQ payment https://ictcoder.com/kyym/go-language-collection-payment-library-support-wechat-alipay-paypal-qq-payment.html

Share free open-source source code

Q&A
  • 1, automatic: after taking the photo, click the (download) link to download; 2. Manual: After taking the photo, contact the seller to issue it or contact the official to find the developer to ship.
View details
  • 1, the default transaction cycle of the source code: manual delivery of goods for 1-3 days, and the user payment amount will enter the platform guarantee until the completion of the transaction or 3-7 days can be issued, in case of disputes indefinitely extend the collection amount until the dispute is resolved or refunded!
View details
  • 1. Heptalon will permanently archive the process of trading between the two parties and the snapshots of the traded goods to ensure that the transaction is true, effective and safe! 2, Seven PAWS can not guarantee such as "permanent package update", "permanent technical support" and other similar transactions after the merchant commitment, please identify the buyer; 3, in the source code at the same time there is a website demonstration and picture demonstration, and the site is inconsistent with the diagram, the default according to the diagram as the dispute evaluation basis (except for special statements or agreement); 4, in the absence of "no legitimate basis for refund", the commodity written "once sold, no support for refund" and other similar statements, shall be deemed invalid; 5, before the shooting, the transaction content agreed by the two parties on QQ can also be the basis for dispute judgment (agreement and description of the conflict, the agreement shall prevail); 6, because the chat record can be used as the basis for dispute judgment, so when the two sides contact, only communicate with the other party on the QQ and mobile phone number left on the systemhere, in case the other party does not recognize self-commitment. 7, although the probability of disputes is very small, but be sure to retain such important information as chat records, mobile phone messages, etc., in case of disputes, it is convenient for seven PAWS to intervene in rapid processing.
View details
  • 1. As a third-party intermediary platform, Qichou protects the security of the transaction and the rights and interests of both buyers and sellers according to the transaction contract (commodity description, content agreed before the transaction); 2, non-platform online trading projects, any consequences have nothing to do with mutual site; No matter the seller for any reason to require offline transactions, please contact the management report.
View details

Related Article

make a comment
No comments available at the moment
Official customer service team

To solve your worries - 24 hours online professional service