GoPay SDK

repository·main·Indexed 26 days ago

https://github.com/go-pay/gopay

A Golang SDK providing unified integration for multiple payment gateways, including WeChat Pay, Alipay (Standard and V3), Douyin, PayPal, QQ, Allinpay, Lakala, Saobei, and Apple Pay verification. It includes a specialized HTTP request library (xhttp), a custom logging interface (xlog), and a BodyMap utility for managing and encoding request/response data for payment provider signatures.

Tokens
23.1K
Snippets
30
Records
130
Agent score
90%

What's inside gopay

  1. Initialize WeChat v3 Client

    main

    To use WeChat v3 APIs, initialize a client using wechat.NewClientV3. You must provide the Merchant ID (mchid), the certificate serial number (serialNo), the apiV3Key, and the content of your private key (apiclient_key.pem).

    Automatic Signature Verification Options:

    • Recommended for new users: Use AutoVerifySignByPublicKey by providing the WeChat Pay public key content and the Public Key ID (must include the PUB_KEY_ID_ prefix).
    • Alternative: Use AutoVerifySign() to automatically fetch and periodically update WeChat platform certificates.

    Note: WeChat v3 does not support sandbox environments; use a 0.01 CNY transaction for testing.

  2. Initialize the PayPal Client

    main

    To use the PayPal SDK, initialize a new client using paypal.NewClient with your Clientid and Secret. You can also configure the maximum HTTP response body size and enable debug logging.

    import (
        "github.com/go-pay/gopay/paypal"
        "github.com/go-pay/xlog"
    )
    
    // Initialize PayPal payment client
    client, err := paypal.NewClient(Clientid, Secret, false)
    if err != nil {
        xlog.Error(err)
        return
    }
    
    // Custom configuration for HTTP response body size (default is 10MB)
    client.SetBodySize()
    
    // Enable debug mode to output logs (default is off)
    client.DebugSwitch = gopay.DebugOn
  3. Initialize the Apple client

    main
    To use the App Store Server API features, initialize an Apple client using NewClient. You need to provide the issuer ID, bundle ID, key ID, the content of your private key, and a boolean indicating if you are in the production environment.
  4. Use Saobei Payment 2.0 APIs

    main

    The Saobei Payment 2.0 interface provides methods for processing payments, querying statuses, and handling refunds. For specific implementation details and usage examples, refer to the gopay/saobei/pay_test.go file in the repository.

    Available methods on the client:

    • client.MiniPay(): For Mini Program payments (requires a valid account for testing).
    • client.BarcodePay(): For barcode payment processing.
    • client.Query(): To query the status of a payment.
    • client.Refund(): To submit a refund application.
    • client.QueryRefund(): To query the status of a refund order.
  5. Parse and Verify WeChat Asynchronous Notifications

    main

    When WeChat sends an asynchronous notification (webhook), you must parse the request body and verify the signature to ensure authenticity.

    1. Parse: Use wechat.ParseNotifyToBodyMap(req) to convert the *http.Request into a BodyMap. For refund notifications, use wechat.ParseRefundNotify(req).
    2. Verify: Use wechat.VerifySign(apiKey, signType, bean) where bean is the parsed BodyMap or response struct.
    3. Refund Decryption: If processing a refund notification, the req_info field is encrypted. Use wechat.DecryptRefundNotifyReqInfo(reqInfo, apiKey) to decrypt it.
    4. Response: Always return a valid XML response to WeChat to acknowledge receipt. Use rsp.ToXmlString().

    Note: http.Request.Body can only be read once. If you need to debug or read it multiple times, handle body reuse manually.

  6. Initialize the Alipay V3 Client

    main

    To use Alipay V3, initialize a client using alipay.NewClientV3. You must provide your appid, your application privateKey (supports PKCS1 and PKCS8), and a boolean isProd to indicate if you are in a production environment. You must also load your certificates using SetCert.

    Available configuration methods:

    • SetAppAuthToken(token string): Sets the authorization token.
    • SetBodySize(): Customizes the HTTP response body size (default is 10MB).
    • SetRequestIdFunc(): Sets a custom method for generating RequestId.
    • SetAESKey(key string): Sets the biz_content encryption key (currently unavailable).
    • DebugSwitch: Set to gopay.DebugOn to enable debug logging.
  7. Disable TLS Certificate Verification for Sandbox/Self-signed Certificates

    main

    Starting from v1.5.119, TLS certificate verification is enabled by default to prevent MITM attacks. For sandbox environments or scenarios using self-signed certificates, you must manually inject an xhttp.Client that skips verification using SetHttpClient. This is supported for WeChat, Alipay, Douyin, PayPal, QQ, Allinpay, Lakala, and Saobei.

    import (
        "crypto/tls"
        "github.com/go-pay/gopay/pkg/xhttp"
    )
    
    hc := xhttp.NewClient().SetHttpTLSConfig(&tls.Config{InsecureSkipVerify: true})
    client.SetHttpClient(hc) // wechat / alipay / douyin / paypal / qq / allinpay / lakala / saobei 均支持
  8. Initialize the Alipay client

    main

    To use Alipay, initialize an alipay.Client using your application ID and private key (supports PKCS1 and PKCS8). You can specify if you are in a production environment via the isProd boolean.

    Key configuration options include:

    • SetLocation: Set the timezone (e.g., alipay.LocationShanghai).
    • SetCharset: Set character encoding (defaults to utf-8).
    • SetSignType: Set signature type (e.g., alipay.RSA2).
    • SetReturnUrl / SetNotifyUrl: Set URLs for synchronous returns and asynchronous notifications.
    • AutoVerifySign: Enables automatic signature verification (requires certificate mode).
    • SetCertSnByPath / SetCertSnByContent: Configure public key certificate mode using file paths or byte content.
    • DebugSwitch: Enable logging by setting to gopay.DebugOn.
    import (
        "github.com/go-pay/gopay/alipay"
        "github.com/go-pay/xlog"
    )
    
    // appid: application ID
    // privateKey: application private key (PKCS1 or PKCS8)
    // isProd: false for sandbox, true for production
    client, err := alipay.NewClient("2016091200494382", privateKey, false)
    if err != nil {
        xlog.Error(err)
        return
    }
    
    // Configuration examples
    client.SetLocation(alipay.LocationShanghai).
        SetCharset(alipay.UTF8).
        SetSignType(alipay.RSA2).
        SetReturnUrl("https://www.fmm.ink").
        SetNotifyUrl("https://www.fmm.ink")
    
    // Certificate mode (choose one)
    // By path:
    err := client.SetCertSnByPath("appPublicCert.crt", "alipayRootCert.crt", "alipayPublicCert.crt")
    // By content:
    err := client.SetCertSnByContent("appPublicCert.crt bytes", "alipayRootCert bytes", "alipayPublicCert.crt bytes")
  9. Use Saobei Funds and CBK Enterprise Wallet APIs

    main

    Saobei provides specialized interfaces for managing funds and enterprise wallet distribution (CBK).

    • Funds Interface: For managing merchant funds, refer to the examples in gopay/saobei/merchant_test.go.
    • CBK Enterprise Wallet Distribution: For enterprise wallet splitting/distribution, refer to the examples in gopay/saobei/account_test.go.
  10. Initialize the WeChat v2 Client

    main

    To use WeChat v2 APIs, initialize a client using wechat.NewClient. You must provide the appId, mchId (Merchant ID), apiKey, and a boolean isProd to indicate if you are in a production environment.

    Important Notes:

    • Use isProd = false for sandbox testing. Use isProd = true for real payments.
    • For certificates, you can either provide both apiclient_cert.pem and apiclient_key.pem OR a single apiclient_cert.p12 file.
    • You can enable debug mode via client.DebugSwitch = gopay.DebugOn to output request logs.