微信掃碼支付

業務需求

商戶自定義金額生成二維碼,掃描二維碼進行自定義金額支付

官方文檔鏈接

https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_4

接口代碼

@RequestMapping(value = "/companyReceipt")
    @ResponseBody
    public String companyReceipt(TTemplatePay tTemplatePay) throws Exception {
        JSONObject jsonObject = new JSONObject();
        PayUtil payUtil = new PayUtil();
        String codeUrl = "";
        // 公衆賬號ID
        payUtil.setAppid(PAY_APPID);
        // 商戶號
        payUtil.setMch_id(PAY_MCH_ID);
        payUtil.setOut_trade_no(WeixinpayUtil.getUUID());
        payUtil.setNonce_str(WeixinpayUtil.getUUID());
        // 通知地址(支付成功,回調接口地址)
        payUtil.setNotify_url(NOTIFY_URL);
       	// 自定義支付金額(單位:分)
        payUtil.setTotal_fee(tTemplatePay.getTotalFee()*100);

        LOGGER.info("------企業支付生成支付二維碼,支付金額money{}", payUtil.getTotal_fee());
        // 企業指定金額生成支付二維碼
        Map<String, Object> map = WxCompanyReceiptUtil.wxCompanyReceipt(payUtil);

        if(StringUtils.equals("SUCCESS", map.get("result_code").toString()) && StringUtils.equals("SUCCESS", map.get("return_code").toString())){
            tTemplatePay.setOutTradeNo(payUtil.getOut_trade_no());
            tTemplatePay.setNonceStr(payUtil.getNonce_str());
            // 支付訂單信息添加到數據庫
            int i = payService.insertTemplateOrder(tTemplatePay);
            if(i > 0){
            	// 二維碼鏈接
                codeUrl = map.get("code_url").toString();
                jsonObject.accumulate("codeUrl", codeUrl);
                LOGGER.info("------企業支付生成支付二維碼,支付二維碼鏈接{}", codeUrl);
                LOGGER.info("------企業生成支付二維碼,掃碼支付訂單入庫{}", "SUCCESS");
            }else{
                LOGGER.info("------企業生成支付二維碼,掃碼支付訂單入庫{}", "ERROR");
            }
        }else{
            LOGGER.info("------企業生成支付二維碼{}", "ERROR");
        }
        return jsonObject.toString();
    }

組裝參數請求獲取二維碼

package com.litte.util;

import com.litte.entity.PayUtil;
import com.litte.util.wxpay.WXPayUtil;

import java.util.Map;

public class WxCompanyReceiptUtil {
    /**
     * @Description: 企業指定金額生成支付二維碼
     * @Author: Mr.Jkx
     * @Date: 2019/4/10 10:40
     */
    public static Map<String, Object> wxCompanyReceipt(PayUtil payUtil) throws Exception {
        String stringA = "appid=" + payUtil.getAppid()
                + "&body=商品描述"
                + "&mch_id=" + payUtil.getMch_id()
                + "&nonce_str=" + payUtil.getNonce_str()
                + "&notify_url=" + "https://域名/wxPay/companyReceiptBack"
                + "&out_trade_no=" + payUtil.getOut_trade_no()
                + "&spbill_create_ip=Ip" // 終端IP
                + "&total_fee="+ payUtil.getTotal_fee()
                + "&trade_type=NATIVE"
                + "&key=支付祕鑰";
        String sign = Md5Util.md5(stringA).toUpperCase();

        String xml = "<xml>" +
                "   <appid>" + payUtil.getAppid() + "</appid>" +
                "   <body>商品描述</body>" +
                "   <mch_id>" + payUtil.getMch_id() + "</mch_id>" +
                "   <nonce_str>" + payUtil.getNonce_str() + "</nonce_str>" +
                "   <notify_url>NOTIFY_URL</notify_url>" +
                "   <out_trade_no>" + payUtil.getOut_trade_no() + "</out_trade_no>" +
                "   <spbill_create_ip>Ip</spbill_create_ip>" +
                "   <total_fee>" + payUtil.getTotal_fee() + "</total_fee>" +
                "   <trade_type>NATIVE</trade_type>" +
                "   <sign>" + sign + "</sign>" +
                "</xml> ";

        System.out.println("調試模式_統一下單接口 請求XML數據:" + xml);

        //調用統一下單接口,並接受返回的結果
        String result = BasePay.httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml);
        // 將解析結果存儲在HashMap中
        Map map = WXPayUtil.xmlToMap(result);
        return map;
    }
}

請求方法類

package com.litte.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class BasePay {

    /**
     *   
     *  *  
     *  * @param requestUrl請求地址  
     *  * @param requestMethod請求方法  
     *  * @param outputStr參數  
     *  
     */
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        // 創建SSLContext
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //往服務器端寫內容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 讀取服務器端返回的內容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}

支付後回調請求接口

/** 
    * @Description: 企業微信返回信息,更改訂單狀態
    * @Author: Mr.Jkx 
    * @Date: 2019/4/27 18:28
    */
    @RequestMapping(value = "/companyReceiptBack")
    @ResponseBody
    public void companyReceiptBack(HttpServletRequest request) throws Exception {
        String xmlStr = NotifyServlet.getWxXml(request);
        LOGGER.info("------掃描企業支付二維碼回調請求數據{}", xmlStr);
        // 解析回調請求參數
        Map map2 = WXPayUtil.xmlToMap(xmlStr);
        // 根據回調參數操作訂單信息
       	// TODO
    }

微信相關工具類

package com.litte.util.wxpay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;


public class WXPayUtil {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * XML格式字符串轉換爲Map
     *
     * @param strXML XML字符串
     * @return XML數據轉換後的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * 將Map轉換爲XML格式的字符串
     *
     * @param data Map類型數據
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }


    /**
     * 生成帶有 sign 的 XML 格式字符串
     *
     * @param data Map類型數據
     * @param key API密鑰
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
        return generateSignedXml(data, key, WXPayConstants.SignType.MD5);
    }

    /**
     * 生成帶有 sign 的 XML 格式字符串
     *
     * @param data Map類型數據
     * @param key API密鑰
     * @param signType 簽名類型
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put(WXPayConstants.FIELD_SIGN, sign);
        return mapToXml(data);
    }


    /**
     * 判斷簽名是否正確
     *
     * @param xmlStr XML格式數據
     * @param key API密鑰
     * @return 簽名是否正確
     * @throws Exception
     */
    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data = xmlToMap(xmlStr);
        if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    /**
     * 判斷簽名是否正確,必須包含sign字段,否則返回false。使用MD5簽名。
     *
     * @param data Map類型數據
     * @param key API密鑰
     * @return 簽名是否正確
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        return isSignatureValid(data, key, WXPayConstants.SignType.MD5);
    }

    /**
     * 判斷簽名是否正確,必須包含sign字段,否則返回false。
     *
     * @param data Map類型數據
     * @param key API密鑰
     * @param signType 簽名方式
     * @return 簽名是否正確
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key, signType).equals(sign);
    }

    /**
     * 生成簽名
     *
     * @param data 待簽名數據
     * @param key API密鑰
     * @return 簽名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, WXPayConstants.SignType.MD5);
    }

    /**
     * 生成簽名. 注意,若含有sign_type字段,必須和signType參數保持一致。
     *
     * @param data 待簽名數據
     * @param key API密鑰
     * @param signType 簽名方式
     * @return 簽名
     */
    public static String generateSignature(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 參數值爲空,則不參與簽名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if (WXPayConstants.SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }


    /**
     * 獲取隨機字符串 Nonce Str
     *
     * @return String 隨機字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }


    /**
     * 生成 MD5
     *
     * @param data 待處理數據
     * @return MD5結果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     * @param data 待處理數據
     * @param key 密鑰
     * @return 加密結果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 日誌
     * @return
     */
    public static Logger getLogger() {
        Logger logger = LoggerFactory.getLogger("wxpay java sdk");
        return logger;
    }

    /**
     * 獲取當前時間戳,單位秒
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis()/1000;
    }

    /**
     * 獲取當前時間戳,單位毫秒
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }
}

微信商戶平臺

實現自定義二維碼生成功能必須在“微信商戶平臺”開通“Native支付”支付產品;
在這裏插入圖片描述

發佈了35 篇原創文章 · 獲贊 27 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章