Alipay SDK for .NET

repository·master·Indexed 42 days ago

https://github.com/alipay/alipay-sdk-net-all

A professional toolkit for integrating Alipay services into .NET applications. It automates security, signing, and communication protocols. The SDK provides two versions: v2 and v3, with v3 featuring a RESTful design based on the OpenAPI Specification (OAS) and JSON data interaction. Available via NuGet as AlipaySDKNet and AlipaySDKNet.Standard.

Tokens
551.3K
Snippets
745
Records
813
Agent score
50%

What's inside Alipay SDK for .NET

  1. Overview of Alipay SDK for .NET

    master

    The Alipay SDK for .NET automates non-functional requirements during API calls, including certificate validation, signing (加签), verification (验签), and sending HTTP requests.

    The SDK provides two versions to suit different integration needs:

    • v2: Uses the v2 protocol.
    • v3: Uses the v3 protocol, which follows RESTful design principles and the OpenAPI Specification (OAS).
  2. Use AlipayIserviceCcmSwTreeApi for Knowledge Base Category Management

    master

    The AlipayIserviceCcmSwTreeApi class provides methods to manage knowledge base categories (知识库-类目). It supports batch querying, creating, deleting, retrieving, modifying, and publishing categories. All URIs are relative to https://openapi.alipay.com.

    // Available methods:
    // Batchquery (GET)
    // Create (PUT)
    // Delete (DELETE)
    // Get (GET)
    // Modify (PATCH)
    // Publish (PUT)
  3. Use AlipayEcoEduKtBillingApi to manage education billing

    master

    The AlipayEcoEduKtBillingApi class provides methods for managing education fee billing within the Alipay ecosystem. It allows ISVs (Independent Software Vendors) to send billing information to parents, query existing bills, and synchronize billing statuses (e.g., successful or failed payments) after reconciliation in their own systems.

    Available methods:

    • Modify: Synchronize the status of an education fee bill.
    • Query: Retrieve details of a specific billing record.
    • Send: Send an education fee bill to a child so parents can view it in Alipay.
    var apiInstance = new AlipayEcoEduKtBillingApi(config);
  4. Use AlipayOpenInstantdeliveryMerchantshopApi for Instant Delivery Merchant Shop Management

    master

    The AlipayOpenInstantdeliveryMerchantshopApi class provides methods to manage merchant shops within the instant delivery scenario. It supports paginated querying, creating new shops, modifying existing shops, and retrieving shop details.

    Available Methods

    MethodHTTP RequestDescription
    BatchqueryPOST /v3/alipay/open/instantdelivery/merchantshop/batchqueryPaginated query of merchant shops
    CreatePOST /v3/alipay/open/instantdelivery/merchantshop/createCreate a new merchant shop
    ModifyPOST /v3/alipay/open/instantdelivery/merchantshop/modifyUpdate an existing merchant shop
    QueryGET /v3/alipay/open/instantdelivery/merchantshop/queryRetrieve detailed information for a specific shop

    Common Setup and Authentication

    All requests require an AlipayConfig object passed via AlipayConfigUtil to the API client. You can use either Key Mode or Certificate Mode.

    Key Mode Configuration:

    • AppId
    • PrivateKey
    • AlipayPublicKey
    • EncryptKey
    Configuration config = new Configuration();
    config.BasePath = "https://openapi.alipay.com";
    var apiInstance = new AlipayOpenInstantdeliveryMerchantshopApi(config);
    
    AlipayConfig alipayConfig = new AlipayConfig();
    alipayConfig.AppId = "app_id";
    alipayConfig.PrivateKey = "private_key";
    alipayConfig.AlipayPublicKey = "alipay_public_key";
    alipayConfig.EncryptKey = "encrypt_key";
    
    AlipayConfigUtil alipayConfigUtil = new AlipayConfigUtil(alipayConfig);
    apiInstance.Client.SetAlipayConfigUtil(alipayConfigUtil);
  5. Key differences in the v3 protocol

    master

    The v3 protocol introduces several improvements over the v2 protocol:

    • RESTful Design: Uses RESTful design styles described via the OpenAPI Specification (OAS).
    • Data Format: Uses JSON for data interaction instead of XML or form-based formats.
    • Simplified Signing: Simplifies the signing and verification logic by performing signing on the entire HTTP message.
    • Simplified Operations: Streamlines specifications for encryption/decryption and file uploads.
  6. Configure Alipay authentication for OpenAPI

    master

    To use the Alipay SDK, you must configure an AlipayConfig object and wrap it in an AlipayConfigUtil. You can use either Key Mode or Certificate Mode.

    Key Mode:

    • AppId: Your application ID.
    • PrivateKey: Your application's private key.
    • AlipayPublicKey: Alipay's public key.
    • EncryptKey: The encryption key.

    Certificate Mode:

    • AppCertPath: Path to your app certificate public key.
    • AlipayPublicCertPath: Path to Alipay's public certificate.
    • RootCertPath: Path to the root certificate.
    // Key Mode Example
    AlipayConfig alipayConfig = new AlipayConfig();
    alipayConfig.AppId = "app_id";
    alipayConfig.PrivateKey = "private_key";
    alipayConfig.AlipayPublicKey = "alipay_public_key";
    alipayConfig.EncryptKey = "encrypt_key";
    
    // Certificate Mode Example (uncomment to use)
    // alipayConfig.AppCertPath = "../appCertPublicKey.crt";
    // alipayConfig.AlipayPublicCertPath = "../alipayCertPublicKey_RSA2.crt";
    // alipayConfig.RootCertPath = "../alipayRootCert.crt";
    
    AlipayConfigUtil alipayConfigUtil = new AlipayConfigUtil(alipayConfig);
    apiInstance.Client.SetAlipayConfigUtil(alipayConfigUtil);
  7. Understand API Endpoint URIs in Alipay SDK .NET

    master
    When using the Alipay SDK for .NET, all API endpoint URIs are relative to the base URL https://openapi.alipay.com. Ensure that your configuration or request logic accounts for this base path when constructing full URLs for API calls.
  8. Required credentials for Alipay SDK integration

    master

    Before using the SDK, you must complete setup in the Alipay Developer Center (create application, add capability packages, set signing methods). The credentials you need to save depend on your chosen signing mode:

    If using Certificate Mode (Recommended):

    • AppID
    • Application Private Key (应用的私钥)
    • Application Public Certificate File (应用的公钥证书文件)
    • Alipay Public Certificate File (支付宝公钥证书文件)
    • Alipay Root Certificate File (支付宝根证书文件)

    If using Public Key Mode:

    • AppId
    • Application Private Key (应用的私钥)
    • Application Public Key (应用的公钥)
    • Alipay Public Key (支付宝公钥)
  9. Quickstart: Call an Alipay API in C#

    master

    To use the Alipay SDK, follow these three main steps:

    1. Initialize the client: Create an instance of IAopClient (typically DefaultAopClient) with your gateway URL, AppID, private key, and certificate parameters.
    2. Create the request: Instantiate the specific Request object for the API you want to call and populate its BizModel.
    3. Execute and handle response: Use client.CertificateExecute(request) to send the request and check the IsError property of the response to handle success or failure.

    Note: When using the recommended Certificate Mode, you must provide paths to your application public certificate, Alipay public certificate, and Alipay root certificate via CertParams.

    using System;
    using Aop.Api;
    using Aop.Api.Request;
    using Aop.Api.Response;
    using Aop.Api.Domain;
    
    namespace SDK.Demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    // 1. Create IAopClient instance
                    IAopClient client = new DefaultAopClient(
                        "https://openapi.alipay.com/gateway.do",
                        "2019091767145019", // Replace with your AppId
                        "MIIEowIBAAKCAQ ... ...", // Replace with your PKCS1 format App Private Key
                        "json", "1.0", "RSA2",
                        "utf-8", // Replace with your character encoding, recommended: utf-8
                        false, GetCertParams());
    
                    // 2. Create the Request object for the specific Open API
                    AlipayOpenOperationOpenbizmockBizQueryRequest request = GetRequest();
    
                    // 3. Execute request and handle response
                    AlipayOpenOperationOpenbizmockBizQueryResponse response = client.CertificateExecute(request);
                    if (!response.IsError)
                    {
                        Console.WriteLine("Call successful.");
                    }
                    else
                    {
                        Console.WriteLine("Call failed. Reason: " + response.Msg + ", " + response.SubMsg);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occurred: " + e.Message);
                    throw e;
                }
            }
    
            private static CertParams GetCertParams()
            {
                return new CertParams
                {
                    // Replace with your application public certificate file path
                    AlipayPublicCertPath = "/home/foo/alipayCertPublicKey_RSA2.crt",
                    // Replace with your Alipay public certificate file path
                    AppCertPath = "/home/foo/appCertPublicKey_2019090366875133.crt",
                    // Replace with your Alipay root certificate file path
                    RootCertPath = "/home/foo/alipayRootCert.crt"
                };
            }
    
            private static AlipayOpenOperationOpenbizmockBizQueryRequest GetRequest()
            {
                // Initialize Request and populate Model properties.
                AlipayOpenOperationOpenbizmockBizQueryRequest request = new AlipayOpenOperationOpenbizmockBizQueryRequest();
                AlipayOpenOperationOpenbizmockBizQueryModel model = new AlipayOpenOperationOpenbizmockBizQueryModel
                {
                    BizNo = "123456789"
                };
                request.SetBizModel(model);
                return request;
            }
        }
    }
  10. Configure AlipayConfig for EBPP API calls

    master

    To use the AlipayEbppInvoiceIssueruleApi, you must initialize a Configuration object and set up an AlipayConfig object. This configuration can be used in either Key Mode (using public keys) or Certificate Mode (using .crt files).

    Key Mode Configuration:

    • AppId: Your application ID.
    • PrivateKey: Your application's private key.
    • AlipayPublicKey: Alipay's public key.
    • EncryptKey: The encryption key.

    Certificate Mode Configuration:

    • AppCertPath: Path to your application certificate.
    • AlipayPublicCertPath: Path to Alipay's public certificate.
    • RootCertPath: Path to the root certificate.

    Once configured, wrap the AlipayConfig in an AlipayConfigUtil and pass it to the API client using apiInstance.Client.SetAlipayConfigUtil(alipayConfigUtil).

    Configuration config = new Configuration();
    config.BasePath = "https://openapi.alipay.com";
    var apiInstance = new AlipayEbppInvoiceIssueruleApi(config);
    
    // Setup AlipayConfig (Key Mode Example)
    AlipayConfig alipayConfig = new AlipayConfig();
    alipayConfig.AppId = "app_id";
    alipayConfig.PrivateKey = "private_key";
    alipayConfig.AlipayPublicKey = "alipay_public_key";
    alipayConfig.EncryptKey = "encrypt_key";
    
    AlipayConfigUtil alipayConfigUtil = new AlipayConfigUtil(alipayConfig);
    apiInstance.Client.SetAlipayConfigUtil(alipayConfigUtil);