Implementing WeChat Mini Program Payment Unified Order in Java

Author:zhaoyiming0803 Date:2025-11-16

Experience is a good thing — just don’t lean on it too hard. Otherwise you’ll spend N times the time and effort on something you could have solved easily.

Today I built the payment feature for a WeChat mini program. I didn’t use the V3 API, and I didn’t use the official Java SDK either. I went with the V2 API and wrote the signing and encryption logic myself. Why:

  1. From my earlier work with V3 WeChat Pay, I feel V2 and V3 aren’t that different in development speed or security.
  2. WeChat Pay’s server SDKs come in Java, PHP, and Go — there’s no Node.js version (Alipay has one). I mostly write backends in Java and Node.js, and a bit of PHP, so I figured if I write it once in Java, I can reuse it in Node.js.

To build WeChat Pay you need to understand the whole flow first. Here’s the official diagram: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3

The Controller layer pseudo code looks roughly like this:

@RestController
@RequestMapping("/wxpay")
public class OrderController {

    @Autowired
    private WxPayService wxPayService;

    private static final String unifiedOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private static final String mchId = "xxx";
    private static final String tradeType = "JSAPI";
    private static final String apiKey = "xxxxxxx";
    private static final String notifyUrl = "https://xxxxx.com/wxpay/notify";
    private static final String signType = "MD5";

    /**
     * WeChat Mini Program unified order api
     */
    @PostMapping("/miniapp/unifiedorder")
    public R createWxMiniappUnifiedorder(@RequestBody CreateWxMiniAppUnifiedorderDto wxMiniappUnifiedorder,
                                         HttpServletRequest request) {
        try {
            // Get openid from your business logic
            // Official doc: https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
            String openid = "";
            // Mini program appid, recommend to config in config file
            String appid = "";
            // 10-digit timestamp in seconds
            Long timeStamp = System.currentTimeMillis() / 1000;
            // Payment amount, unit: cent
            int amount = 1;

            Map<String, String> paramsForFirstSign = getParamsForRequest(appid, openid, amount, request);
            String xmlRequest = wxPayService.mapToXml(paramsForFirstSign);
            // POST request, Content-Type: text/xml
            String xmlResponse = wxPayService.sendPost(unifiedOrderUrl, xmlRequest);
            Map<String, String> responseMap = wxPayService.xmlToMap(xmlResponse);

            String prepayId = responseMap.get("prepay_id");
            if (prepayId != null) {
                // Important: Sign again for mini program frontend
                // Generate new nonceStr and sign, do NOT reuse the one for unified order request
                // Request params: snake_case
                // Frontend response params: camelCase
                String nonceStr = wxPayService.generateNonceStr();
                String wrappedPackageId = "prepay_id=" + prepayId;

                ResponseWxMiniappUnifiedorderDto res = new ResponseWxMiniappUnifiedorderDto();
                res.setNonceStr(nonceStr);
                res.setPackageValue(wrappedPackageId);
                res.setSignType(signType);
                // Reuse the same timestamp
                res.setTimeStamp(timeStamp);

                Map<String, String> paramsForResponse = getParamsForResponse(appid, nonceStr, wrappedPackageId, timeStamp);
                String signForResponse = wxPayService.generateSignature(paramsForResponse, apiKey);
                res.setPaySign(signForResponse);

                return R.ok(res);
            }
            return R.no(responseMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Map<String, String> getParamsForRequest(String appid, String openid, int amount, HttpServletRequest request) {
        try {
            // Generate random string, max 32 chars
            String nonceStr = wxPayService.generateNonceStr();
            // Generate out trade no, max 32 chars
            String outTradeNo = wxPayService.generateOutTradeNo();
            // Get client ip from request
            String ipAddress = wxPayService.getClientIpAddress(request);

            Map<String, String> params = new HashMap<>();
            // Follow official document strictly
            // https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1
            // Params key: snake_case, all lowercase
            params.put("appid", appid);
            params.put("mch_id", mchId);
            params.put("nonce_str", nonceStr);
            params.put("body", "TestOrder");
            params.put("out_trade_no", outTradeNo);
            params.put("total_fee", String.valueOf(amount));
            params.put("spbill_create_ip", ipAddress);
            params.put("notify_url", notifyUrl);
            params.put("trade_type", tradeType);
            params.put("openid", openid);
            params.put("sign_type", signType);

            String signForRequest = wxPayService.generateSignature(params, apiKey);
            params.put("sign", signForRequest);
            return params;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Map<String, String> getParamsForResponse(String appid, String nonceStr, String wrappedPackageId, Long timeStamp) {
        try {
            // Params key: camelCase for mini program pay sign
            Map<String, String> params = new HashMap<>();
            params.put("appId", appid);
            params.put("nonceStr", nonceStr);
            params.put("package", wrappedPackageId);
            params.put("signType", signType);
            params.put("timeStamp", String.valueOf(timeStamp));
            return params;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

You can put the Service layer together yourself — it’s not hard.

The pseudo code for the mini program frontend looks like this:

Page({
  async pay () {
    // Wrap wx.request as Promise
    const unifiedOrderResult = await request({
      url: app.url + '/wxpay/miniapp/unifiedorder',
      method: 'POST',
      data: {
        // Get openid according to your business logic
        openid: ''
      },
      header: {
        "token": "xxxxxx"
      }
    })

    if (unifiedOrderResult.code !== 200) {
      return wx.showToast({
        title: unifiedOrderResult.msg || 'Payment failed, please try again',
        mask: true
      })
    }

    const payOptions = {
      nonceStr: unifiedOrderResult.data.nonceStr,
      package: unifiedOrderResult.data.packageValue,
      paySign: unifiedOrderResult.data.paySign,
      signType: unifiedOrderResult.data.signType,
      // timeStamp must be string type
      timeStamp: unifiedOrderResult.data.timeStamp + ''
    }

    // Wrap wx.requestPayment as Promise
    const prepayResult = await requestPayment(payOptions)

    if (prepayResult.code !== 200) {
      return wx.showToast({
        title: prepayResult.msg || 'Payment failed, please try again',
        mask: true
      })
    }

    // Query order status to confirm payment result
    // Official document: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_2
    const payResult = await request({
      url: app.url + `/app/recharge/order/query/${unifiedOrderResult.data.packageValue}`,
      method: 'POST',
      data: {
        // Get openid according to your business logic
        openid: ''
      },
      header: {
        "token": "xxxxxx"
      }
    })

    // ... other business judgment logic
  }
})

When you integrate third-party payments — WeChat or Alipay, either one — read the docs carefully. AI is not reliable ^_^