1. Introduction
In today's digital age, mini-program payment function has become one of the core needs of many applications. Through mini-program payment, users can easily complete shopping, recharge and other operations, greatly improving user experience and business efficiency. As a popular Java development framework, Spring Boot provides powerful support for implementing mini-program payment functions with its simplicity and efficiency. This article will introduce in detail how to implement the payment function of WeChat applets in the Spring Boot project, including key links such as environment construction, interface development, payment process implementation, and payment result notification processing.
2. Preparation
(I) WeChat Pay Merchant Platform Configuration
Register a WeChat Pay Merchant Number: Register a merchant number on the WeChat Pay Merchant Platform (/) to obtain basic information such as merchant number (mch_id), API key (key).
Apply for WeChat Payment Certificate: Download the payment certificate on the merchant platform for signature verification and data encryption.
Configure payment parameters: Configure payment parameters on the merchant platform, including callback address (notify_url), etc.
(II) Spring Boot project construction
Create Spring Boot Project: Quickly create a Spring Boot project through Spring Initializr (/), and select the required dependencies, such as Spring Web, Spring Boot DevTools, etc.
Add WeChat Pay dependencies: Add WeChat Pay related dependencies to the file:
<dependency> <groupId>-apiv3</groupId> <artifactId>wechatpay-java</artifactId> <version>1.0.0</version> </dependency>
(III) Configuration file settings
Configure WeChat payment related parameters in or file:
: your_app_id : your_mch_id : your_api_key : your_notify_url
Implementation of payment function
(I) Unified single interface development
Create payment service class: Create WxPayService class to handle payment-related logic:
@Service public class WxPayService { @Value("${}") private String appId; @Value("${}") private String mchId; @Value("${}") private String key; @Value("${}") private String notifyUrl; public Map<String, String> unifiedOrder(Map<String, String> params) { // Build unified single request parameters Map<String, String> requestParams = new HashMap<>(); ("appid", appId); ("mch_id", mchId); ("nonce_str", ().toString().replace("-", "")); ("body", ("body")); ("out_trade_no", ("out_trade_no")); ("total_fee", ("total_fee")); ("spbill_create_ip", ("spbill_create_ip")); ("notify_url", notifyUrl); ("trade_type", "JSAPI"); ("openid", ("openid")); // sign String sign = (requestParams, key); ("sign", sign); // Initiate a unified single request String xml = (requestParams); String result = ("/pay/unifiedorder", xml); Map<String, String> resultMap = (result); // Return the payment parameters required by the front-end Map<String, String> payParams = new HashMap<>(); ("appId", appId); ("timeStamp", (() / 1000)); ("nonceStr", ().toString().replace("-", "")); ("package", "prepay_prepay_id")); ("signType", "MD5"); ("paySign", (payParams, key)); return payParams; } }
Create a payment controller: Create a WxPayController class to receive payment requests from applets and call a unified single interface:
@RestController @RequestMapping("/wxpay") public class WxPayController { @Autowired private WxPayService wxPayService; @PostMapping("/unifiedOrder") public Map<String, String> unifiedOrder(@RequestBody Map<String, String> params) { return (params); } }
(II) Payment result notification processing
Create payment result notification processing interface: Create WxPayNotifyController class to receive WeChat payment result notifications:
@RestController @RequestMapping("/wxpay") public class WxPayNotifyController { @Autowired private WxPayService wxPayService; @PostMapping("/notify") public String notify(@RequestBody String notifyData) { return (notifyData); } }
Implement payment result processing logic: Implement payment result processing logic in WxPayService:
public String notify(String notifyData) { try { // parse notification data Map<String, String> notifyMap = (notifyData); // Verify the signature if (!(notifyMap, key)) { return "FAIL"; } // Process payment results if ("SUCCESS".equals(("result_code"))) { // Update business logic such as order status return "SUCCESS"; } } catch (Exception e) { (); } return "FAIL"; }
(III) Front-end calls payment interface
In the front-end page of the mini program, call the back-end interface to obtain payment parameters and call the WeChat Pay API to complete the payment:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WeChat Pay Example</title> </head> <body> <h1>WeChat Pay Example</h1> <button >Pay Now</button> <script> ("payButton").addEventListener("click", function() { // Call the backend interface to obtain payment parameters fetch('/wxpay/unifiedOrder', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ({ body: 'Test Payment', out_trade_no: '123456789', total_fee: '1', spbill_create_ip: '127.0.0.1', openid: 'your_openid' }) }) .then(response => ()) .then(payParams => { // Call WeChat Pay API ( 'getBrandWCPayRequest', { "appId": , "timeStamp": , "nonceStr": , "package": , "signType": , "paySign": }, function(res) { if (res.err_msg == "get_brand_wcpay_request:ok") { alert("Payment Success"); } else { alert("Pay failed"); } } ); }); }); </script> </body> </html>
4. Testing and Optimization
(I) Test the payment process
- Simulated payment request: initiate a payment request in the applet, check whether the backend interface can be called correctly and return payment parameters.
- Verification payment result notification: Simulate WeChat payment result notification, check whether the backend can correctly process payment results and update the order status.
(II) Optimization and Security
- Signature verification: Ensure that signatures are strictly verified in the payment result notification processing to prevent forgery notifications.
- Logging: Records the logs for payment requests and notification processing, which facilitates troubleshooting.
- Exception handling: Add exception handling logic to the payment process to ensure that the system can run normally when an error is encountered.
5. Summary
Through the above steps, we have successfully implemented the WeChat applet payment function in the Spring Boot project. From environment construction to interface development, to payment process implementation and payment result notification processing, every step is crucial. In actual development, further optimization and adjustment are needed according to specific business needs. I hope this article can provide developers with a clear implementation idea and reference code to help everyone quickly realize the payment function of mini program.
6. Reference code
Here is the complete reference code:
(one)
@Service public class WxPayService { @Value("${}") private String appId; @Value("${}") private String mchId; @Value("${}") private String key; @Value("${}") private String notifyUrl; public Map<String, String> unifiedOrder(Map<String, String> params) { Map<String, String> requestParams = new HashMap<>(); ("appid", appId); ("mch_id", mchId); ("nonce_str", ().toString().replace("-", "")); ("body", ("body")); ("out_trade_no", ("out_trade_no")); ("total_fee", ("total_fee")); ("spbill_create_ip", ("spbill_create_ip")); ("notify_url", notifyUrl); ("trade_type", "JSAPI"); ("openid", ("openid")); String sign = (requestParams, key); ("sign", sign); String xml = (requestParams); String result = ("/pay/unifiedorder", xml); Map<String, String> resultMap = (result); Map<String, String> payParams = new HashMap<>(); ("appId", appId); ("timeStamp", (() / 1000)); ("nonceStr", ().toString().replace("-", "")); ("package", "prepay_prepay_id")); ("signType", "MD5"); ("paySign", (payParams, key)); return payParams; } public String notify(String notifyData) { try { Map<String, String> notifyMap = (notifyData); if (!(notifyMap, key)) { return "FAIL"; } if ("SUCCESS".equals(("result_code"))) { // Update order status and other business logic return "SUCCESS"; } } catch (Exception e) { (); } return "FAIL"; } }
(two)
@RestController @RequestMapping("/wxpay") public class WxPayController { @Autowired private WxPayService wxPayService; @PostMapping("/unifiedOrder") public Map<String, String> unifiedOrder(@RequestBody Map<String, String> params) { return (params); } }
(three)
@RestController @RequestMapping("/wxpay") public class WxPayNotifyController { @Autowired private WxPayService wxPayService; @PostMapping("/notify") public String notify(@RequestBody String notifyData) { return (notifyData); } }
Through the above code examples and detailed steps, the payment function of WeChat applets can be quickly realized. I hope it can help everyone better understand and apply Spring Boot to implement the mini program payment function.
This is the article about SpringBoot implementing the payment function of WeChat applets. For more related SpringBoot applets, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!