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,493
Resource Number 38021 Last Updated 2025-02-24
¥ 0HKD 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/go-language-collection-payment-library-support-wechat-alipay-paypal-qq-payment/

Share free open-source source code

Q&A
  • 1. Automatic: After making an online payment, click the (Download) link to download the source code; 2. Manual: Contact the seller or the official to check if the template is consistent. Then, place an order and make payment online. The seller ships the goods, and both parties inspect and confirm that there are no issues. ICTcoder will then settle the payment for the seller. Note: Please ensure to place your order and make payment through ICTcoder. If you do not place your order and make payment through ICTcoder, and the seller sends fake source code or encounters any issues, ICTcoder will not assist in resolving them, nor can we guarantee your funds!
View details
  • 1. Default transaction cycle for source code: The seller manually ships the goods within 1-3 days. The amount paid by the user will be held in escrow by ICTcoder until 7 days after the transaction is completed and both parties confirm that there are no issues. ICTcoder will then settle with the seller. In case of any disputes, ICTcoder will have staff to assist in handling until the dispute is resolved or a refund is made! If the buyer places an order and makes payment not through ICTcoder, any issues and disputes have nothing to do with ICTcoder, and ICTcoder will not be responsible for any liabilities!
View details
  • 1. ICTcoder will permanently archive the transaction process between both parties and snapshots of the traded goods to ensure the authenticity, validity, and security of the transaction! 2. ICTcoder cannot guarantee services such as "permanent package updates" and "permanent technical support" after the merchant's commitment. Buyers are advised to identify these services on their own. If necessary, they can contact ICTcoder for assistance; 3. When both website demonstration and image demonstration exist in the source code, and the text descriptions of the website and images are inconsistent, the text description of the image shall prevail as the basis for dispute resolution (excluding special statements or agreements); 4. If there is no statement such as "no legal basis for refund" or similar content, any indication on the product that "once sold, no refunds will be supported" or other similar declarations shall be deemed invalid; 5. Before the buyer places an order and makes payment, the transaction details agreed upon by both parties via WhatsApp or email can also serve as the basis for dispute resolution (in case of any inconsistency between the agreement and the description of the conflict, the agreement shall prevail); 6. Since chat records and email records can serve as the basis for dispute resolution, both parties should only communicate with each other through the contact information left on the system when contacting each other, in order to prevent the other party from denying their own commitments. 7. Although the probability of disputes is low, it is essential to retain important information such as chat records, text messages, and email records, in case a dispute arises, so that ICTcoder can intervene quickly.
View details
  • 1. As a third-party intermediary platform, ICTcoder solely protects transaction security and the rights and interests of both buyers and sellers based on the transaction contract (product description, agreed content before the transaction); 2. For online trading projects not on the ICTcoder platform, any consequences are unrelated to this platform; regardless of the reason why the seller requests an offline transaction, please contact the administrator to report.
View details

Related Source code

ICTcoder Customer Service

24-hour online professional services