Alipay Easy SDK

repository·master·Indexed 22 days ago

https://github.com/alipay/alipay-easysdk

A streamlined, high-efficiency server-side SDK for the Alipay Open Platform available for .NET, Java, and PHP. It simplifies complex API calls into natural-language-like methods focusing on high-frequency business scenarios across capabilities such as Payment, Member, Marketing, Security, and Base. The SDK supports Public Key Certificate and Public Key signing modes and provides extensibility for ISV proxy calling, custom asynchronous notifications, and optional business parameters.

Tokens
42.9K
Snippets
148
Records
169
Agent score
66%

What's inside alipay-easysdk

  1. Overview of Alipay Easy SDK

    master

    Alipay Easy SDK is a server-side SDK designed to provide a simplified, high-efficiency programming experience for accessing Alipay Open Platform core capabilities. Unlike the traditional Alipay SDK which is comprehensive and general-purpose, the Easy SDK focuses on high-frequency scenarios with a streamlined API design that mimics natural language and built-in language functions.

    Key benefits include:

    • Minimalist Code Style: Reduces multi-line boilerplate into single-line calls.
    • Global Singleton Access: Uses a Factory pattern for easy access anywhere in your code.
    • Parameter Optimization: Focuses on essential parameters for common tasks while allowing flexible extension for low-frequency or custom parameters.
    • Consistent Multi-language Experience: Built using the Darabonba DSL, ensuring consistent API patterns across Java, C#, and PHP.
  2. Extend API calls with optional parameters and ISV features

    master

    The SDK provides extension methods to handle advanced scenarios without changing the core API structure:

    • ISV Proxy Calling: Use .agent("auth_token") to perform calls on behalf of an agent.
    • Custom Async Notification: Use .asyncNotify("url") to override the global notifyUrl for a specific request.
    • Optional Business Parameters: Use .optional(key, value) or .batchOptional(Map<String, Object>) to set fields within biz_content.

    These extension methods can be chained in any order.

    // Example of combining extensions
    Factory.Payment.FaceToFace()
        .agent("ca34ea491e7146cc87d25fca24c4cD11") // ISV Agent
        .asyncNotify("https://www.test.com/callback") // Specific callback
        .optional("seller_id", "2088102146225135") // Single optional param
        .preCreate("Apple iPhone11", "2234567890", "5799.00");
    
    // Using batchOptional for multiple business parameters
    Map<String, Object> optionalArgs = new HashMap<>();
    optionalArgs.put("seller_id", "2088102146225135");
    optionalArgs.put("discountable_amount", "8.88");
    
    Factory.Payment.FaceToFace()
        .batchOptional(optionalArgs)
        .preCreate("Apple iPhone11", "2234567890", "5799.00");
  3. Understand the SDK versioning scheme

    master

    The SDK follows Semantic Versioning (SemVer) to communicate the impact of updates:

    • Patch updates (e.g., 1.0.0 $\rightarrow$ 1.0.1): Bug fixes only. No changes to SDK functionality.
    • Minor updates (e.g., 1.0.0 $\rightarrow$ 1.1.0): New features or modifications that are backward compatible.
    • Major updates (e.g., 1.0.0 $\rightarrow$ 2.0.0): Significant changes that are not backward compatible. Regression testing is highly recommended after upgrading major versions.
  4. Understand the API organization pattern

    master

    The SDK organizes its API structure to match the Alipay Capability Map. The invocation pattern follows this hierarchy:

    Factory.CapabilityName.ScenarioName().MethodName(...)

    For example, to use the TemplateMessage scenario under the Marketing capability, you would call: Factory.Marketing.TemplateMessage().send(...)

    Method names are simplified versions of the underlying OpenAPI functions, but their input and output parameters remain consistent with the official OpenAPI documentation.

  5. Compare Alipay Easy SDK vs traditional Alipay SDK

    master

    The following table highlights the differences in developer experience:

    FeatureAlipay Easy SDKAlipay SDK
    Code StyleMinimalist, natural language styleTraditional, requires multiple lines per call
    Instance ManagementFactory singleton available globallyAlipayClient must be created and passed manually
    ParametersOptimized for high-frequency use; supports optional assemblyNo distinction between high/low frequency; up to dozens of parameters per API
    // Alipay Easy SDK Example
    Factory.Payment.Common().create("Iphone6 16G", "202003019443", "0.10", "2088002656718920");
    
    // Alipay SDK Example (Traditional)
    AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
    AlipayTradeCreateModel model = new AlipayTradeCreateModel();
    model.setSubject("Iphone6 16G");
    model.setOutTradeNo("202003019443");
    model.setTotalAmount("0.10");
    model.setBuyerId("2088002656718920");
    request.setBizModel(model);
    alipayClient.execute(request);
  6. Understand the Alipay Easy SDK API organization pattern

    master

    The API structure in Alipay Easy SDK follows the hierarchy of the Alipay Capability Map. The invocation path follows this pattern:

    Factory.CapabilityCategory.ScenarioCategory.MethodName(...)

    For example, to use the 'Send Template Message' feature under the 'Template Message' scenario within 'Marketing Capabilities', the call would be: Factory.Marketing.TemplateMessage().send(...).

    Method names are simplified summaries of the underlying OpenAPI functions, but the parameter meanings remain identical to the OpenAPI documentation.

  7. Quick Start: Call an Alipay API

    master

    Using the SDK involves three main steps: setting global options, making the API call, and handling the response or exceptions.

    1. Set Options: Use Factory::setOptions() once globally.
    2. API Call: Navigate the capability hierarchy using Factory::capability()->scenario()->method().
    3. Handle Response: Use Alipay\EasySDK\Kernel\Util\ResponseChecker to verify if the call was successful.
    <?php
    
    require 'vendor/autoload.php';
    use Alipay\EasySDK\Kernel\Factory;
    use Alipay\EasySDK\Kernel\Util\ResponseChecker;
    use Alipay\EasySDK\Kernel\Config;
    
    // 1. Set global options
    Factory::setOptions(getOptions());
    
    try {
        // 2. Make API call (e.g., Unified Order Creation)
        $result = Factory::payment()->common()->create("iPhone6 16G", "20200326235526001", "88.88", "2088002656718920");
        
        $responseChecker = new ResponseChecker();
        
        // 3. Handle response
        if ($responseChecker->success($result)) {
            echo "Success";
        } else {
            echo "Failed: " . $result->msg . " " . $result->subMsg;
        }
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
    
    function getOptions() {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = 'YOUR_APP_ID';
        $options->merchantPrivateKey = 'YOUR_PRIVATE_KEY';
        $options->alipayCertPath = '/path/to/alipayCert.crt';
        $options->alipayRootCertPath = '/path/to/alipayRoot.crt';
        $options->merchantCertPath = '/path/to/appCert.crt';
        return $options;
    }
  8. Extend API calls with agent, asyncNotify, and optional parameters

    master

    The SDK provides extension methods to modify API requests dynamically before execution.

    ISV Proxy Calling (agent)

    Use agent($appAuthToken) to perform a call on behalf of an ISV.

    Custom Asynchronous Notification (asyncNotify)

    Use asyncNotify($url) to set a specific callback URL for a single request. This overrides the global notifyUrl in Config.

    Business Parameters (optional and batchOptional)

    Use these to set optional fields within the biz_content of an API request:

    • optional($key, $value): Sets a single optional parameter.
    • batchOptional($array): Sets multiple optional parameters at once using an associative array.

    These methods can be chained in any order.

    // Example: Combining multiple extensions
    Factory::payment()->faceToFace()
        ->agent("ca34ea491e7146cc87d25fca24c4cD11")
        ->asyncNotify("https://www.test.com/callback")
        ->optional("seller_id", "2088102146225135")
        ->batchOptional(["timeout_express" => "10m", "body" => "Iphone6 16G"])
        ->preCreate("Apple iPhone11 128G", "2234567890", "5799.00");
  9. Perform a standard API call

    master

    A standard API call follows three steps:

    1. Set parameters: Call Factory.SetOptions once globally.
    2. Invoke API: Use the Factory pattern to navigate to the desired capability and method.
    3. Handle response: Use ResponseChecker.Success(response) to verify if the call succeeded and handle exceptions with a try-catch block.

    Example: Creating a Face-to-Face Payment QR code.

    using System;
    using Alipay.EasySDK.Factory;
    using Alipay.EasySDK.Kernel;
    using Alipay.EasySDK.Kernel.Util;
    using Alipay.EasySDK.Payment.FaceToFace.Models;
    
    // ... inside Main ...
    Factory.SetOptions(GetConfig());
    try
    {
        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
            .PreCreate("Apple iPhone11 128G", "2234567234890", "5799.00");
    
        if (ResponseChecker.Success(response))
        {
            Console.WriteLine("Success");
        }
        else
        {
            Console.WriteLine($"Failed: {response.Msg}, {response.SubMsg}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
    }
  10. Install AlipayEasySDK via NuGet or .NET CLI

    master

    You can install the Alipay Easy SDK for .NET using the NuGet Package Manager or the .NET CLI.

    Using NuGet Package Manager:

    1. Right-click your project in the Solution Explorer and select Manage NuGet Packages.
    2. Go to the Browse tab and search for AlipayEasySDK.
    3. Select the package where Authors is antopen and click Install.

    Using .NET CLI: Run the following command in your terminal:

    dotnet add package AlipayEasySDK
    dotnet add package AlipayEasySDK
  11. Install Alipay Easy SDK for PHP

    master

    You can install the SDK using Composer (recommended) or by manually integrating the dependencies.

    Run the following command in your project directory:

    Manual Integration

    1. Ensure Composer is installed on your machine.
    2. Run composer install in the SDK directory to download dependencies into the vendor folder.
    composer require alipaysdk/easysdk:^2.0
  12. Install Alipay Easy SDK for Java via Maven

    master

    To use the Alipay Easy SDK in your Java project, add the following dependency to your pom.xml file. Check Maven Central for the latest version number.

    <dependency>
        <groupId>com.alipay.sdk</groupId>
        <artifactId>alipay-easysdk</artifactId>
        <version>Use the version shown in the maven badge</version>
    </dependency>