smartwalle/alipay Go SDK

repository·master·Indexed 24 days ago

https://github.com/smartwalle/alipay

An Alipay SDK for Golang supporting various payment methods (Wap, App, Page) and both certificate-based and public-key-based authentication. It provides tools for initializing clients, configuring RSA2 signing, handling synchronous callbacks and asynchronous notifications, and executing Alipay API requests via built-in methods or custom payloads.

Tokens
18.7K
Snippets
29
Records
134
Agent score
85%

What's inside smartwalle/alipay

  1. Use Custom Requests for Unimplemented Interfaces

    master

    If the SDK does not have a built-in method for a specific Alipay interface, you can use alipay.NewPayload combined with alipay.Client methods to perform the request.

    Depending on your goal, use one of the following three methods:

    1. Request(payload, &result): To make a network request to Alipay (e.g., for querying transaction status).
    2. BuildURL(payload): To generate a URL for web-based payments (e.g., alipay.trade.page.pay).
    3. EncodeParam(payload): To generate signed parameters (e.g., for App payments like alipay.trade.app.pay).
  2. Configure Public Certificate Mode

    master

    If you use the Public Certificate mode for signature verification, you must load the certificates downloaded from your Alipay application.

    Note: You cannot use Public Certificate mode and Ordinary Public Key mode simultaneously; you must choose one.

  3. Install the Alipay SDK v3

    master

    To use the recommended v3 version of the SDK with Go modules, run the following command:

    go get github.com/smartwalle/alipay/v3

    Then import it in your Go code:

    import "github.com/smartwalle/alipay/v3"

    If you are not using Go modules, use:

    go get github.com/smartwalle/alipay

    and import github.com/smartwalle/alipay.

    go get github.com/smartwalle/alipay/v3
  4. Handle Asynchronous Notifications (notify_url)

    master

    When Alipay's server calls your NotifyURL, use DecodeNotification to parse the message and verify the signature automatically.

    After successfully processing the notification, you must call alipay.ACKNotification(writer) to acknowledge receipt; otherwise, Alipay will continue to send the same notification.

  5. Configure the Alipay Sandbox Environment

    master

    Alipay provides a sandbox environment for development and testing, which includes independent merchant and buyer accounts.

    There are two gateway addresses:

    • New address (Default): https://openapi-sandbox.dl.alipaydev.com/gateway.do
    • Old address: https://openapi.alipaydev.com/gateway.do

    By default, the SDK uses the new address. If your integration requires the old address, specify it during initialization using alipay.WithPastSandboxGateway().

    alipay.New(appId, privateKey, isProduction, alipay.WithPastSandboxGateway())
  6. Configure Application Credentials and Certificates

    master

    The SDK uses RSA2 for signing. When generating keys using the Alipay RSA signing tool, a key length of 2048 is recommended. Ensure you configure RSA2(SHA256) keys in the Alipay management console.

    To use the Certificate Mode (Public Key Certificate mode), you must load the following files into the client:

    1. App Certificate Public Key: Your application's public certificate.
    2. Alipay Root Certificate: The root certificate from Alipay.
    3. Alipay Certificate Public Key: The public key certificate from Alipay.

    You can also optionally set an encryption key for interface content encryption using SetEncryptKey.

  7. Verify Synchronous Callbacks (return_url)

    master

    When a user is redirected back to your ReturnURL after a web payment, use VerifySign to validate the parameters provided by Alipay.

    Important: It is recommended that your ReturnURL does not contain any extra query parameters, as VerifySign validates all received parameters. If you must use parameters, remove them from request.Form before calling VerifySign.

  8. Understand TradeStatus values

    master

    When querying a transaction, the TradeStatus field in the response indicates the current state of the order. Use the TradeStatus type to handle these constants:

    • WAIT_BUYER_PAY: Transaction created, awaiting buyer payment.
    • TRADE_SUCCESS: Payment successful.
    • TRADE_CLOSED: Transaction closed due to timeout or full refund.
    • TRADE_FINISHED: Transaction finished and cannot be refunded.
    // Possible values for TradeStatus
    const (
    	TradeStatusWaitBuyerPay TradeStatus = "WAIT_BUYER_PAY"
    	TradeStatusClosed       TradeStatus = "TRADE_CLOSED"
    	TradeStatusSuccess      TradeStatus = "TRADE_SUCCESS"
    	TradeStatusFinished     TradeStatus = "TRADE_FINISHED"
    )
  9. Manage fund authorization (Pre-authorization)

    master

    This project supports several stages of the fund authorization lifecycle:

    1. Create Voucher: Use FundAuthOrderVoucherCreate to create an authorization order. This returns a CodeValue or CodeURL for the user to complete the payment.
    2. Freeze Funds: Use FundAuthOrderFreeze (or FundAuthOrderAppFreeze for online scenarios) to freeze the specified Amount using an AuthCode.
    3. Unfreeze Funds: Use FundAuthOrderUnfreeze to release frozen funds back to the user.
    4. Cancel Operation: Use FundAuthOperationCancel to cancel an authorization operation.
    5. Query Details: Use FundAuthOperationDetailQuery to check the status and amounts of an authorization order.

    Order Statuses:

    • INIT: Created but not authorized.
    • AUTHORIZED: Authorization successful; ready for payment or unfreezing.
    • FINISH: Payment completed and no remaining frozen funds.
    • CLOSED: Authorization timed out or all funds were unfrozen.
  10. Configure the Client with Options

    master

    The New and NewWithSigner functions accept functional options to customize the client behavior:

    • WithTimeLocation(location *time.Location): Sets the time location for timestamp generation.
    • WithHTTPClient(client *http.Client): Provides a custom HTTP client.
    • WithVerifier(aliCertSN string, verifier Verifier): Registers a custom verifier for a specific Alipay certificate serial number (useful if certificates are managed externally).
    • WithSandboxGateway(gateway string): Sets a custom gateway for sandbox mode.
    • WithProductionGateway(gateway string): Sets a custom gateway for production mode.
    • WithNewSandboxGateway(): Explicitly sets the new sandbox gateway.
    • WithPastSandboxGateway(): Sets the legacy sandbox gateway.
  11. Initialize the Alipay Client

    master

    To start using the SDK, use New to create a client. You must provide your appId, your application's privateKey, and a boolean indicating if you are in production mode. If production is false, the client defaults to the sandbox environment.

    You can also use NewWithSigner if your private key is managed by a third party and you need to provide a custom nsign.Signer implementation.

  12. Load Alipay Public Keys and Certificates

    master

    To verify signatures from Alipay, you must load their public keys or certificates into the client. The SDK supports several modes:

    Public Key Mode

    Use LoadAliPayPublicKey(s string) to load a standard RSA public key string.

    Load certificates to handle serial numbers automatically:

    • LoadAppCertPublicKey(s string): Load your application's public key certificate.
    • LoadAppCertPublicKeyFromFile(filename string): Load your application's public key certificate from a file.
    • LoadAlipayCertPublicKey(s string): Load an Alipay public key certificate.
    • LoadAlipayCertPublicKeyFromFile(filename string): Load an Alipay public key certificate from a file.
    • LoadAliPayRootCert(s string): Load Alipay root certificates (supports multiple certificates separated by the internal constant kCertificateEnd).
    • LoadAliPayRootCertFromFile(filename string): Load Alipay root certificates from a file.