SoFunction
Updated on 2025-04-13

The entire process of Java connecting to WeChat payment

introduction

Today, with the booming development of digital commerce, mobile payment has become the core link connecting users and services. With its huge user base and mature ecosystem, WeChat Pay has become an indispensable payment tool for enterprises to expand their online business. However, for Java developers, how to efficiently and securely connect to the WeChat payment interface and build a stable and reliable payment system still faces many technical challenges - from complex signature verification mechanisms to idempotence processing of asynchronous notifications, from certificate management to performance optimization in high concurrency scenarios, each step requires accurate technical design and rigorous code implementation.

This article will be guided by systematic and practicality, and will deeply analyze the core processes and key technologies of Java connecting to WeChat payment. Whether it is Native payment, JSAPI payment or mini-program payment, its underlying logic revolves around three core links: prepayment order generation, asynchronous notification of payment results, and active order status query. The article not only provides clear code examples (based on the Spring Boot framework and WeChat Pay V3 API), but also focuses on high-frequency pain points in actual development: How to ensure communication security through RSA signature? How to design an idempotent callback interface to avoid repeated deductions? How to use WeChat platform certificates to prevent forgery requests? These problems will be broken one by one in the article.

In addition, this article will also explore best practices in enterprise-level payment systems, such as using WechatPay Apache HttpClient to simplify certificate management, synchronize order status through distributed locks, and improve system observability in combination with log monitoring. Whether you are a developer who first explores the payment field or a technical person who needs to optimize the existing payment architecture, you can obtain a complete knowledge link from basic configuration to advanced optimization, helping to build a highly available and highly secure payment service system and laying a solid technical cornerstone for business growth.

1. Preparation

Register a WeChat merchant platform

  • Get the merchant number (mchid), API key (API_KEY)。
  • Download API Certificate (apiclient_cert.pemandapiclient_key.pem)。

Configure payment parameters

# 
-id=Your business number
-key=yourAPIKey
-url=https://Your domain name/api/wxpay/notify

2. Core interface implementation

1. Generate prepayment orders (Native payment)

public class WxPayService {
    private String mchId;
    private String apiKey;
    private String notifyUrl;

    // Initialization parameters (read via @Value injection or configuration file)
    /**
      * Generate Native payment QR code link
      */
    public String createNativeOrder(String orderId, int amount) throws Exception {
        String url = "/v3/pay/transactions/native";

        Map<String, Object> params = new HashMap<>();
        ("mchid", mchId);
        ("appid", "Your AppID");  // If it is a public account/mini program payment        ("description", "Order Description");
        ("out_trade_no", orderId);
        ("notify_url", notifyUrl);
        ("amount", ("total", amount, "currency", "CNY"));

        // Generate a signature and send a request        String body = (params);
        String authorization = generateSignature("POST", url, body);
        
        // Send request using OkHttp or RestTemplate        String response = sendPostRequest(url, body, authorization);
        return (response).getString("code_url");
    }

    /**
      * Generate the Authorization header for V3 interface
      */
    private String generateSignature(String method, String url, String body) {
        String timestamp = (() / 1000);
        String nonceStr = ().toString().replace("-", "");
        String message = method + "\n" + url + "\n" + timestamp + "\n" + nonceStr + "\n" + body + "\n";
        String signature = signWithSHA256RSA(message, apiKey);  // Sign with private key        return "WECHATPAY2-SHA256-RSA2048 " 
                + "mchid=\"" + mchId + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"Your certificate serial number\","
                + "signature=\"" + signature + "\"";
    }
}

2. Process WeChat payment callbacks (key!)

@RestController
@RequestMapping("/api/wxpay")
public class WxPayCallbackController {

    @PostMapping("/notify")
    public String handleNotify(@RequestBody String requestBody,
                               @RequestHeader("Wechatpay-Signature") String signature,
                               @RequestHeader("Wechatpay-Timestamp") String timestamp,
                               @RequestHeader("Wechatpay-Nonce") String nonce) {
        // 1. Verify the signature (prevent forgery requests)        String message = timestamp + "\n" + nonce + "\n" + requestBody + "\n";
        boolean isValid = verifySignature(message, signature, publicKey); // Verify using WeChat platform public key        if (!isValid) {
            return "<xml><return_code>FAIL</return_code></xml>";
        }

        // 2. Analyze callback data        Map<String, String> result = parseXml(requestBody);
        String orderId = ("out_trade_no");
        String transactionId = ("transaction_id");
        
        // 3. Impotence processing: Check whether the order has been processed        if ((orderId)) {
            return "<xml><return_code>SUCCESS</return_code></xml>";
        }

        // 4. Update order status        (orderId, transactionId);
        
        // 5. Return a successful response (must! Otherwise WeChat will try again)        return "<xml><return_code>SUCCESS</return_code></xml>";
    }
}

3. Query the order status

public class WxPayService {
    public Map<String, String> queryOrder(String orderId) throws Exception {
        String url = "/v3/pay/transactions/out-trade-no/" 
                    + orderId + "?mchGET", url, "");
        String response = sendGetRequest(url, authorization);
        return (response, );
    }
}

3. Key points to note

Signature verification

  • All callbacks must verify the signature to prevent forgery requests.
  • Using WeChat providedPlatform Certificateverify.

Idepotency design

  • Prevent repeated order processing via database-unique index or Redis lock.

Certificate Management

Recommended useWechatPay Apache HttpClientSimplify certificate processing:

<dependency>
    <groupId>-apiv3</groupId>
    <artifactId>wechatpay-apache-httpclient</artifactId>
    <version>0.4.7</version>
</dependency>

Logging

  • Record all WeChat requests and callbacks to facilitate troubleshooting.

4. Complete call example (Spring Boot)

@RestController
public class PaymentController {
    @Autowired
    private WxPayService wxPayService;

    @GetMapping("/createOrder")
    public String createOrder(@RequestParam String orderId, @RequestParam int amount) {
        try {
            String codeUrl = (orderId, amount);
            return "&amp;lt;img src=\"/qr?data=" + codeUrl + "\"&amp;gt;";
        } catch (Exception e) {
            return "Payment creation failed: " + ();
        }
    }
}

5. Frequently Asked Questions

  • Certificate loading failed: Check the certificate path and format (must be PEM format).
  • Signature error: UseWeChat official visa verification tooldebug.
  • Callback not triggered: Checknotify_urlIs it accessible to the external network and returnSUCCESS

Through the above steps, the core docking of WeChat payment can be completed to ensure the reliability and security of the payment process.

This is the end of this article about the entire process of Java docking with WeChat Pay. For more related content on Java docking with WeChat Pay, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!