### ISV Multi-Merchant Payment Scenarios (C#) Source: https://context7.com/essensoft/paylinks/llms.txt Supports the service provider (ISV)代调用 (dai diao yong - acting on behalf of) mode, enabling the processing of payment requests for multiple merchants. This C# example shows how to handle Alipay and WeChat Pay in a multi-merchant setup. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Payments.Request; using Essensoft.Paylinks.Alipay.Payments.Model; public class MultiMerchantPaymentService { private readonly IAlipayClient _alipayClient; private readonly IWeChatPayClient _wechatPayClient; // 服务商配置 (ISV 自身的配置) private readonly AlipayClientOptions _isvAlipayOptions; private readonly WeChatPayClientOptions _isvWeChatPayOptions; public MultiMerchantPaymentService( IAlipayClient alipayClient, IWeChatPayClient wechatPayClient) { _alipayClient = alipayClient; _wechatPayClient = wechatPayClient; } // 支付宝 - 使用应用授权令牌代调用 public async Task CreateOrderForMerchantAsync(string appAuthToken) { var request = new AlipayTradeCreateRequest(); request.SetBodyModel(new AlipayTradeCreateBodyModel { OutTradeNo = $"ISV_{DateTime.Now:yyyyMMddHHmmss}", TotalAmount = "0.01", Subject = "代调用订单" }); // 传入商户的应用授权令牌 var response = await _alipayClient.ExecuteAsync( request, _isvAlipayOptions, appAuthToken: appAuthToken); } // 微信支付 - 切换商户配置 public async Task CreateOrderForWeChatMerchantAsync( WeChatPayClientOptions merchantOptions) { var request = new WeChatPayTransactionsNativeRequest(); request.SetBodyModel(new WeChatPayTransactionsNativeBodyModel { AppId = merchantOptions.AppId, MchId = merchantOptions.MchId, Description = "子商户订单", OutTradeNo = $"MCH_{DateTime.Now:yyyyMMddHHmmss}", NotifyUrl = "https://your-domain.com/api/notify", Amount = new CommReqAmountInfo { Total = 100 } }); // 使用商户自己的配置 var response = await _wechatPayClient.ExecuteAsync( request, merchantOptions); } } ``` -------------------------------- ### Generate Alipay PC Website Payment Form (C#) Source: https://context7.com/essensoft/paylinks/llms.txt Generates an HTML form for PC website payments, redirecting users to Alipay to complete the transaction. It supports both POST and GET methods for form submission. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Payments.Request; using Essensoft.Paylinks.Alipay.Payments.Model; public async Task CreatePagePayFormAsync( IAlipayClient client, AlipayClientOptions options) { var request = new AlipayTradePagePayRequest(); request.SetNotifyUrl("https://your-domain.com/api/alipay/notify"); request.SetReturnUrl("https://your-domain.com/payment/success"); request.SetBizModel(new AlipayTradePagePayBizModel { OutTradeNo = $"PAGE_{DateTime.Now:yyyyMMddHHmmss}", TotalAmount = "99.99", Subject = "电脑网站支付测试", ProductCode = "FAST_INSTANT_TRADE_PAY", Body = "商品详情描述" }); // 生成支付表单 HTML (POST 方式) var formHtml = await client.PageExecuteAsync(request, options, reqMethod: "POST"); // 或生成跳转 URL (GET 方式) var redirectUrl = await client.PageExecuteAsync(request, options, reqMethod: "GET"); return formHtml; // 前端直接渲染此 HTML 即可自动提交表单跳转支付 } ``` -------------------------------- ### Configure Alipay Client Options Source: https://context7.com/essensoft/paylinks/llms.txt Configures application information, certificates, and keys for Alipay. Supports both the common public key mode and certificate mode. Includes optional fields for sensitive information encryption. ```csharp using Essensoft.Paylinks.Alipay.Client; var alipayOptions = new AlipayClientOptions { // Gateway URL ServerUrl = "https://openapi.alipay.com", // App ID AppId = "2021001234567890", // App Private Key (PKCS#1 format) AppPrivateKey = @"MIIEpAIBAAKCAQEA...", // Alipay Public Key AlipayPublicKey = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A...", // Certificate Mode (Optional) AppCertSN = "your_app_cert_sn", AlipayCertSN = "alipay_cert_sn", AlipayRootCertSN = "alipay_root_cert_sn", // Sensitive Information Encryption (Optional) EncryptType = "AES", EncryptKey = "your_aes_encrypt_key" }; ``` -------------------------------- ### Initiate Alipay Refund with C# Source: https://context7.com/essensoft/paylinks/llms.txt This C# function initiates a refund for a successfully paid Alipay order. It supports full or partial refunds and requires the client, options, merchant order number (outTradeNo), and the refund amount. It returns a string indicating fund change upon success or throws an exception on failure. Dependencies include Essensoft.Paylinks.Alipay.Client and Essensoft.Paylinks.Alipay.Payments. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Payments.Request; using Essensoft.Paylinks.Alipay.Payments.Model; public async Task RefundAlipayOrderAsync( IAlipayClient client, AlipayClientOptions options, string outTradeNo, string refundAmount) { var request = new AlipayTradeRefundRequest(); request.SetBodyModel(new AlipayTradeRefundBodyModel { OutTradeNo = outTradeNo, RefundAmount = refundAmount, // 退款金额,单位元 RefundReason = "用户申请退款", // 部分退款时必填,用于标识一次退款请求 OutRequestNo = $"REFUND_{DateTime.Now:yyyyMMddHHmmss}" }); var response = await client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 退款成功返回资金变化信息 return response.FundChange; // Y-资金变化, N-无资金变化 } throw new Exception($"退款失败: {response.Body}"); } ``` -------------------------------- ### 微信支付 - 订单查询 (C#) Source: https://context7.com/essensoft/paylinks/llms.txt 使用 C# 根据商户订单号查询微信支付订单状态。此功能用于确认支付结果,并返回交易状态。它依赖 Essensoft.Paylinks.WeChatPay SDK。 ```csharp using Essensoft.Paylinks.WeChatPay.Client; using Essensoft.Paylinks.WeChatPay.Payments.Request; using Essensoft.Paylinks.WeChatPay.Payments.Model; public async Task QueryOrderAsync( IWeChatPayClient client, WeChatPayClientOptions options, string outTradeNo) { var request = new WeChatPayQueryByOutTradeNoRequest { OutTradeNo = outTradeNo }; request.SetQueryModel(new WeChatPayQueryByOutTradeNoQueryModel { MchId = options.MchId }); var response = await client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 交易状态: SUCCESS-支付成功, REFUND-转入退款, NOTPAY-未支付, // CLOSED-已关闭, REVOKED-已撤销, USERPAYING-用户支付中, PAYERROR-支付失败 return response.TradeState; } throw new Exception($"查询订单失败: {response.Body}"); } ``` -------------------------------- ### 微信支付 - 申请退款 (C#) Source: https://context7.com/essensoft/paylinks/llms.txt 使用 C# 对已支付的微信订单发起退款申请。支持全额或部分退款,并返回退款状态。它依赖 Essensoft.Paylinks.WeChatPay SDK。 ```csharp using Essensoft.Paylinks.WeChatPay.Client; using Essensoft.Paylinks.WeChatPay.Payments.Request; using Essensoft.Paylinks.WeChatPay.Payments.Model; using Essensoft.Paylinks.WeChatPay.Payments.Domain; public async Task RefundAsync( IWeChatPayClient client, WeChatPayClientOptions options, string outTradeNo, int totalAmount, int refundAmount) { var request = new WeChatPayRefundRequest(); request.SetBodyModel(new WeChatPayRefundBodyModel { OutTradeNo = outTradeNo, OutRefundNo = $"REFUND_{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():N}", Reason = "商品退款", NotifyUrl = "https://your-domain.com/api/wechatpay/refund-notify", Amount = new RefundAmount { Total = totalAmount, // 原订单总金额(分) Refund = refundAmount, // 退款金额(分) Currency = "CNY" } }); var response = await client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 退款状态: SUCCESS-退款成功, CLOSED-退款关闭, // PROCESSING-退款处理中, ABNORMAL-退款异常 return response.Status; } throw new Exception($"退款失败: {response.Body}"); } ``` -------------------------------- ### WeChat Pay - JSAPI/Mini Program Order Creation Source: https://context7.com/essensoft/paylinks/llms.txt Creates an order for JSAPI (Official Account) and Mini Program payment scenarios. Requires the user's OpenID. ```APIDOC ## POST /v3/pay/transactions/jsapi ### Description Creates an order for JSAPI (Official Account) and Mini Program payment scenarios. Requires the user's OpenID. ### Method POST ### Endpoint /v3/pay/transactions/jsapi ### Parameters #### Query Parameters None #### Request Body - **appid** (string) - Required - The unique identifier for your application. - **mchid** (string) - Required - The merchant ID provided by WeChat Pay. - **description** (string) - Required - The description of the transaction. - **out_trade_no** (string) - Required - A unique identifier for the transaction generated by the merchant. - **notify_url** (string) - Required - The URL to which WeChat Pay will send notifications about the transaction status. - **amount** (object) - Required - The amount details for the transaction. - **total** (integer) - Required - The total amount for the transaction in cents. - **currency** (string) - Required - The currency of the transaction (e.g., CNY). - **payer** (object) - Required - Information about the payer. - **openid** (string) - Required - The user's OpenID in the current application. ### Request Example ```json { "appid": "your_app_id", "mchid": "your_merchant_id", "description": "JSAPI支付测试", "out_trade_no": "JSAPI_20231027103000", "notify_url": "https://your-domain.com/api/wechatpay/notify", "amount": { "total": 1, "currency": "CNY" }, "payer": { "openid": "user_openid" } } ``` ### Response #### Success Response (200) - **prepay_id** (string) - The prepay ID used to generate the payment parameters. #### Response Example ```json { "prepay_id": "wx20231027103000abcdef1234567890" } ``` ### Frontend Payment Parameters After obtaining the `prepay_id`, you need to generate frontend payment parameters. These include `appId`, `timeStamp`, `nonceStr`, `package` (formatted as `prepay_id=...`), `signType`, and `paySign`. ### Response Example (Frontend Parameters) ```json { "appId": "your_app_id", "timeStamp": "1698370200", "nonceStr": "random_nonce_string", "package": "prepay_id=wx20231027103000abcdef1234567890", "signType": "RSA", "paySign": "generated_signature" } ``` ``` -------------------------------- ### Configure WeChat Pay Client Options Source: https://context7.com/essensoft/paylinks/llms.txt Sets up the necessary merchant information, certificate, and key parameters for WeChat Pay API requests, including signature generation and response verification. Supports various fields like ServerUrl, AppId, MchId, and APIv3Key. ```csharp using Essensoft.Paylinks.WeChatPay.Client; var weChatPayOptions = new WeChatPayClientOptions { // Gateway URL ServerUrl = "https://api.mch.weixin.qq.com", // App ID (Official Account/Mini Program/APP's AppID) AppId = "wx1234567890abcdef", // Merchant ID MchId = "1234567890", // Merchant Certificate Serial Number MchSerialNo = "ABCDEF1234567890ABCDEF1234567890ABCDEF12", // Merchant Certificate Private Key (PKCS#1 format) MchPrivateKey = @"-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----", // Merchant APIv3 Key (for decrypting notifications) APIv3Key = "your_apiv3_key_32_characters_long", // Optional: WeChat Pay Public Key (for signature verification) WeChatPayPublicKey = @"-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A...\n-----END PUBLIC KEY-----", // Optional: WeChat Pay Public Key ID WeChatPayPublicKeyId = "PUB_KEY_ID_0123456789" }; ``` -------------------------------- ### Create Alipay Unified Order (C#) Source: https://context7.com/essensoft/paylinks/llms.txt Creates an Alipay trade order, suitable for mini-program payments and face-to-face transactions. It requires essential details like order number, amount, subject, and buyer ID. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Payments.Request; using Essensoft.Paylinks.Alipay.Payments.Model; public async Task<(string TradeNo, string OutTradeNo)> CreateAlipayOrderAsync( IAlipayClient client, AlipayClientOptions options, string buyerId) { var request = new AlipayTradeCreateRequest(); request.SetBodyModel(new AlipayTradeCreateBodyModel { OutTradeNo = $"ALIPAY_{DateTime.Now:yyyyMMddHHmmss}", TotalAmount = "0.01", // 金额单位为元,支持两位小数 Subject = "订单标题", BuyerId = buyerId, // 买家支付宝用户ID (2088开头) ProductCode = "FACE_TO_FACE_PAYMENT", NotifyUrl = "https://your-domain.com/api/alipay/notify", // 可选参数 Body = "订单描述信息", TimeoutExpress = "30m" // 订单超时时间 }); var response = await client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return (response.TradeNo, response.OutTradeNo); } throw new Exception($"创建订单失败: {response.Body}"); } ``` -------------------------------- ### Handle Alipay Asynchronous Notifications with C# Source: https://context7.com/essensoft/paylinks/llms.txt This C# controller demonstrates how to handle asynchronous notifications from Alipay. It uses the Essensoft.Paylinks.Alipay.Client and Essensoft.Paylinks.Alipay.Mvc.Extensions to verify signatures and parse notification data. The controller processes different trade statuses like 'TRADE_SUCCESS' and 'TRADE_CLOSED', returning 'success' or 'fail' to Alipay. Dependencies include ASP.NET Core MVC components. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Mvc.Extensions; using Essensoft.Paylinks.Alipay.Payments.Notify; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/alipay")] public class AlipayNotifyController : ControllerBase { private readonly IAlipayNotifyClient _notifyClient; private readonly AlipayClientOptions _options; public AlipayNotifyController( IAlipayNotifyClient notifyClient, AlipayClientOptions options) { _notifyClient = notifyClient; _options = options; } [HttpPost("notify")] public async Task PayNotify() { try { // 获取通知参数 var parameters = await Request.GetAlipayParametersAsync(); // 验签并解析通知 var notify = await _notifyClient.ExecuteAsync( parameters, _options); // 处理支付结果 switch (notify.TradeStatus) { case "TRADE_SUCCESS": case "TRADE_FINISHED": var outTradeNo = notify.OutTradeNo; // 商户订单号 var tradeNo = notify.TradeNo; // 支付宝交易号 var totalAmount = notify.TotalAmount; // 订单金额 var buyerId = notify.BuyerId; // 买家ID // TODO: 更新订单状态 // await _orderService.UpdateOrderPaidAsync(outTradeNo, tradeNo); break; case "TRADE_CLOSED": // 交易关闭处理 break; } // 必须返回 "success" 字符串 return Content("success"); } catch (Exception) { // 返回 "fail" 支付宝会重试 return Content("fail"); } } } ``` -------------------------------- ### 微信支付 - JSAPI/小程序下单 (C#) Source: https://context7.com/essensoft/paylinks/llms.txt 使用 C# 创建 JSAPI/小程序支付订单。此功能需要用户的 OpenID,并返回前端调起支付所需的参数。它依赖 Essensoft.Paylinks.WeChatPay SDK。 ```csharp using Essensoft.Paylinks.WeChatPay.Client; using Essensoft.Paylinks.WeChatPay.Payments.Request; using Essensoft.Paylinks.WeChatPay.Payments.Model; using Essensoft.Paylinks.WeChatPay.Payments.Domain; public async Task CreateJsapiOrderAsync( IWeChatPayClient client, WeChatPayClientOptions options, string openId) { // 1. 预下单获取 prepay_id var prepayRequest = new WeChatPayTransactionsJsapiRequest(); prepayRequest.SetBodyModel(new WeChatPayTransactionsJsapiBodyModel { AppId = options.AppId, MchId = options.MchId, Description = "JSAPI支付测试", OutTradeNo = $"JSAPI_{DateTime.Now:yyyyMMddHHmmss}", NotifyUrl = "https://your-domain.com/api/wechatpay/notify", Amount = new CommReqAmountInfo { Total = 1, // 1分钱 Currency = "CNY" }, Payer = new CommReqPayerInfo { OpenId = openId // 用户在当前应用的OpenID } }); var prepayResponse = await client.ExecuteAsync(prepayRequest, options); if (prepayResponse.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception($"预下单失败: {prepayResponse.Body}"); } // 2. 生成前端调起支付所需参数 var transferRequest = new WeChatPayJsapiTransferPaymentRequest { AppId = options.AppId, Package = $"prepay_id={prepayResponse.PrepayId}" }; // 签名并返回支付参数 var paymentParams = await client.SdkExecuteAsync(transferRequest, options); // 返回给前端用于调起支付 // paymentParams 包含: AppId, TimeStamp, NonceStr, Package, SignType, PaySign return paymentParams; } ``` -------------------------------- ### Configure Dependency Injection for Paylinks in ASP.NET Core Source: https://context7.com/essensoft/paylinks/llms.txt Registers WeChat Pay and Alipay clients within the ASP.NET Core dependency injection container. Supports default and custom timeout configurations, as well as custom HttpClient settings. ```csharp using Essensoft.Paylinks.WeChatPay.Client.Extensions; using Essensoft.Paylinks.Alipay.Client.Extensions; var builder = WebApplication.CreateBuilder(args); // Register WeChat Pay client, default timeout 15 seconds builder.Services.AddWeChatPayClient(); // Custom timeout builder.Services.AddWeChatPayClient(timeout: 30); // Custom HttpClient configuration builder.Services.AddWeChatPayClient(httpClient => { httpClient.Timeout = TimeSpan.FromSeconds(30); httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0"); }); // Register Alipay client builder.Services.AddAlipayClient(); // Custom Alipay HttpClient configuration builder.Services.AddAlipayClient(httpClient => { httpClient.Timeout = TimeSpan.FromSeconds(30); }); var app = builder.Build(); ``` -------------------------------- ### Alipay - Unified Order Creation Source: https://context7.com/essensoft/paylinks/llms.txt Creates an Alipay transaction order, suitable for mini-program payments, face-to-face payments, and other scenarios. ```APIDOC ## POST /api/alipay/order/create ### Description Creates an Alipay transaction order. This endpoint is used for various payment scenarios including mini-programs and in-person payments. ### Method POST ### Endpoint /api/alipay/order/create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buyerId** (string) - Required - The Alipay user ID of the buyer (starts with 2088). ### Request Example ```csharp // Example request body structure (actual implementation may vary) { "buyerId": "2088xxxxxxxxxxxxxx" } ``` ### Response #### Success Response (200) - **tradeNo** (string) - The unique trade number generated by Alipay. - **outTradeNo** (string) - The merchant's order number. #### Response Example ```json { "tradeNo": "2023102721001001001000000000", "outTradeNo": "ALIPAY_20231027105500" } ``` #### Error Handling Throws an exception if order creation fails, including the error details from the Alipay response. ```csharp // Exception details will be logged or returned in the response body. throw new Exception("创建订单失败: [Alipay Response Body]"); ``` ``` -------------------------------- ### Generate Alipay App Payment Parameters (C#) Source: https://context7.com/essensoft/paylinks/llms.txt Generates payment parameters for Alipay app payments, which are used by the mobile SDK to invoke the Alipay client. This facilitates in-app payment flows on mobile devices. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Payments.Request; using Essensoft.Paylinks.Alipay.Payments.Model; public async Task CreateAppPayOrderStringAsync( IAlipayClient client, AlipayClientOptions options) { var request = new AlipayTradeAppPayRequest(); request.SetNotifyUrl("https://your-domain.com/api/alipay/notify"); request.SetBizModel(new AlipayTradeAppPayBizModel { OutTradeNo = $"APP_{DateTime.Now:yyyyMMddHHmmss}", TotalAmount = "0.01", Subject = "APP支付测试商品", ProductCode = "QUICK_MSECURITY_PAY", Body = "商品详细描述", TimeoutExpress = "30m" }); // 生成 APP 支付参数字符串 var orderString = await client.SdkExecuteAsync(request, options); // 将 orderString 返回给 APP 客户端,调用支付宝 SDK 发起支付 return orderString; } ``` -------------------------------- ### Download and Cache WeChat Pay Platform Certificates (C#) Source: https://context7.com/essensoft/paylinks/llms.txt Downloads and caches WeChat Pay platform certificates, essential for verifying WeChat Pay response signatures. This C# code snippet demonstrates how to use the IWeChatPayClient and IWeChatPayPlatformCertificateManagerFactory to fetch, decrypt, and store certificates. ```csharp using Essensoft.Paylinks.WeChatPay.Client; using Essensoft.Paylinks.WeChatPay.Certificates.Request; using Essensoft.Paylinks.WeChatPay.Certificates.Extensions; public async Task DownloadAndCacheCertificatesAsync( IWeChatPayClient client, IWeChatPayPlatformCertificateManagerFactory certificateManagerFactory, WeChatPayClientOptions options) { var request = new WeChatPayCertificatesRequest(); // 首次下载需要关闭验签 request.SetNeedVerify(false); var response = await client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 解密并获取证书列表 var certificates = response.GetCertificates(options.APIv3Key); // 获取证书管理器 var certificateManager = certificateManagerFactory.Create(options.MchId); foreach (var cert in certificates) { // 添加到证书管理器缓存 certificateManager.Add(new WeChatPayPlatformCertificate { SerialNo = cert.SerialNo, PublicKey = cert.PublicKey, EffectiveTime = cert.EffectiveTime, ExpireTime = cert.ExpireTime }); } // 清理过期证书 certificateManager.RemoveUnavailableCertificates(); } } ``` -------------------------------- ### Query Alipay Order Status with C# Source: https://context7.com/essensoft/paylinks/llms.txt This C# function queries the status of an Alipay order using the provided client, options, and the merchant's order number (outTradeNo). It returns the trade status upon success or throws an exception if the query fails. Dependencies include Essensoft.Paylinks.Alipay.Client and Essensoft.Paylinks.Alipay.Payments. ```csharp using Essensoft.Paylinks.Alipay.Client; using Essensoft.Paylinks.Alipay.Payments.Request; using Essensoft.Paylinks.Alipay.Payments.Model; public async Task QueryAlipayOrderAsync( IAlipayClient client, AlipayClientOptions options, string outTradeNo) { var request = new AlipayTradeQueryRequest(); request.SetBodyModel(new AlipayTradeQueryBodyModel { OutTradeNo = outTradeNo // 或使用支付宝交易号 // TradeNo = "2024xxxxxxxxxxxx" }); var response = await client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 交易状态: WAIT_BUYER_PAY-等待付款, TRADE_CLOSED-交易关闭, // TRADE_SUCCESS-支付成功, TRADE_FINISHED-交易完成 return response.TradeStatus; } throw new Exception($"查询订单失败: {response.Body}"); } ``` -------------------------------- ### Alipay - PC Website Payment Source: https://context7.com/essensoft/paylinks/llms.txt Generates an HTML form for PC website payments, redirecting the user to Alipay to complete the payment process. ```APIDOC ## POST /api/alipay/page/pay ### Description Generates an HTML form for PC website payments. Users are redirected to Alipay to finalize the payment. ### Method POST ### Endpoint /api/alipay/page/pay ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are set internally in the SDK) ### Request Example ```csharp // No explicit request body needed for this operation. // The SDK constructs the request based on internal configurations. ``` ### Response #### Success Response (200) - **formHtml** (string) - The generated HTML form that should be rendered by the client to initiate the payment. #### Response Example ```html Alipay Payment
``` ### Notes This endpoint can also generate a redirect URL for GET requests, but the primary use case shown is generating a POST form for direct submission. ``` -------------------------------- ### WeChat Pay - Apply Refund Source: https://context7.com/essensoft/paylinks/llms.txt Applies for a refund for a paid order. Supports full and partial refunds. ```APIDOC ## POST /v3/secapi/pay/refund ### Description Applies for a refund for a paid order. Supports full and partial refunds. ### Method POST ### Endpoint /v3/secapi/pay/refund ### Parameters #### Query Parameters None #### Request Body - **out_trade_no** (string) - Required - The merchant's original order number. - **out_refund_no** (string) - Required - A unique identifier for the refund generated by the merchant. - **reason** (string) - Required - The reason for the refund. - **notify_url** (string) - Optional - The URL to which WeChat Pay will send notifications about the refund status. - **amount** (object) - Required - The refund amount details. - **total** (integer) - Required - The total amount of the original order in cents. - **refund** (integer) - Required - The amount to be refunded in cents. - **currency** (string) - Required - The currency of the transaction (e.g., CNY). ### Request Example ```json { "out_trade_no": "JSAPI_20231027103000", "out_refund_no": "REFUND_20231027103000_guid", "reason": "商品退款", "notify_url": "https://your-domain.com/api/wechatpay/refund-notify", "amount": { "total": 100, "refund": 50, "currency": "CNY" } } ``` ### Response #### Success Response (200) - **status** (string) - The status of the refund. Possible values include: - SUCCESS: Refund successful - CLOSED: Refund closed - PROCESSING: Refund processing - ABNORMAL: Refund abnormal #### Response Example ```json { "status": "SUCCESS" } ``` ``` -------------------------------- ### Create WeChat Pay Native Order Source: https://context7.com/essensoft/paylinks/llms.txt Generates a QR code URL for Native payment, suitable for PC website payments. This C# method uses the WeChatPayClient to send a request with order details like description, amount, and notification URL. ```csharp using Essensoft.Paylinks.WeChatPay.Client; using Essensoft.Paylinks.WeChatPay.Payments.Request; using Essensoft.Paylinks.WeChatPay.Payments.Model; using Essensoft.Paylinks.WeChatPay.Payments.Domain; public class WeChatPayService { private readonly IWeChatPayClient _client; public WeChatPayService(IWeChatPayClient client) { _client = client; } public async Task CreateNativeOrderAsync(WeChatPayClientOptions options) { var request = new WeChatPayTransactionsNativeRequest(); request.SetBodyModel(new WeChatPayTransactionsNativeBodyModel { AppId = options.AppId, MchId = options.MchId, Description = "商品描述", OutTradeNo = $"ORDER_{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():N}", NotifyUrl = "https://your-domain.com/api/wechatpay/notify", Amount = new CommReqAmountInfo { Total = 100, // Amount in cents, 100 = 1 Yuan Currency = "CNY" }, // Optional: Set order expiration time TimeExpire = DateTimeOffset.Now.AddHours(2), // Optional: Attach data Attach = "自定义附加数据" }); var response = await _client.ExecuteAsync(request, options); if (response.StatusCode == System.Net.HttpStatusCode.OK) { // Return QR code URL, frontend can use it to generate QR code return response.CodeUrl; } throw new Exception($"Create order failed: {response.Body}"); } } ``` -------------------------------- ### Handle WeChat Pay Async Notifications (C#) Source: https://context7.com/essensoft/paylinks/llms.txt Processes asynchronous notification callbacks from WeChat Pay. It includes signature verification and decryption of notification content. This is crucial for confirming payment status and updating order information. ```csharp using Essensoft.Paylinks.WeChatPay.Client; using Essensoft.Paylinks.WeChatPay.Core; using Essensoft.Paylinks.WeChatPay.Mvc.Extensions; using Essensoft.Paylinks.WeChatPay.Payments.Notify; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/wechatpay")] public class WeChatPayNotifyController : ControllerBase { private readonly IWeChatPayNotifyClient _notifyClient; private readonly WeChatPayClientOptions _options; public WeChatPayNotifyController( IWeChatPayNotifyClient notifyClient, WeChatPayClientOptions options) { _notifyClient = notifyClient; _options = options; } [HttpPost("notify")] public async Task PayNotify() { try { // 获取请求头和请求体 var headers = await Request.GetWeChatPayHeadersAsync(); var body = await Request.GetWeChatPayBodyAsync(); // 验签并解密通知 var notify = await _notifyClient.ExecuteAsync( headers, body, _options); // 处理支付成功通知 if (notify.TradeState == "SUCCESS") { var outTradeNo = notify.OutTradeNo; // 商户订单号 var transactionId = notify.TransactionId; // 微信支付订单号 var totalAmount = notify.Amount.Total; // 支付金额(分) var openId = notify.Payer.OpenId; // 支付者OpenID // TODO: 更新订单状态,发货等业务逻辑 // await _orderService.UpdateOrderPaidAsync(outTradeNo, transactionId); } // 返回成功响应 return Ok(new { code = "SUCCESS", message = "成功" }); } catch (Exception ex) { // 返回失败响应,微信会重试通知 return Ok(new { code = "FAIL", message = ex.Message }); } } } ``` -------------------------------- ### Alipay - App Payment Source: https://context7.com/essensoft/paylinks/llms.txt Generates payment parameters for Alipay App payments, which are used by the mobile SDK to invoke the Alipay client. ```APIDOC ## POST /api/alipay/app/pay ### Description Generates payment parameters for Alipay App payments. These parameters are used by the mobile SDK to launch the Alipay application for payment. ### Method POST ### Endpoint /api/alipay/app/pay ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are set internally in the SDK) ### Request Example ```csharp // No explicit request body needed for this operation. // The SDK constructs the request based on internal configurations. ``` ### Response #### Success Response (200) - **orderString** (string) - The payment parameters string that should be passed to the Alipay mobile SDK for initiating the payment. #### Response Example ``` alipay_sdk=...&app_id=...&biz_content=...&charset=...&format=...&method=...¬ify_url=...&return_url=...&sign=...&sign_type=...×tamp=...&version=... ``` ### Notes The returned `orderString` should be passed to the Alipay SDK on the mobile application to initiate the payment process. ``` -------------------------------- ### WeChat Pay - Asynchronous Notification Handling Source: https://context7.com/essensoft/paylinks/llms.txt Handles asynchronous notification callbacks from WeChat Pay, including signature verification and decryption of notification content. ```APIDOC ## POST /api/wechatpay/notify ### Description Handles asynchronous notification callbacks from WeChat Pay. It verifies the signature and decrypts the notification content to process payment status updates. ### Method POST ### Endpoint /api/wechatpay/notify ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body The request body contains the notification data sent by WeChat Pay. ### Request Example ```csharp // Request body is automatically handled by the framework. // Headers and body are retrieved using helper methods. ``` ### Response #### Success Response (200) - **code** (string) - Indicates the processing status, 'SUCCESS' for successful handling, 'FAIL' otherwise. - **message** (string) - A message detailing the outcome of the processing. #### Response Example ```json { "code": "SUCCESS", "message": "成功" } ``` #### Error Handling If an exception occurs during processing, a 'FAIL' response is returned with the exception message. WeChat Pay may retry the notification. ```json { "code": "FAIL", "message": "[Error Message]" } ``` ``` -------------------------------- ### WeChat Pay - Order Query Source: https://context7.com/essensoft/paylinks/llms.txt Queries the status of an order using the merchant's order number. Used to confirm payment results. ```APIDOC ## GET /v3/pay/transactions/out-trade-no/{out_trade_no} ### Description Queries the status of an order using the merchant's order number. Used to confirm payment results. ### Method GET ### Endpoint /v3/pay/transactions/out-trade-no/{out_trade_no} ### Parameters #### Path Parameters - **out_trade_no** (string) - Required - The merchant's order number. #### Query Parameters - **mchid** (string) - Required - The merchant ID provided by WeChat Pay. ### Request Example ``` GET /v3/pay/transactions/out-trade-no/JSAPI_20231027103000?mchid=your_merchant_id HTTP/1.1 Host: api.mch.weixin.qq.com ``` ### Response #### Success Response (200) - **trade_state** (string) - The current state of the transaction. Possible values include: - SUCCESS: Payment successful - REFUND: Refunded - NOTPAY: Not paid - CLOSED: Order closed - REVOKED: Order revoked - USERPAYING: User is paying - PAYERROR: Payment failed #### Response Example ```json { "trade_state": "SUCCESS" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.