1. Specific business processes
1. User order
- Front-end operation:
- Users select products in the application, fill in order information (such as address, contact information, etc.), and click the "Order" button.
- The front-end sends order information (product ID, quantity, price, etc.) to the back-end.
- Backend processing:
- After receiving the order request, a unique order number (`out_trade_no`) is generated.
- Store order information in the database and set the order status to "Please pay".
2. Backend create orders
- Build request parameters:
- Use merchant number, application ID, random string, order description, merchant order number, amount (unit: segment), IP address, etc. to construct request data in XML format.
- Send a request:
- Use the HTTP POST method to send requested data to WeChat's unified single API (`/pay/unifiedorder`).
- Processing response:
- Receive the response data (XML format) returned by WeChat and parse the response content.
- Check the returned `return_code` and `result_code` to ensure the request is successful.
- Get `prepay_id` and generate payment signatures and other information based on it.
3. Return payment information
- Return to the front end:
- Encapsulate `prepay_id` and other necessary parameters (such as timestamps, random strings, signatures, etc.) into JSON responses and return to the front end.
- Front-end payment:
- The front-end uses the WeChat Pay SDK to call the payment interface to start the payment process.
- After the user confirms the payment, the WeChat client processes the payment.
4. User confirms payment
- User behavior:
- Users view payment information on WeChat and make payment after confirmation.
- Payment results:
- WeChat processes payment requests and notifies your server asynchronously after completion.
5. WeChat payment callback
- Callback URL configuration:
- Configure your callback URL (such as `/wechat/notify`) on the WeChat merchant platform.
- Process callback requests:
- Receive a POST request from WeChat and read the XML data in the request body.
- Verify signature:
- Extract the signature field in the callback data, use the same parameters to generate a new signature, and compare it with the returned signature to ensure the integrity and validity of the data.
- Update order status:
- Update order status in the database based on `result_code` in the callback data. If the payment is successful, modify the order status to "Paid" and perform corresponding business processing (such as delivery).
- Return processing results:
- Return the processing result to WeChat, usually `<xml><return_code>SUCCESS</return_code></xml>`.
6. Return the processing result
- Response to WeChat:
- Ensure the response format is correct and avoid WeChat resending notifications due to inability to parse.
7. Order status query (optional)
- Query order status:
- Within a period of time after the user pays, WeChat's order query API (`/pay/orderquery`) can be called to confirm the status of the order.
- Processing results:
- Update local order status based on query results to ensure data consistency.
8. Order completion
- Follow-up processing:
- Once the order is paid successfully and shipped, follow-up operations can be carried out according to business needs, such as sending confirmation emails, updating inventory, etc.
2. Specific code implementation
1. Merchant parameter configuration
existThe relevant parameters for configuring WeChat payment:
# WeChat Payment Configuration=your_app_id =your_mch_id =your_api_key =/wechat/notify
2. Create a Spring Boot project
Make sure your project introduces the necessary dependencies. existAdd the following to:
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>xstream</artifactId> <version>1.4.18</version> </dependency>
3. Create WeChat payment service
Create a service classWeChatPayService
, used to handle order creation and signature operations.
import ; import ; import ; import ; import ; import ; import ; import ; import ; @Service public class WeChatPayService { @Value("${}") private String appId; @Value("${}") private String mchId; @Value("${}") private String apiKey; @Value("${}") private String notifyUrl; private static final String UNIFIED_ORDER_URL = "/pay/unifiedorder"; public String createOrder(String orderNo, double amount) throws Exception { String nonceStr = (()); String xmlData = "<xml>" + "<appid>" + appId + "</appid>" + "<mch_id>" + mchId + "</mch_id>" + "<nonce_str>" + nonceStr + "</nonce_str>" + "<body>Product Description</body>" + "<out_trade_no>" + orderNo + "</out_trade_no>" + "<total_fee>" + (int) (amount * 100) + "</total_fee>" + "<spbill_create_ip>127.0.0.1</spbill_create_ip>" + "<notify_url>" + notifyUrl + "</notify_url>" + "<trade_type>APP</trade_type>" + "</xml>"; // Generate signature and add to request data String sign = (xmlData, apiKey); xmlData = ("</xml>", "<sign>" + sign + "</sign></xml>"); try (CloseableHttpClient client = ()) { HttpPost post = new HttpPost(UNIFIED_ORDER_URL); (new StringEntity(xmlData, "UTF-8")); ("Content-Type", "text/xml"); String response = ((post).getEntity(), "UTF-8"); return response; // parse and return the required information } } }
4. Create a WeChat Payment Controller
Create a controllerWeChatPayController
, handles the user's order request (@PostMapping("/createOrder")) and callback @PostMapping("/notify").
import ; import .*; import ; @RestController @RequestMapping("/wechat") public class WeChatPayController { @Autowired private WeChatPayService weChatPayService; @PostMapping("/createOrder") public String createOrder(@RequestParam String orderNo, @RequestParam double amount) { try { return (orderNo, amount); } catch (Exception e) { (); return "Error creating order"; } } @PostMapping("/notify") public String handleCallback(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(()))) { String line; while ((line = ()) != null) { (line); } } catch (IOException e) { (); } String xmlData = (); Map<String, String> data = (xmlData); // parse XML data // Verify the signature String sign = ("sign"); if ((xmlData, apiKey).equals(sign)) { // Process business logic, such as updating order status String resultCode = ("result_code"); if ("SUCCESS".equals(resultCode)) { String orderNo = ("out_trade_no"); // Update order status to paid // updateOrderStatus(orderNo, "PAID"); } return "<xml><return_code>SUCCESS</return_code></xml>"; } else { return "<xml><return_code>FAIL</return_code></xml>"; } } }
5. Signature and XML processing tool classes
Create a tool classWeChatPayUtil
, responsible for signature and XML parsing.
import ; import ; import ; import ; import ; public class WeChatPayUtil { public static String generateSign(String xmlData, String apiKey) { // Convert XML to Map Map<String, String> data = parseXml(xmlData); TreeMap<String, String> sortedMap = new TreeMap<>(data); StringBuilder stringBuilder = new StringBuilder(); for (<String, String> entry : ()) { if (!().equals("sign") && () != null) { (()).append("=").append(()).append("&"); } } ("key=").append(apiKey); return md5(()).toUpperCase(); } public static String md5(String input) { try { MessageDigest md = ("MD5"); byte[] digest = (()); StringBuilder hexString = new StringBuilder(); for (byte b : digest) { String hex = (0xFF & b); if (() == 1) ('0'); (hex); } return (); } catch (Exception e) { throw new RuntimeException(e); } } public static Map<String, String> parseXml(String xml) { // Use XStream to parse XML XStream xStream = new XStream(); ("xml", ); return (Map<String, String>) (xml); } }
3. Parameter configuration and acquisition
1. Configuration steps of callback function
-
Configure callback address on WeChat merchant platform:
- Log in to the WeChat merchant platform.
- Find the "Account Settings" or "API Security" options.
- Fill in your callback address in the "Payment Results Notification URL" (such as
/wechat/notify
)。
2. Merchant parameter acquisition
Merchant parameters mainly include relevant information about WeChat payment, which can be obtained on the WeChat merchant platform.
Merchant parameters
- appId: Public account ID, provided by WeChat Open Platform or WeChat Pay Merchant Platform.
- mchId: Merchant number, provided by WeChat Pay Merchant Platform.
- apiKey: API key, set on the WeChat payment merchant platform, used for signature requests.
- notifyUrl: The payment result notification address, that is, after WeChat payment is successful, the WeChat server will notify the address asynchronously.
This is the article about SpringBoot implementing WeChat payment interface calls and callback functions (merchant parameter acquisition). This is the end. For more related SpringBoot WeChat payment interface calls, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!