Alipay OpenAPI SDK for Node.js

repository·master·Indexed 19 days ago

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

A Node.js SDK (v4.14.0) for the Alipay Open Platform that enables developers to call Alipay API v3 interfaces. It provides functionality for request signing, verification, certificate management, and AES decryption. Key features include the .curl() method for API requests, pageExecute() for web payment forms/URLs, sdkExecute() for app payment strings, and AlipayFormData for file uploads. Requires Node.js >= 18.20.0.

Tokens
11.7K
Snippets
40
Records
46
Agent score
66%

What's inside alipay-sdk

  1. Migrate from alipay-sdk v3 to v4

    master

    When upgrading from version 3 to version 4, note the following breaking changes:

    1. Node.js Requirement: You must use Node.js version 18.20.0 or higher.
    2. CommonJS Import Change:
      • In v3: const AlipaySdk = require('alipay-sdk'); (exports directly to module.exports)
      • In v4: const { AlipaySdk } = require('alipay-sdk'); (exports under exports.AlipaySdk)
    3. exec() Method: If you pass options.formData to exec() and it does not contain a file, it will throw a TypeError. Use pageExecute() instead.

    To debug the SDK, you can use the NODE_DEBUG environment variable:

    NODE_DEBUG=alipay-sdk* node your-script.js
  2. Verify your Alipay SDK configuration

    master

    To ensure your configuration (keys, certificates, or IDs) is correct, call a basic interface using the .curl() method. If the response contains responseHttpStatus: 200, your configuration is successful.

    // Example using the alipay.user.deloauth.detail.query interface
    const result = await alipaySdk.curl('POST', '/v3/alipay/user/deloauth/detail/query', {
      body: {
        date: '20230102',
        offset: 20,
        limit: 1,
      },
    });
    
    console.log(result);
    // Success output example:
    // {
    //   data: {},
    //   responseHttpStatus: 200,
    //   traceId: '06033316171731016275628924348'
    // }
  3. Configure an HTTP proxy for API calls

    master

    If you need to call Alipay APIs through a fixed IP whitelist, you can configure a ProxyAgent when instantiating the AlipaySdk.

    import { AlipaySdk, ProxyAgent } from 'alipay-sdk';
    
    const alipaySdk = new AlipaySdk({
      // ... other config
      proxyAgent: new ProxyAgent('http(s)://your-http-proxy-address'),
    });
    
    // All subsequent http calls via this instance will use the proxy
    const result = await alipaySdk.curl('POST', '/v3/alipay/user/deloauth/detail/query', { ... });
    import { AlipaySdk, ProxyAgent } from 'alipay-sdk';
    
    // 实例化客户端
    const alipaySdk = new AlipaySdk({
      // 其他配置不展示
      // ...
      proxyAgent: new ProxyAgent('http(s)://your-http-proxy-address'),
    });
    
    // 后续的所有 http 调用都会走此 HTTP 代理服务器
    const result = await alipaySdk.curl('POST', '/v3/alipay/user/deloauth/detail/query', {
      body: {
        date: '20230102',
        offset: 20,
        limit: 1,
      },
    });
    
    console.log(result);
  4. Configure AlipaySdkConfig options

    master

    The AlipaySdkConfig object defines how the SDK authenticates and communicates with Alipay.

    Required Fields:

    • appId: Your application ID.
    • privateKey: Your application private key string.

    Optional Fields:

    • signType: Signature type. Defaults to "RSA2". Supports "RSA2" or "RSA".
    • alipayPublicKey: Alipay public key (required if you need to verify responses).
    • gateway: The gateway URL.
    • timeout: Gateway timeout in milliseconds (default: 5000).
    • camelcase: Whether to convert snake_case responses to camelCase (default: true).
    • keyType: Type of privateKey. Defaults to "PKCS1". Supports "PKCS1" or "PKCS8".
    • appCertPath / appCertContent / appCertSn: Application public key certificate settings.
    • alipayRootCertPath / alipayRootCertContent / alipayRootCertSn: Alipay root certificate settings.
    • alipayPublicCertPath / alipayPublicCertContent / alipayCertSn: Alipay public key certificate settings.
    • encryptKey: AES key for AES encryption/decryption interfaces.
    • wsServiceUrl: Server address.
  5. Initialize the AlipaySdk

    master

    To use the SDK, instantiate the AlipaySdk class with a configuration object. The configuration requires appId and privateKey. The SDK supports both 'Ordinary Public Key' mode and 'Certificate' mode. If you provide certificate paths or content (e.g., appCertPath, appCertContent), the SDK automatically extracts serial numbers and loads public keys.

    import { AlipaySdk } from 'alipay-sdk';
    
    const sdk = new AlipaySdk({
      appId: 'YOUR_APP_ID',
      privateKey: 'YOUR_PRIVATE_KEY',
      // For Certificate Mode:
      appCertPath: './path/to/appCert.cert',
      alipayPublicCertPath: './path/to/alipayPublicCert.cert',
      alipayRootCertPath: './path/to/alipayRootCert.cert',
      // For Ordinary Public Key Mode:
      alipayPublicKey: 'YOUR_ALIPAY_PUBLIC_KEY',
    });
  6. Initialize the AlipaySdk with configuration

    master

    To use the SDK, instantiate the AlipaySdk class by passing an AlipaySdkConfig object. This object contains your application credentials and security settings.

    const alipaySdk = new AlipaySdk({
      appId: 'YOUR_APP_ID',
      privateKey: 'YOUR_PRIVATE_KEY',
      // ... other config options
    });
  7. Generate App payment strings with sdkExecute()

    master

    The sdkExecute method is used for server-side generation of request strings. These strings are sent to a client (like a mobile App or Mini Program) which then uses them to invoke the Alipay client to complete the payment. It does not trigger a direct payment from the server.

    Example for App payment:

    const orderStr = sdk.sdkExecute('alipay.trade.app.pay', {
      bizContent: {
        out_trade_no: "ALIPfdf1211sdfsd12gfddsgs3",
        product_code: "FAST_INSTANT_TRADE_PAY",
        subject: "abc",
        body: "234",
        total_amount: "0.01"
      },
      returnUrl: 'https://www.taobao.com'
    });
    
    // The resulting orderStr is then passed to the client-side SDK (e.g., my.tradePay in Mini Programs)
    // App 支付接口,生成请求字符串,
    const orderStr = sdk.sdkExecute('alipay.trade.app.pay', {
      bizContent: {
        out_trade_no: "ALIPfdf1211sdfsd12gfddsgs3",
        product_code: "FAST_INSTANT_TRADE_PAY",
        subject: "abc",
        body: "234",
        total_amount: "0.01"
      },
      returnUrl: 'https://www.taobao.com'
    });
    
    console.log(orderStr);
  8. Deprecated: Use alipaySdk.exec() for API v2

    master

    The exec method is used for calling Alipay API v2 protocol interfaces.

    Warning: This method is deprecated. It is maintained for backward compatibility during the migration from alipay-sdk@3 to alipay-sdk@4. Please switch to alipaySdk.curl() to use the API v3 protocol as soon as possible.

    Parameters:

    • method: The interface method name.
    • bizParams: IRequestParams containing bizContent and optional needEncrypt.
    • options: IRequestOption containing validateSign and log.

    Returns: Promise<AlipaySdkCommonResult> containing code, msg, sub_code, and sub_msg.

  9. Initialize the AlipaySdk using Public Key mode

    master

    In Public Key mode, you provide your application ID, your application's private key, and the Alipay public key.

    Important Note on Key Formats: This SDK defaults to PKCS1 format. If you use the Alipay Key Tool and it generates a different format, you must either:

    1. Use the 'Format Conversion' feature in the Key Tool to convert your keys to PKCS1.
    2. Explicitly set keyType: 'PKCS8' in the configuration object.

    Required configuration keys:

    • appId: Your application ID.
    • privateKey: Your application's private key (read as an ASCII string).
    • alipayPublicKey: Alipay's public key (read as an ASCII string).
    • keyType: (Optional) Set to 'PKCS8' if your keys are not in PKCS1 format.
    • endpoint: (Optional) The gateway address. Defaults to https://openapi.alipay.com.
    import { AlipaySdk } from 'alipay-sdk';
    import fs from 'fs';
    
    // Instantiate the client
    const alipaySdk = new AlipaySdk({
      // Set application ID
      appId: 'your-APPID',
      // Set application private key
      privateKey: fs.readFileSync('/path/to/private-key.pem', 'ascii'),
      // Set Alipay public key
      alipayPublicKey: fs.readFileSync('/path/to/alipay-public-key.pem', 'ascii'),
      // Key type, must match the generated key format
      // keyType: 'PKCS1',
      // Set gateway address, default is https://openapi.alipay.com
      // endpoint: 'https://openapi.alipay.com',
    });
  10. Upload files using AlipayFormData

    master

    For interfaces requiring file uploads, use the AlipayFormData class to construct multipart/form-data requests. You can add files using file paths, file streams, or file buffers.

    Using a file path

    const form = new AlipayFormData();
    form.addFile('file_content', 'image.jpg', path.join(__dirname, './test.jpg'));

    Using a file stream

    import fs from 'node:fs';
    const form = new AlipayFormData();
    form.addFile('file_content', 'image.jpg', fs.createReadStream('/path/to/test-file'));

    Using a file buffer

    import fs from 'node:fs';
    const form = new AlipayFormData();
    form.addFile('file_content', 'image.jpg', fs.readFileSync('/path/to/test-file'));

    To execute the upload, pass the form instance in the curl options:

    const uploadResult = await alipaySdk.curl<{ file_id: string }>('POST', '/v3/alipay/open/file/upload', {
      form,
      body: {
        biz_code: 'openpt_appstore',
      },
    });
    import { AlipayFormData } from 'alipay-sdk';
    
    const form = new AlipayFormData();
    form.addFile('file_content', '图片.jpg', path.join(__dirname, './test.jpg'));
    
    const uploadResult = await alipaySdk.curl<{
      file_id: string;
    }>
    ('POST', '/v3/alipay/open/file/upload', {
      form,
      body: {
        biz_code: 'openpt_appstore',
      },
    });
    
    console.log(uploadResult);
    // {
    //   data: { file_id: 'A*7Cr9T6IAAC4AAAAAAAAAAAAAATcnAA' },
    //   responseHttpStatus: 200,
    //   traceId: '06033316171731110716358764348'
    // }