Summary of wechat code scanning payment

Summary of wechat code scanning payment

1. Code scanning payment process

    Wechat code scanning payment, the process is very simple, that is, put some information you want to pay into the collection, then use the wechat SDK to generate the corresponding URL, and then generate the corresponding two-dimensional code according to the URL. After code scanning payment, there will be callback and asynchronous notification in the wechat background (it needs to be printed and viewed in the server log)

2. configuration

[SDK Example of invocation](https://pay.weixin.qq.com/wiki/doc/api/download/WxPayAPI_JAVA.zip)

    <dependency>
        <groupId>com.github.wxpay</groupId>
        <artifactId>wxpay-sdk</artifactId>
        <version>Adaptive version</version>
    </dependency>

//Create a new configuration class to implement the WXPayConfig interface, which will be configured with appid, mchid and key, which need to be obtained on the company's merchant platform

    private byte[] certData;

    /*public WeChatConf() throws Exception {
        String certPath = "/apiclient_cert.p12";
        //String certPath = "Certificate path to be saved for refund ";
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }*/

    public String getAppID() {
        return AppId;
    }

    public String getMchID() {
        return MchID;
    }

    public String getKey() {
        return Key;
    }


    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

3. Start to realize the function

    WeChatConf weChatConf = null;
    try {
        weChatConf = new WeChatConf();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //account information
    String appId = weChatConf.getAppID();
    //Business number
    String mch_id = weChatConf.getMchID();
    //Payment secret key
    String key = weChatConf.getKey();
    Map<String, String> data = new HashMap<String, String>();
    data.put("appid", Public account number ID);
    data.put("mch_id", Business number);
    data.put("nonce_str", Random string);
    data.put("body", Commodity Description);
    data.put("out_trade_no", Merchant order number, non repeatable);
    data.put("fee_type", "CNY");//Bid currency (default RMB)
    data.put("total_fee", totalFee+"");//Bid price amount, unit: minute
    data.put("spbill_create_ip", terminal IP);
    data.put("notify_url", Notification address, which must be accessible by the Internet);
    data.put("trade_type", "NATIVE");  // Specified here as scan payment
    String sign = null;
    try {       //WXPayUtil can be found in the SDK downloaded from the link above
        sign = WXPayUtil.generateSignature(data,key,WXPayConstants.SignType.MD5);
    } catch (Exception e) {
        e.printStackTrace();
    }
    data.put("sign", sign);   //autograph
    
    WXPay wxpay = new WXPay(weChatConf);
    Map<String, String> mss = null;
    try {
        mss = wxpay.unifiedOrder(data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String codeUrl = mss.get("code_url");//Here is the URL to generate QR code returned by wechat and wechat

//Writing here, there was a problem. According to the technology provided by the authorities, it is a method to generate the two-dimensional code and use the stream to output to the front desk, because it is the payment of pictures, and it can not be saved to the local ones. But when I was doing it, it was only when the browser was compatible with the mode that the two-dimensional code was displayed. The speed mode did not show that it was very big. Because Alipay paid it directly. Just return a URL, and the generation of QR code will be solved by Alibaba background. So I changed my mind, and directly left it to the foreground to return a URL, and the QR code will be generated in the foreground

//In fact, the payment has been completed by more than a half, but I feel that Alipay and WeChat are not in the same place. Alipay is going to return to a state directly. WeChat needs to write a callback interface, and has to check the callback results on its own, and then return it to WeChat.

//Let's take a look at the callback interface. The callback data of wechat needs to be received by streams


    String returnPage = "";
    String notifyData = "";
    InputStream is = request.getInputStream();
    StringBuffer sb = new StringBuffer();
    String s = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    while ((s = in.readLine()) != null) {
        sb.append(s);
    }
    in.close();
    is.close();
    notifyData = sb.toString();
    Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);// Convert to map
    if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
        // Correct signature
        //Notify wechat. Asynchronous confirmation succeeded. Must be written. Otherwise, it will always notify the background. Eight times later, it will be considered that the transaction failed
        resXml = "<xml>" + "<return_codSUCCESS]]></return_code>"
        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
    } else {
        // Signature error. If there is no sign field in the data, it is also considered as a signature error
        resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
        + "<return_msg><![CDATA[The message is empty.]]></return_msg>" + "</xml> ";
    }
    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    out.write(resXml.getBytes());
    out.flush();
    out.close();

    //Write here, the whole QR code payment is over. In addition, if the QR code is generated in the front desk, you need to write another polling interface to check whether the order status is paid, and then jump to payment success / payment failure in the front desk according to the returned results. Just after work, there are bad written places to accept comments, leaving a problem for the big guys, will the front desk generate QR code payment be safe How to solve the problem?

Keywords: Java SDK xml github

Added by madspoihur on Wed, 11 Dec 2019 18:29:33 +0200