### Create Order and Get Mini Program Payment Parameters Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder and obtaining the parameters needed for a mini-program payment. The result is typically returned to the frontend for initiating the payment. ```java Map jsApiParams = payService.jsApi(order); // 返回给小程序前端 return ResponseEntity.ok(jsApiParams); ``` -------------------------------- ### Create Order and Get App Payment Parameters Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder and then generating the parameters required for app-based payment. These parameters are then passed to the mobile application. ```java Map appParams = payService.app(order); // 将参数传递给APP端进行支付 ``` -------------------------------- ### AliPayConfigStorage Configuration Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md Demonstrates how to instantiate and configure AliPayConfigStorage with essential payment parameters. ```java AliPayConfigStorage config = new AliPayConfigStorage(); config.setAppId("2016091500514025"); config.setKeyPrivate("应用私钥"); config.setKeyPublic("支付宝公钥"); config.setNotifyUrl("https://example.com/alipay/notify"); config.setReturnUrl("https://example.com/alipay/return"); config.setSignType("RSA2"); config.setCharset("UTF-8"); ``` -------------------------------- ### Create Order and Get QR Code String Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder and obtaining the string representation of the QR code content, which might be a URL or other payment-related information. ```java String qrContent = payService.getQrPay(order); ``` -------------------------------- ### Parameter Concatenation Examples Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_签名工具 Examples demonstrating how to use parameterText with different separators and ignore keys. ```java //第一个方式 Map data = new HashMap(); data.put("title", "标题"); data.put("body", "主题"); //这里str的结果是: body=主题&title=标题 String str = parameterText(data); //第二个方式 Map data = new HashMap(); data.put("title", "标题"); data.put("body", "主题"); //这里str的结果是: body=主题|title=标题 String str = parameterText(data, "|"); //第三个方式 Map data = new HashMap(); data.put("title", "标题"); data.put("body", "主题"); data.put("appid", "1233"); //这里str的结果是: body=主题|title=标题 String str = parameterText(data, "|", "appid"); ``` -------------------------------- ### Profit Sharing Request Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/转账与工具服务.md Demonstrates how to initiate a profit-sharing request by setting up the order and receiver details. ```java ProfitSharingOrder sharingOrder = new ProfitSharingOrder(); sharingOrder.setTransactionId("4200001234567890"); sharingOrder.setOutTradeNo("order001"); sharingOrder.setOutOrderNo("share001"); // 分账给商户 ReceiversOrder receiver1 = new ReceiversOrder(); receiver1.setType(ReceiverType.MERCHANT_ID); receiver1.setAccount("1234567890"); // 商户ID receiver1.setAmount(5000); // 50元 receiver1.setDescription("平台分成"); // 分账给个人 ReceiversOrder receiver2 = new ReceiversOrder(); receiver2.setType(ReceiverType.PERSONAL_OPENID); receiver2.setAccount("用户openid"); receiver2.setAmount(5000); // 50元 receiver2.setDescription("用户佣金"); sharingOrder.setReceivers(Arrays.asList(receiver1, receiver2)); Map result = profitSharingService.profitSharing(sharingOrder); ``` -------------------------------- ### Create Payment Order and Get Redirect URL Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder and then generating a redirect URL for initiating a web payment. The returned URL should be used for client-side redirection. ```java PayOrder order = new PayOrder( "iPhone 13", "苹果手机", new BigDecimal("5999"), "order20240616001" ); String payUrl = payService.toPay(order); // 前端进行页面跳转 response.sendRedirect(payUrl); ``` -------------------------------- ### Complete Profit Sharing Request Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/转账与工具服务.md Shows how to complete a profit-sharing operation using the `profitSharingFinish` method with an `AssistOrder`. ```java AssistOrder finishOrder = new AssistOrder(); finishOrder.setOutTradeNo("order001"); Map result = profitSharingService .profitSharingFinish(finishOrder); ``` -------------------------------- ### PayMessageRouter Routing Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Demonstrates how to configure PayMessageRouter to handle different trade statuses like success and failure. ```java PayMessageRouter router = new PayMessageRouter(); // 处理支付成功消息 router.rule(new PayMessageRouterRule() .condition(message -> "TRADE_SUCCESS".equals(message.getTradeStatus())) .handler((message, context) -> { // 处理支付成功 updateOrderStatus(message.getOrderId(), "PAID"); return new PayTextOutMessage("success"); })); // 处理支付失败消息 router.rule(new PayMessageRouterRule() .condition(message -> "TRADE_CLOSED".equals(message.getTradeStatus())) .handler((message, context) -> { // 处理支付失败 updateOrderStatus(message.getOrderId(), "FAILED"); return new PayTextOutMessage("success"); })); ``` -------------------------------- ### Initialize and Set AliPay Configuration Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of initializing AliPayConfigStorage with application ID and private key, then setting it on an AliPayService instance. Supports chained configuration. ```java AliPayConfigStorage configStorage = new AliPayConfigStorage(); configStorage.setAppId("2016091500514025"); configStorage.setKeyPrivate("支付宝应用私钥"); AliPayService payService = new AliPayService(configStorage); payService.setPayConfigStorage(configStorage); ``` -------------------------------- ### Controller for Alipay Callback Handling Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md An example controller method demonstrating the complete process of handling an Alipay callback: parsing, verifying, processing, and sending a response. ```java @PostMapping("/alipay/notify") public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) { try { // 解析回调 NoticeParams params = payService.getNoticeParams( new DefaultNoticeRequest(request) ); // 验证签名 if (!payService.verify(params)) { return; } // 处理回调 PayOutMessage outMessage = payService.payBack( new DefaultNoticeRequest(request) ); // 发送响应 outMessage.send(response); } catch (Exception e) { log.error("处理支付宝回调异常", e); } } ``` -------------------------------- ### PayPal YAML Configuration Source: https://github.com/egzosn/pay-java-parent/wiki/paypal(贝宝)_快速入门 Example YAML configuration for PayPal, including test mode, success/cancel URLs, and client credentials. ```yaml paypal: isTest: true #是否开启沙盒环境测试 success-url: http://localhost:8080/paypal/success #成功后返回的url(使用的是异步通知地址的兼容做法) cancel-url: http://localhost:8080/paypal/cancel #取消付款的回调url client: id: 你的clientId secret: 你的secret ``` -------------------------------- ### Use Payoneer Payment Service Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/其他支付渠道.md Example demonstrating how to use the Payoneer payment service. This involves configuring the storage and creating a PayOrder for processing. ```java PayoneerConfigStorage config = new PayoneerConfigStorage(); config.setAppId("payoneer_app_id"); config.setKeyPrivate("payoneer_api_key"); config.setPartnerId("partner_id"); PayoneerPayService payService = new PayoneerPayService(config); PayOrder order = new PayOrder( "商品", "描述", new BigDecimal("100"), "20240616001", PayoneerTransactionType.PAYMENT ); Map payInfo = payService.orderInfo(order); ``` -------------------------------- ### Pay Service Instance Source: https://github.com/egzosn/pay-java-parent/wiki/支付宝_交易辅助接口 Assumes you have an instance of PayService. Refer to the Quick Start guide for instantiation details. ```APIDOC PayService payService = ...; ``` -------------------------------- ### Perform GET Request with Parameters Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_http请求工具 Executes a GET request using the configured template, specifying the URL, response type, and parameters. ```java //返回一个String类型的结果集 String result = template.getForObject("http://egan.in/pay/{id}/f/{type}", String.class,"1","APP") Map uriVariables = new HashMap(2); uriVariables.put("id", "1"); uriVariables.put("type", "APP"); String result = getForObject("http://egan.in/pay/{id}/f/{type}", String.class, uriVariables); ``` -------------------------------- ### Create UnionPay Payment Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/其他支付渠道.md Example of how to create and initiate a UnionPay payment using the SDK. Requires setting up the configuration and creating a PayOrder object. ```java UnionPayConfigStorage config = new UnionPayConfigStorage(); config.setMerId("999999999999999"); config.setKeyPrivate("银联商户密钥"); config.setNotifyUrl("https://example.com/union/notify"); config.setTest(true); UnionPayService payService = new UnionPayService(config); PayOrder order = new PayOrder( "商品标题", "商品描述", new BigDecimal("100"), "20240616001", UnionTransactionType.CONSUME ); String payUrl = payService.toPay(order); ``` -------------------------------- ### Simplified Payment Callback Setup Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_支付消息回调路由 Configure interceptors and handlers for payment callbacks. The actual business logic is processed within the set PayMessageHandler. ```java PayService service = ....; //增加支付回调消息拦截器 payService.addPayMessageInterceptor(new AliPayMessageInterceptor()); //设置回调消息处理 payService.setPayMessageHandler(spring.getBean(AliPayMessageHandler.class)); ``` -------------------------------- ### LoggingInterceptor Implementation Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md An example implementation of PayMessageInterceptor that logs incoming payment message details. It returns false to indicate that message processing should continue. ```java public class LoggingInterceptor implements PayMessageInterceptor { private static final Logger LOG = LoggerFactory.getLogger(LoggingInterceptor.class); @Override public boolean intercept(PayMessage message, PayService payService) { LOG.info("收到支付消息: orderId={}, tradeNo={}, status={}, amount={}", message.getOrderId(), message.getTradeNo(), message.getTradeStatus(), message.getAmount()); // 不中断处理,继续传递给处理器 return false; } } ``` -------------------------------- ### Initialize Single AliPay Service Configuration Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/configuration.md This example shows how to configure a single AliPay service instance using properties, likely from a configuration file or Spring's property placeholders. It sets essential parameters like app ID, keys, notify URL, and sign type. ```java public PayServiceConfig { private final PayService payService; @Bean public PayService aliPayService() { AliPayConfigStorage config = new AliPayConfigStorage(); config.setAppId("${alipay.appId}"); config.setKeyPrivate("${alipay.keyPrivate}"); config.setKeyPublic("${alipay.keyPublic}"); config.setNotifyUrl("${alipay.notifyUrl}"); config.setSignType("RSA2"); return new AliPayService(config); } } ``` -------------------------------- ### Create Order and Generate QR Code Image Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder and then generating a QR code image. The image can then be written to an output stream, for instance, in an HTTP response. ```java BufferedImage qrImage = payService.genQrPay(order); // 在HTTP响应中输出图片 ImageIO.write(qrImage, "png", response.getOutputStream()); ``` -------------------------------- ### Complete Payment Callback Handling Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md This Java code demonstrates a complete controller for handling asynchronous payment notifications from various providers. It includes parsing, signature verification, idempotency checks, and business logic execution for successful payments. Ensure the necessary PayService and OrderService beans are autowired. ```java @RestController @RequestMapping("/payment") public class PaymentCallbackController { @Autowired private PayService payService; @Autowired private OrderService orderService; /** * 支付宝异步通知 */ @PostMapping("/alipay/notify") public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) { handleNotify(request, response, payService); } /** * 微信异步通知 */ @PostMapping("/wxpay/notify") public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) { handleNotify(request, response, payService); } private void handleNotify(HttpServletRequest request, HttpServletResponse response, PayService payService) { log.info("收到支付回调通知"); try { // 1. 解析回调参数 NoticeRequest noticeRequest = new DefaultNoticeRequest(request); NoticeParams params = payService.getNoticeParams(noticeRequest); // 2. 验证签名 if (!payService.verify(params)) { log.warn("签名验证失败"); response.getWriter().write("fail"); return; } // 3. 获取订单信息 Map body = params.getBody(); String outTradeNo = (String) body.get("out_trade_no"); String tradeNo = (String) body.get("trade_no"); String tradeStatus = (String) body.get("trade_status"); // 4. 幂等性检查 Order order = orderService.getOrder(outTradeNo); if ("PAID".equals(order.getStatus())) { log.info("订单已处理,跳过重复处理: {}", outTradeNo); response.getWriter().write("success"); return; } // 5. 处理业务逻辑 if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) { // 更新订单 order.setStatus("PAID"); order.setTradeNo(tradeNo); order.setPayTime(new Date()); orderService.updateOrder(order); // 触发后续流程 handlePaymentSuccess(order); } // 6. 返回成功响应 PayOutMessage outMessage = payService.getPayOutMessage("0", "success"); outMessage.send(response); } catch (Exception e) { log.error("处理支付回调异常", e); try { response.getWriter().write("fail"); } catch (IOException ex) { log.error("写入响应失败", ex); } } } private void handlePaymentSuccess(Order order) { // 发送邮件通知 sendOrderConfirmationEmail(order); // 更新库存 updateInventory(order); // 发放积分 grantPoints(order); // 触发发货流程 triggerShipment(order); log.info("订单处理完成: {}", order.getOutTradeNo()); } } ``` -------------------------------- ### RateLimitInterceptor Implementation Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md An example implementation of PayMessageInterceptor that enforces rate limiting on message processing. It returns true to interrupt processing if the rate limit is exceeded. ```java public class RateLimitInterceptor implements PayMessageInterceptor { private final RateLimiter rateLimiter = RateLimiter.create(10); // 每秒10个请求 @Override public boolean intercept(PayMessage message, PayService payService) { if (!rateLimiter.tryAcquire()) { LOG.warn("消息处理限流: orderId={}", message.getOrderId()); return true; // 中断处理 } return false; // 继续处理 } } ``` -------------------------------- ### PayOutMessage Implementations Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Provides examples of creating different types of outgoing messages: text, XML, and JSON. ```java // 文本消息 PayTextOutMessage textMessage = new PayTextOutMessage("success"); // XML消息 PayXmlOutMessage xmlMessage = new PayXmlOutMessage("..."); // JSON消息 PayJsonOutMessage jsonMessage = new PayJsonOutMessage("{\"code\": \"0\"}"); ``` -------------------------------- ### Callback Response Construction Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Examples of constructing callback responses for different payment providers like Alipay and WeChat, and integrating them into a controller. ```APIDOC ## Callback Response Construction ### Description Demonstrates how to build and send responses to payment gateways for callbacks, tailored to specific provider requirements. ### Alipay Callback Response ```java // Success response PayOutMessage successMsg = payService.getPayOutMessage("0", "success"); // Or use a convenient method PayOutMessage msg = new PayTextOutMessage("success"); ``` ### WeChat Callback Response ```java // WeChat expects XML format response String xml = "" + "" + "" + ""; PayOutMessage msg = new PayXmlOutMessage(xml); ``` ### Usage in Controller ```java @PostMapping("/alipay/notify") public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) { try { // Parse callback NoticeParams params = payService.getNoticeParams( new DefaultNoticeRequest(request) ); // Verify signature if (!payService.verify(params)) { return; } // Process callback PayOutMessage outMessage = payService.payBack( new DefaultNoticeRequest(request) ); // Send response outMessage.send(response); } catch (Exception e) { log.error("Error processing Alipay callback", e); } } ``` ``` -------------------------------- ### Perform Micro Payment with Auth Code Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder, setting the authorization code (e.g., from a scanned barcode), and then executing a micro payment. The result contains the payment outcome. ```java PayOrder order = new PayOrder("商品", "描述", new BigDecimal("100"), "out001"); order.setAuthCode("285110098965321"); // 扫描的条码 Map result = payService.microPay(order); ``` -------------------------------- ### Getting Callback Parameters Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Demonstrates how to obtain NoticeParams from a NoticeRequest and extract specific data like trade number and status from the body, or query parameters. ```java NoticeRequest request = new DefaultNoticeRequest(httpRequest); NoticeParams params = payService.getNoticeParams(request); // 获取支付宝回调数据 Map body = params.getBody(); String tradeNo = (String) body.get("trade_no"); String tradeStatus = (String) body.get("trade_status"); // 获取查询参数 String queryParam = params.getParameter("param_name"); ``` -------------------------------- ### Configure HTTP Connection Timeout Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of setting a custom connection timeout for HTTP requests using HttpConfigStorage and applying it to the pay service. ```java HttpConfigStorage httpConfig = new HttpConfigStorage(); httpConfig.setConnectionTimeout(5000); payService.setRequestTemplateConfigStorage(httpConfig); ``` -------------------------------- ### Create Payment Order Details Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of creating a PayOrder object with details like title, description, price, and a unique merchant order ID, then generating the order information map. ```java PayOrder order = new PayOrder( "商品标题", // 商品名称 "商品描述", // 商品描述 new BigDecimal("10"), // 价格 "20240616001" // 商户订单号 ); Map orderInfo = payService.orderInfo(order); ``` -------------------------------- ### Custom PayMessageHandler Implementation Example Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Provides a concrete implementation of PayMessageHandler to process payment success events, update order status, and trigger subsequent business logic. Requires an OrderService dependency. ```java public class CustomPayMessageHandler implements PayMessageHandler { private OrderService orderService; @Override public PayOutMessage handle(PayMessage message, Map context) { String orderId = message.getOrderId(); String tradeStatus = message.getTradeStatus(); BigDecimal amount = message.getAmount(); // 查询订单 Order order = orderService.getOrder(orderId); if ("TRADE_SUCCESS".equals(tradeStatus)) { // 更新订单状态 order.setStatus("PAID"); order.setPayTime(message.getPaymentTime()); orderService.updateOrder(order); // 触发后续业务逻辑 handlePaymentSuccess(order, amount); } // 返回成功响应 return PayOutMessage.success(); } private void handlePaymentSuccess(Order order, BigDecimal amount) { // 发送订单确认邮件 // 触发发货流程 // 更新用户积分 // ... } } ``` -------------------------------- ### Retrieve and Access AliPay App ID Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Example of getting the pay service's configuration and then accessing the application ID from the retrieved storage object. ```java AliPayConfigStorage config = payService.getPayConfigStorage(); String appId = config.getAppId(); ``` -------------------------------- ### WxPayService V2 Constructor Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/微信支付服务.md Illustrates how to instantiate WxPayService for V2, accepting either just the configuration storage or both configuration and HTTP client storage. ```java public class WxPayService extends BasePayService implements TransferService { public WxPayService(WxPayConfigStorage payConfigStorage) public WxPayService(WxPayConfigStorage payConfigStorage, HttpConfigStorage configStorage) } ``` ```java WxPayConfigStorage config = new WxPayConfigStorage(); // ... 配置参数 WxPayService payService = new WxPayService(config); ``` -------------------------------- ### HttpRequestTemplate GET Request with URI Variables (Map) Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_http请求工具 Performs a GET request with URI variables provided as a Map. Useful for dynamic URL construction. ```java /** * get 请求 * @param uri 请求地址 * @param responseType 响应类型 * @param uriVariables 用于匹配表达式 * @param 响应类型 * @return 类型对象 * * Map uriVariables = new HashMap();
* * uriVariables.put("id", "1");
* * uriVariables.put("type", "APP");
* * getForObject("http://egan.in/pay/{id}/f/{type}", String.class, uriVariables)
*
*/ public T getForObject(String uri, Class responseType, Map uriVariables); ``` -------------------------------- ### HttpRequestTemplate GET Request with URI Variables (Object Array) Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_http请求工具 Performs a GET request with URI variables provided as an Object array. A simpler alternative when variables are in order. ```java /** * get 请求 * @param uri 请求地址 * @param responseType 响应类型 * @param uriVariables 用于匹配表达式 * @param 响应类型 * @return 类型对象 * * * getForObject("http://egan.in/pay/{id}/f/{type}", String.class, "1", "APP") * */ public T getForObject(String uri, Class responseType, Object... uriVariables); ``` -------------------------------- ### AliPayService Constructor 1: With PayConfigStorage Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md Instantiates AliPayService using only an AliPayConfigStorage object. ```APIDOC ## AliPayService(AliPayConfigStorage payConfigStorage) ### Description Constructs an AliPayService instance with the provided Alipay configuration storage. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **payConfigStorage** (AliPayConfigStorage) - Required - The Alipay configuration object. ### Request Example ```java AliPayConfigStorage config = new AliPayConfigStorage(); // ... configure parameters AliPayService payService = new AliPayService(config); ``` ### Response None (Constructor) ``` -------------------------------- ### Load AliPay Configuration from Properties File Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/configuration.md This utility method demonstrates loading AliPay configuration details from a specified properties file. It uses Java's `Properties` class to read key-value pairs and populate an `AliPayConfigStorage` object. ```java public class ConfigLoader { public static AliPayConfigStorage loadAliPayConfig(String configPath) throws IOException { Properties props = new Properties(); props.load(new FileInputStream(configPath)); AliPayConfigStorage config = new AliPayConfigStorage(); config.setAppId(props.getProperty("appId")); config.setKeyPrivate(props.getProperty("keyPrivate")); config.setKeyPublic(props.getProperty("keyPublic")); config.setNotifyUrl(props.getProperty("notifyUrl")); return config; } } ``` -------------------------------- ### Get HTTP Request Template Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Retrieves the HTTP request template object, which can be used for making custom HTTP calls. ```java HttpRequestTemplate getHttpRequestTemplate(); ``` -------------------------------- ### 微信支付V3服务类 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/微信支付服务.md 定义了微信支付V3的服务类WxPayService,它继承自BasePayService并实现了PayService接口。提供了带配置存储和HTTP配置存储的构造函数。 ```java public class WxPayService extends BasePayService implements PayService { public WxPayService(WxPayConfigStorage payConfigStorage) public WxPayService(WxPayConfigStorage payConfigStorage, HttpConfigStorage configStorage) } ``` -------------------------------- ### 创建扫码支付订单 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md 使用AliPayService创建扫码支付订单,可选择生成二维码图片或获取二维码链接。 ```java PayOrder order = new PayOrder( "商品", "描述", new BigDecimal("100"), "order001" ); // 生成二维码图片 BufferedImage qrImage = payService.genQrPay(order); // 或获取二维码链接 String qrUrl = payService.getQrPay(order); ``` -------------------------------- ### Get Pay Configuration Storage Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Retrieves the currently configured payment configuration storage object. Useful for inspecting or reusing existing configurations. ```java PC getPayConfigStorage(); ``` -------------------------------- ### Initialize HttpRequestTemplate with HttpConfigStorage Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_http请求工具 Creates an HttpRequestTemplate with custom HTTP configurations including proxy and SSL settings. ```java //http代理SSL配置信息 HttpConfigStorage configStorage = new HttpConfigStorage(); /* 网路代理配置 根据需求进行设置**/ //http代理地址 httpConfigStorage.setHttpProxyHost("代理地址"); //代理端口 httpConfigStorage.setHttpProxyPort(代理端口); //代理用户名 httpConfigStorage.setHttpProxyUsername("user"); //代理密码 httpConfigStorage.setHttpProxyPassword("password"); /* 网路代理配置 根据需求进行设置**/ /* 网络请求ssl证书 根据需求进行设置**/ //设置ssl证书路径 // httpConfigStorage.setKeystore(WxPayController.class.getResourceAsStream("/证书文件")); httpConfigStorage.setKeystore("证书绝对路径"); //设置ssl证书对应的密码 httpConfigStorage.setStorePassword("证书对应的密码"); //设置ssl证书对应的存储方式,这里默认为文件地址 httpConfigStorage.setCertStoreType(CertStoreType.PATH); /* /网络请求ssl证书**/ //创建一个带http代理、SSL证书支持请求模板 HttpRequestTemplate template = new HttpRequestTemplate(configStorage); ``` -------------------------------- ### AliPayService Constructor 2: With PayConfigStorage and HttpConfigStorage Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md Instantiates AliPayService using both AliPayConfigStorage and HttpConfigStorage objects. ```APIDOC ## AliPayService(AliPayConfigStorage payConfigStorage, HttpConfigStorage configStorage) ### Description Constructs an AliPayService instance with the provided Alipay configuration storage and HTTP request configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **payConfigStorage** (AliPayConfigStorage) - Required - The Alipay configuration. - **configStorage** (HttpConfigStorage) - Required - HTTP request configuration (proxy, timeout, etc.). ### Request Example ```java AliPayConfigStorage aliConfig = new AliPayConfigStorage(); // ... configure Alipay HttpConfigStorage httpConfig = new HttpConfigStorage(); httpConfig.setConnectionTimeout(5000); httpConfig.setReadTimeout(10000); AliPayService payService = new AliPayService(aliConfig, httpConfig); ``` ### Response None (Constructor) ``` -------------------------------- ### 处理支付宝回调并返回响应 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md 使用AliPayService处理支付宝回调,并根据回调结果生成响应消息。此方法用于向支付宝返回处理结果。 ```java @PostMapping("/payback") public void payback(HttpServletRequest request, HttpServletResponse response) { PayOutMessage outMessage = payService.payBack(new DefaultNoticeRequest(request)); outMessage.send(response); } ``` -------------------------------- ### PayPal Order Query and Refund Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/其他支付渠道.md Provides examples for querying the status of a PayPal order using its transaction number and initiating a refund for a specified amount. ```java // 查询订单 AssistOrder queryOrder = new AssistOrder(); queryOrder.setOutTradeNo("ORDER20240616001"); Map result = payService.query(queryOrder); // 申请退款 RefundOrder refundOrder = new RefundOrder(); refundOrder.setOutTradeNo("ORDER20240616001"); refundOrder.setRefundAmount(new BigDecimal("100")); RefundResult refundResult = payService.refund(refundOrder); ``` -------------------------------- ### AliPayService Constructor with Config Storage and HTTP Config Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md Initializes AliPayService with both Alipay-specific configuration and custom HTTP request settings, such as connection and read timeouts. ```java AliPayConfigStorage aliConfig = new AliPayConfigStorage(); // ... 配置支付宝 HttpConfigStorage httpConfig = new HttpConfigStorage(); httpConfig.setConnectionTimeout(5000); httpConfig.setReadTimeout(10000); AliPayService payService = new AliPayService(aliConfig, httpConfig); ``` -------------------------------- ### 微信支付V3配置示例 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/微信支付服务.md 展示了如何实例化并配置WxPayConfigStorage对象,用于微信支付V3的初始化。需要设置AppID、商户ID、私钥、API密钥、证书序列号和回调通知URL。 ```java WxPayConfigStorage v3Config = new WxPayConfigStorage(); v3Config.setAppId("wx1234567890abcdef"); v3Config.setMchId("1234567890"); v3Config.setKeyPrivate("商户私钥"); v3Config.setApiSecret("API密钥"); v3Config.setSerialNo("证书序列号"); v3Config.setNotifyUrl("https://example.com/wx/v3/notify"); ``` -------------------------------- ### UnionPay Payment Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/其他支付渠道.md This section details how to create a payment using the UnionPay service. It includes configuration setup, order creation, and generating the payment URL. ```APIDOC ## UnionPay Payment Creation ### Description This API allows you to initiate a payment through UnionPay. You need to configure the `UnionPayConfigStorage` with your merchant details and then create a `PayOrder` object to generate the payment URL. ### Method `UnionPayService.toPay(PayOrder order)` ### Parameters #### Request Body (PayOrder) - **title** (string) - Required - The title of the product. - **description** (string) - Required - The description of the product. - **price** (BigDecimal) - Required - The amount to be paid. - **orderId** (string) - Required - The unique identifier for the order. - **transactionType** (UnionTransactionType) - Required - The type of transaction, e.g., `UnionTransactionType.CONSUME`. ### Request Example ```java UnionPayConfigStorage config = new UnionPayConfigStorage(); config.setMerId("999999999999999"); config.setKeyPrivate("银联商户密钥"); config.setNotifyUrl("https://example.com/union/notify"); config.setTest(true); UnionPayService payService = new UnionPayService(config); PayOrder order = new PayOrder( "商品标题", "商品描述", new BigDecimal("100"), "20240616001", UnionTransactionType.CONSUME ); String payUrl = payService.toPay(order); ``` ### Response #### Success Response - **payUrl** (string) - The URL to complete the payment. ``` -------------------------------- ### Initialize HttpRequestTemplate (Default) Source: https://github.com/egzosn/pay-java-parent/wiki/公共模块_http请求工具 Creates a default HttpRequestTemplate instance without any custom HTTP configurations. ```java HttpRequestTemplate template = new HttpRequestTemplate(); ``` -------------------------------- ### Configure WxPayConfigStorage and Generate QR Code Source: https://github.com/egzosn/pay-java-parent/wiki/微信_快速入门 This snippet shows how to set up WxPayConfigStorage and generate a QR code for native payments. Ensure all required parameters like mchId, appid, and secretKey are correctly configured. ```java WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage(); wxPayConfigStorage.setMchId("合作者id(商户号)"); wxPayConfigStorage.setAppid("应用id"); wxPayConfigStorage.setKeyPublic("转账公钥,转账时必填"); wxPayConfigStorage.setSecretKey("密钥"); wxPayConfigStorage.setNotifyUrl("异步回调地址"); wxPayConfigStorage.setReturnUrl("同步回调地址"); wxPayConfigStorage.setSignType("签名方式"); wxPayConfigStorage.setInputCharset("utf-8"); //https证书设置,退款必须 方式一 /* HttpConfigStorage httpConfigStorage = new HttpConfigStorage(); httpConfigStorage.setKeystore("证书信息串"); httpConfigStorage.setStorePassword("证书密码"); //设置ssl证书对应的存储方式,这里默认为文件地址 httpConfigStorage.setCertStoreType(CertStoreType.PATH); PayService service = new WxPayService(wxPayConfigStorage, httpConfigStorage); */ PayService service = new WxPayService(wxPayConfigStorage); PayOrder payOrder = new PayOrder("订单title", "摘要", new BigDecimal(0.01) , UUID.randomUUID().toString().replace("-", "")); /*-----------扫码付------------------- payOrder.setTransactionType(WxTransactionType.NATIVE); //获取扫码付的二维码 BufferedImage image = service.genQrPay(payOrder); /*-----------/扫码付------------------- ``` -------------------------------- ### Get QR Code String for Payment Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付服务接口.md Retrieves the string content of a QR code, such as a payment URL, which can be used to generate a QR code or for other display purposes. ```java String getQrPay(O order); ``` -------------------------------- ### Create PayPal V1 Payment Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/其他支付渠道.md Demonstrates how to create a PayPal V1 payment order and obtain a payment URL. Ensure the PayPalConfigStorage is correctly configured with sandbox or live mode. ```java PayPalConfigStorage config = new PayPalConfigStorage(); config.setAppId("paypal_app_id"); config.setKeyPrivate("paypal_secret"); config.setMode("sandbox"); // 或 live PayPalPayService payService = new PayPalPayService(config); PayOrder order = new PayOrder( "iPhone 13", "Apple iPhone", new BigDecimal("599.99"), "ORDER20240616001", PayPalTransactionType.SALE ); // 获取支付链接 String payUrl = payService.toPay(order); response.sendRedirect(payUrl); ``` -------------------------------- ### PayOutMessage Interface Definition Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Defines the contract for outgoing messages sent back to the payment platform, including methods to send the response and get message content. ```java public interface PayOutMessage { /** * 发送响应消息给支付平台 */ void send(HttpServletResponse response) throws IOException; /** * 获取消息内容 */ String getMessage(); } ``` -------------------------------- ### HttpRequestTemplate Methods Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Provides methods for sending various HTTP requests (GET, POST, PUT, DELETE) and uploading files. Requires an HttpConfigStorage instance for configuration. ```java public class HttpRequestTemplate { // 构造方法 public HttpRequestTemplate(HttpConfigStorage configStorage) // GET 请求 public ResponseEntity get(String url, Map headers) public ResponseEntity get(String url) // POST 请求 public ResponseEntity post(String url, String entity, Map headers) public ResponseEntity postJson(String url, String jsonData) public ResponseEntity postForm(String url, Map formData) // PUT 请求 public ResponseEntity put(String url, String entity) // DELETE 请求 public ResponseEntity delete(String url) // 上传文件 public ResponseEntity upload(String url, String fileFieldName, File file) } ``` -------------------------------- ### 验证支付宝回调签名 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md 在接收支付宝回调时,使用AliPayService验证回调参数的签名。验证失败则直接返回。 ```java @PostMapping("/notify") public void aliPayNotify(HttpServletRequest request) { // 解析回调参数 DefaultNoticeRequest noticeRequest = new DefaultNoticeRequest(request); NoticeParams noticeParams = payService.getNoticeParams(noticeRequest); // 验证签名 if (!payService.verify(noticeParams)) { return; // 签名验证失败 } // 获取回调信息 Map body = noticeParams.getBody(); String tradeNo = (String) body.get("trade_no"); String outTradeNo = (String) body.get("out_trade_no"); String tradeStatus = (String) body.get("trade_status"); if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) { // 订单已支付,更新业务系统 } } ``` -------------------------------- ### Send PayPal Payment Message Source: https://github.com/egzosn/pay-java-parent/wiki/paypal_支付回调消息回复 This snippet demonstrates how to create a PayOrder object and send it to PayPal for processing. It utilizes the paypalService to get order information and build a payment request. ```java PayOrder payOrder = new PayOrder("subject say something", "Order payment", new BigDecimal(4), StringUnits.getUUID(), PayPalTransactionType.sale); payOrder.setCurType(DefaultCurType.USD); // orderInfo函数是做一个给paypal发送预订单的操作 具体逻辑请看orderInfo函数源码 Map orderInfo = paypalService.orderInfo(payOrder); // buildRequest校验请求是否正确,具体逻辑请看buildRequest函数,返回的是一个发起支付的url。 String result=paypalService.buildRequest(orderInfo, MethodType.POST); return result; ``` -------------------------------- ### Load AliPay Configuration from Environment Variables Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/configuration.md This snippet demonstrates how to load AliPay configuration properties directly from environment variables. Ensure the environment variables are set before running the application. ```java AliPayConfigStorage config = new AliPayConfigStorage(); config.setAppId(System.getenv("ALI_PAY_APP_ID")); config.setKeyPrivate(System.getenv("ALI_PAY_KEY_PRIVATE")); config.setKeyPublic(System.getenv("ALI_PAY_KEY_PUBLIC")); ``` -------------------------------- ### 创建APP支付订单 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md 使用AliPayService创建APP支付订单并获取支付参数。返回的参数可用于APP端发起支付。 ```java PayOrder order = new PayOrder( "商品", "描述", new BigDecimal("100"), "order001", AliTransactionType.APP_PAY ); // 获取APP支付参数 Map appParams = payService.app(order); // 返回给APP端 ``` -------------------------------- ### DefaultNoticeRequest Initialization Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md Shows how to create a DefaultNoticeRequest instance from an HttpServletRequest. ```java // 从 HttpServletRequest 创建 HttpServletRequest request = ...; NoticeRequest noticeRequest = new DefaultNoticeRequest(request); ``` -------------------------------- ### Configure Alipay and Generate QR Code Source: https://github.com/egzosn/pay-java-parent/wiki/支付宝_快速入门 This snippet demonstrates how to set up Alipay configuration and generate a QR code for sweep payments. Ensure all configuration parameters are correctly set. ```java AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage(); aliPayConfigStorage.setPid("合作者id"); aliPayConfigStorage.setAppId("应用id"); aliPayConfigStorage.setPublicKey("支付宝公钥"); aliPayConfigStorage.setKeyPrivate("应用私钥"); aliPayConfigStorage.setNotifyUrl("异步回调地址"); aliPayConfigStorage.setReturnUrl("同步回调地址"); aliPayConfigStorage.setSignType("签名方式"); aliPayConfigStorage.setSeller("收款账号"); aliPayConfigStorage.setInputCharset("utf-8"); //是否为测试账号,沙箱环境 aliPayConfigStorage.setTest(true); PayService service = new AliPayService(aliPayConfigStorage); PayOrder payOrder = new PayOrder("订单title", "摘要", new BigDecimal(0.01) , UUID.randomUUID().toString().replace("-", "")); /*-----------扫码付------------------- *//* payOrder.setTransactionType(AliTransactionType.SWEEPPAY); //获取扫码付的二维码 BufferedImage image = service.genQrPay(payOrder); /*-----------/扫码付------------------- *//* ``` -------------------------------- ### HttpRequestTemplate Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/HTTP和消息处理.md A utility class for sending HTTP requests, supporting various methods like GET, POST, PUT, and DELETE. It allows for custom configurations including headers, request bodies, and file uploads. ```APIDOC ## HttpRequestTemplate (HTTP Request Tool) ### Description Provides a utility for sending HTTP requests with support for various methods and configurations. ### Methods - **HttpRequestTemplate(HttpConfigStorage configStorage)**: Constructor to initialize the template with specific HTTP configurations. - **ResponseEntity get(String url, Map headers)**: Sends an HTTP GET request with specified headers. - **ResponseEntity get(String url)**: Sends a simple HTTP GET request. - **ResponseEntity post(String url, String entity, Map headers)**: Sends an HTTP POST request with a request body and headers. - **ResponseEntity postJson(String url, String jsonData)**: Sends an HTTP POST request with JSON data. - **ResponseEntity postForm(String url, Map formData)**: Sends an HTTP POST request with form data. - **ResponseEntity put(String url, String entity)**: Sends an HTTP PUT request with a request body. - **ResponseEntity delete(String url)**: Sends an HTTP DELETE request. - **ResponseEntity upload(String url, String fileFieldName, File file)**: Uploads a file using an HTTP POST request. ``` -------------------------------- ### 创建网页支付订单 Source: https://github.com/egzosn/pay-java-parent/blob/develop/_autodocs/api-reference/支付宝支付服务.md 使用AliPayService创建网页支付订单并获取支付链接。需要配置AliPayService实例和PayOrder对象。 ```java AliPayService payService = new AliPayService(config); PayOrder order = new PayOrder( "iPhone 13", // 商品标题 "苹果手机", // 商品描述 new BigDecimal("5999"), // 金额 "20240616001", // 商户订单号 AliTransactionType.PAGE_PAY // 交易类型 ); // 获取支付链接 String payUrl = payService.toPay(order); response.sendRedirect(payUrl); ```