### Installing Alipay SDK via npm Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Installs the Alipay SDK package using npm, saving it as a project dependency. Requires Node.js >= 18.20.0. ```bash npm install alipay-sdk --save ``` -------------------------------- ### Example HTML Form for Alipay Web Page Pay Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Provides an example of the HTML form generated by alipaySdk.pageExecute when using the 'POST' method. It includes hidden input fields for SDK version, business content, and other parameters, along with a script to auto-submit the form. ```html
``` -------------------------------- ### Initializing Alipay SDK (Public Key Mode) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Initializes the Alipay SDK client using the Public Key mode. Requires the App ID, application private key, and Alipay public key. Paths to key files are examples. ```typescript import { AlipaySdk } from 'alipay-sdk'; // 实例化客户端 const alipaySdk = new AlipaySdk({ // 设置应用 ID appId: 'your-APPID', // 设置应用私钥 privateKey: fs.readFileSync('/path/to/private-key.pem', 'ascii'), // 设置支付宝公钥 alipayPublicKey: fs.readFileSync('/path/to/alipay-public-key.pem', 'ascii'), // 密钥类型,请与生成的密钥格式保持一致,参考平台配置一节 // keyType: 'PKCS1', // 设置网关地址,默认是 https://openapi.alipay.com // endpoint: 'https://openapi.alipay.com', }); ``` -------------------------------- ### Call my.tradePay in Alipay Mini Program (JavaScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Provides an example of how to use the generated order string from sdkExecute within an Alipay Mini Program. It shows calling the my.tradePay API with the orderStr and handling success and failure callbacks. ```js // 返回支付宝客户端之后,在【小程序中】通过 my.tradePay 进行调用。 // 详见:https://opendocs.alipay.com/mini/api/openapi-pay my.tradePay({ // 服务端生成的字符串,即上面返回的 orderStr orderStr, success: (res) => { my.alert({ content: JSON.stringify(res), }); }, fail: (res) => { my.alert({ content: JSON.stringify(res), }); } }); ``` -------------------------------- ### Generate Payment URL for Web Page Pay using Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Shows how to generate a direct payment URL for web page payment using alipaySdk.pageExecute with the 'GET' method. It takes bizContent and returnUrl and returns a URL string that the user's browser can navigate to initiate the payment. ```ts // 支付页面接口,返回支付链接,交由用户打开,会跳转至支付宝网站 const url = sdk.pageExecute('alipay.trade.page.pay', 'GET', { bizContent, returnUrl: 'https://www.taobao.com' }); // 返回示例:https://openapi.alipay.com/gateway.do?method=alipay.trade.app.pay&app_id=2021002182632749&charset=utf-8&version=1.0&sign_type=RSA2×tamp=2023-02-28%2011%3A46%3A35&app_auth_token=202302BBbcfaf3bbfa99e8a6913F10&sign=TPi33NcaKLRBLJDofon84D8itMoBkVAdJsfmIiQDScEw4NHAklXvcvn148A2t47YxDSK0urBnhS0%2BEV%2BVR6h6aKgp931%2FfFbG1I3SAguMjMbr23gnbS68d4spcQ%3D%3D&alipay_sdk=alipay-sdk-nodejs-3.3.0&biz_content=blabla ``` -------------------------------- ### Upload File Content using Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Shows how to upload a file by reading its entire content into memory. It uses AlipayFormData and fs.readFileSync to get the file content as a buffer. The alipaySdk.curl method sends the POST request. ```ts import fs from 'node:fs'; import { AlipayFormData } from 'alipay-sdk'; const form = new AlipayFormData(); form.addFile('file_content', '图片.jpg', fs.readFileSync('/path/to/test-file')); 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' // } ``` -------------------------------- ### Verifying Frontend Response Signature - Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Shows how to verify the signature of a response received from the frontend using the `rsaCheck` method. This method requires the signed content (which must be quoted), the signature, and the signature type. The example includes the expected JSON structure from the frontend. ```JSON { "response": "hvDOnibG0DPcOFPNubK3DEfLQGL4=", "sign": "OIwk7zfZMp5GX78Ow==", "sign_type": "RSA2", "encrypt_type": "AES", "charset": "UTF-8" } ``` ```TypeScript // 注意,加密内容必须前后加上双引号 const signContent = '"hvDOnibG0DPcOFPNubK3DEfLQGL4="'; const sign = 'OIwk7zfZMp5GX78Ow=='; const signType = 'RSA2'; const signCheckPass = alipaySdk.rsaCheck(signContent, sign, signType); console.log(signCheckPass); ``` -------------------------------- ### Upload File Stream using Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Demonstrates uploading a file using a readable stream. It utilizes AlipayFormData to construct the form data and fs.createReadStream to get the file stream. The alipaySdk.curl method is used to send the POST request to the file upload endpoint. ```ts import fs from 'node:fs'; import { AlipayFormData } from 'alipay-sdk'; const form = new AlipayFormData(); form.addFile('file_content', '图片.jpg', fs.createReadStream('/path/to/test-file')); 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' // } ``` -------------------------------- ### Initializing Alipay SDK (Certificate Mode) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Initializes the Alipay SDK client using the recommended Certificate mode. Requires the App ID, application private key, Alipay root certificate, Alipay public key certificate, and application public key certificate paths. ```ts import { AlipaySdk } from 'alipay-sdk'; const alipaySdk = new AlipaySdk({ appId: '2016123456789012', privateKey: fs.readFileSync('/path/to/private-key.pem', 'ascii'), // 传入支付宝根证书、支付宝公钥证书和应用公钥证书。 alipayRootCertPath: '/path/to/alipayRootCert.crt', alipayPublicCertPath: '/path/to/alipayCertPublicKey_RSA2.crt', appCertPath: '/path/to/appCertPublicKey.crt', }); ``` -------------------------------- ### Enabling Debug Logs - Alipay SDK Node.js (Bash) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Explains how to enable debug logging for the Alipay SDK by setting the `NODE_DEBUG` environment variable before running the Node.js script. This helps in troubleshooting issues. ```Bash NODE_DEBUG=alipay-sdk* node your-script.js ``` -------------------------------- ### Calling API via HTTP Proxy - Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Demonstrates configuring the SDK to use an HTTP proxy server for all subsequent API calls. This is useful for scenarios requiring fixed IP whitelisting. It shows how to initialize the SDK with `proxyAgent` and then make a request using `curl`. ```TypeScript 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); ``` -------------------------------- ### Verifying SDK Configuration with curl Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Uses the `curl` method to call a basic Alipay API endpoint (`/v3/alipay/user/deloauth/detail/query`) to verify that the SDK configuration is correct. A successful call returns `responseHttpStatus: 200`. ```ts // https://opendocs.alipay.com/open-v3/668cd27c_alipay.user.deloauth.detail.query?pathHash=3ab93168 const result = await alipaySdk.curl('POST', '/v3/alipay/user/deloauth/detail/query', { body: { date: '20230102', offset: 20, limit: 1, }, }); console.log(result); ``` -------------------------------- ### Generate HTML Form for Web Page Pay using Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Illustrates generating an HTML form for web page payment using alipaySdk.pageExecute with the 'POST' method. It takes bizContent and returnUrl as parameters and returns the HTML string for the form, which is typically submitted automatically via JavaScript. ```ts const bizContent = { out_trade_no: "ALIPfdf1211sdfsd12gfddsgs3", product_code: "FAST_INSTANT_TRADE_PAY", subject: "abc", body: "234", total_amount: "0.01" }; // 支付页面接口,返回 HTML 代码片段,内容为 Form 表单 const html = alipaySdk.pageExecute('alipay.trade.page.pay', 'POST', { bizContent, returnUrl: 'https://www.taobao.com' }); ``` -------------------------------- ### Making an API Call with curl (Trade Pay) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Demonstrates how to use the `curl` method to call the Alipay Unified Receipt Transaction Payment API (`/v3/alipay/trade/pay`). Includes required business parameters like `out_trade_no`, `total_amount`, and `subject`. ```ts const result = await alipaySdk.curl('POST', '/v3/alipay/trade/pay', { body: { notify_url: 'http://www.your-notify.com/notify', // 通知回调地址 out_trade_no: '商家的交易码,需保持唯一性', total_amount: '0.1', subject: '测试订单', // 更多参数请查看文档 https://opendocs.alipay.com/open-v3/08c7f9f8_alipay.trade.pay?scene=32&pathHash=8bf49b74 } }); console.log(result); ``` -------------------------------- ### Making API Requests (Deprecated exec) - Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Demonstrates how to use the deprecated `exec` method to make requests to the Alipay server. Business parameters are placed within the `bizContent` object. Note that some interfaces may require parameters outside `bizContent`. This method is deprecated in favor of `curl`. ```TypeScript const result = await alipay.exec('alipay.trade.pay', { notify_url: 'http://www.your-notify.com/notify', // 通知回调地址 bizContent: { out_trade_no: '商家的交易码,需保持唯一性', total_amount: '0.1', subject: '测试订单', } }); ``` -------------------------------- ### Generate Order String for App Pay using Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Demonstrates generating the order string required for Alipay App payment using alipaySdk.sdkExecute. This method is server-side and produces a signed string containing payment details that needs to be passed to the client-side (e.g., mobile app, mini program) for the actual payment call. ```ts // 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); // method=alipay.trade.app.pay&app_id=2021002182632749&charset=utf-8&version=1.0&sign_type=RSA2×tamp=2023-02-24%2016%3A20%3A28&app_auth_token=202302BBbcfad868001a4df3bbfa99e8a6913F10&sign=M%2B2sTNATtUk3i8cOhHGtqjVDHIHSpPReZgjfLfIgbQD4AvI%2Fh%2B%2FS2lkqfJVnI%2Bu0IQ2z7auE1AYQ0wd7yPC4%2B2m5WnN21Q6uQhCCHOsg30mXdnkdB3rgXIiFOSuURRwnaiBmKNKdhaXel51fxYZOTOApV47K6ZUsOlPxc%2FVJWUnC7Hrl64%2BAKqtbv%2BcaefzapYsJwGDzMAGccHGfxevSoZ2Ev7S0FsrDe4LBx4m%2BCWSIFASWFyWYxJq%2BJg7LH1HJqBdBk1jjh5JJ3bNlEqJk8MEFU7sNRae2ErdEPOwCchWkQOaVGOGpFlEHuTSvxnAKnjRkFerE14v%2BVm6weC1Tbw%3D%3D&alipay_sdk=alipay-sdk-nodejs-3.2.0&biz_content=%7B%22out_trade_no%22%3A%22ziheng-test-eeee%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%E8%AE%A2%E5%8D%95%E6%A0%87%E9%A2%98%22%2C%22total_amount%22%3A%220.01%22%2C%22body%22%3A%22%E8%AE%A2%E5%8D%95%E6%8F%8F%E8%BF%B0%22%7D ``` -------------------------------- ### Uploading Files with AlipayFormData Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Shows how to use `AlipayFormData` to prepare a `multipart/form-data` request for file uploads, specifically for the Alipay File Upload API (`/v3/alipay/open/file/upload`). Adds a file and a business code parameter. ```ts 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); ``` -------------------------------- ### CommonJS Require Difference (v3 vs v4) - Alipay SDK Node.js (JavaScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Highlights the change in how the `AlipaySdk` class is imported using `require` in CommonJS modules when upgrading from v3 to v4 of the SDK. V3 directly exports the class, while v4 exports it as a named property. ```JavaScript // v3 是会直接导出到 module.exports 下 const AlipaySdk = require('alipay-sdk'); ``` ```JavaScript // v4 是导出到 exports.AlipaySdk 下 const { AlipaySdk } = require('alipay-sdk'); ``` -------------------------------- ### Verifying Alipay Notification Signatures (V2) - Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Provides an alternative method `checkNotifySignV2` for verifying notification signatures. This version does not decode parameter values by default, which can resolve issues encountered with `checkNotifySign`. It takes a data object containing notification parameters. ```TypeScript const postData = { sign_type: 'RSA2', sign: 'QfTb8tqE1BMhS5qAn.....', gmt_create: '2019-08-15 15:56:22', other_biz_field: '....', }; // true | false const success = sdk.checkNotifySignV2(postData); ``` -------------------------------- ### Verifying Alipay Notification Signatures - Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Shows how to verify the signature of a notification received from the Alipay server using the `checkNotifySign` method. This ensures the notification's authenticity. The method takes a query object containing notification parameters. ```TypeScript // 获取 queryObj,如 ctx.query, router.query // 如服务器未将 queryString 转化为 object,需要手动转化 const queryObj = { sign_type: 'RSA2', sign: 'QfTb8tqE1BMhS5qAn.....', gmt_create: '2019-08-15 15:56:22', other_biz_field: '....', } // true | false const success = sdk.checkNotifySign(queryObj); ``` -------------------------------- ### Decrypting Encrypted Content - Alipay SDK Node.js (TypeScript) Source: https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/README.md Illustrates how to decrypt content, such as an encrypted mobile number obtained from a mini-program, using the `aesDecrypt` method. Requires the AES key to be configured in the SDK instance. ```TypeScript const plainText = alipaySdk.aesDecrypt(getPhoneNumberResponse); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.