微信Native掃碼支付

采用微信提供的Native模式二方式進(jìn)行開發(fā),模式二與模式一相比,流程更為簡(jiǎn)單,不依賴設(shè)置的回調(diào)支付URL。商戶后臺(tái)系統(tǒng)先調(diào)用微信支付的統(tǒng)一下單接口,微信后臺(tái)系統(tǒng)返回鏈接參數(shù)code_url,商戶后臺(tái)系統(tǒng)將code_url值生成二維碼圖片,用戶使用微信客戶端掃碼后發(fā)起支付。注意:code_url有效期為2小時(shí),過期后掃碼不能再發(fā)起支付。

業(yè)務(wù)流程說明:

(1)商戶后臺(tái)系統(tǒng)根據(jù)用戶選購的商品生成訂單。

(2)用戶確認(rèn)支付后調(diào)用微信支付【統(tǒng)一下單API】生成預(yù)支付交易;

(3)微信支付系統(tǒng)收到請(qǐng)求后生成預(yù)支付交易單,并返回交易會(huì)話的二維碼鏈接code_url。

(4)商戶后臺(tái)系統(tǒng)根據(jù)返回的code_url生成二維碼。

(5)用戶打開微信“掃一掃”掃描二維碼,微信客戶端將掃碼內(nèi)容發(fā)送到微信支付系統(tǒng)。

(6)微信支付系統(tǒng)收到客戶端請(qǐng)求,驗(yàn)證鏈接有效性后發(fā)起用戶支付,要求用戶授權(quán)。

(7)用戶在微信客戶端輸入密碼,確認(rèn)支付后,微信客戶端提交授權(quán)。

(8)微信支付系統(tǒng)根據(jù)用戶授權(quán)完成支付交易。

(9)微信支付系統(tǒng)完成支付交易后給微信客戶端返回交易結(jié)果,并將交易結(jié)果通過短信、微信消息提示用戶。微信客戶端展示支付交易結(jié)果頁面。

(10)微信支付系統(tǒng)通過發(fā)送異步消息通知商戶后臺(tái)系統(tǒng)支付結(jié)果。商戶后臺(tái)系統(tǒng)需回復(fù)接收情況,通知微信后臺(tái)系統(tǒng)不再發(fā)送該單的支付通知。

(11)未收到支付通知的情況,商戶后臺(tái)系統(tǒng)調(diào)用【查詢訂單API】。

(12)商戶確認(rèn)訂單已支付后給用戶發(fā)貨。

WeixinPay

public class WeixinPay {
    public static Logger lg= LoggerFactory.getLogger(WeixinPay.class);
    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 獲取微信支付的二維碼地址
     * @return
     * @author pzh
     * @throws Exception
     */
    public static Map getCodeUrl(WeChatParams ps) throws Exception {
        /**
         * 賬號(hào)信息
         */
        String appid = WeChatConfig.APPID;//微信服務(wù)號(hào)的appid
        String mch_id = WeChatConfig.MCHID; //微信支付商戶號(hào)
        String key = WeChatConfig.APIKEY; // 微信支付的API密鑰
        String notify_url = WeChatConfig.WECHAT_NOTIFY_URL_PC;//回調(diào)地址【注意,這里必須要使用外網(wǎng)的地址】
        String ufdoder_url=WeChatConfig.UFDODER_URL;//微信下單API地址

        /**
         * 時(shí)間字符串
         */
        String currTime = PayForUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayForUtil.buildRandom(4) + "";
        String nonce_str = strTime + strRandom;

        /**
         * 參數(shù)封裝
         */
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);//隨機(jī)字符串
        packageParams.put("body", ps.getBody());//支付的商品名稱
        packageParams.put("out_trade_no", ps.getOut_trade_no()+nonce_str);//商戶訂單號(hào)【備注:每次發(fā)起請(qǐng)求都需要隨機(jī)的字符串,否則失敗。】
        packageParams.put("total_fee", ps.getTotal_fee());//支付金額
        packageParams.put("spbill_create_ip", PayForUtil.localIp());//客戶端主機(jī)
        packageParams.put("notify_url", notify_url);
        packageParams.put("trade_type", "NATIVE");
        packageParams.put("limit_pay","no_credit");
        packageParams.put("device_info","WEB");
        packageParams.put("attach", ps.getAttach());//額外的參數(shù)【業(yè)務(wù)類型+會(huì)員ID+支付類型】


        String sign = PayForUtil.createSign("UTF-8", packageParams,key);  //獲取簽名
        packageParams.put("sign", sign);

        String requestXML = PayForUtil.getRequestXml(packageParams);//將請(qǐng)求參數(shù)轉(zhuǎn)換成String類型
        lg.info("微信支付請(qǐng)求參數(shù)的報(bào)文"+requestXML);
        String resXml = HttpUtil.postData(ufdoder_url,requestXML);  //解析請(qǐng)求之后的xml參數(shù)并且轉(zhuǎn)換成String類型
        Map map = XMLUtil.doXMLParse(resXml);
        lg.info("微信支付響應(yīng)參數(shù)的報(bào)文"+resXml);
        String result = (String) map.get("result_code");
        if ("SUCCESS".equals(result)){

        } else {

        }
        return map;
    }

    /**
     * 將路徑生成二維碼圖片
     * @author pzh
     * @param content
     * @param response
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void encodeQrcode(String content,HttpServletResponse response){

        if(StringUtils.isBlank(content))
            return;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 250, 250,hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            //輸出二維碼圖片流
            try {
                ImageIO.write(image, "png", response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WriterException e1) {
            e1.printStackTrace();
        }
    }
    /**
     * 類型轉(zhuǎn)換
     * @author pzh
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }
    // 特殊字符處理
    public static String UrlEncode(String src)  throws UnsupportedEncodingException {
        return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
    }
}

HttpUtil

public class HttpUtil {
    private final static int CONNECT_TIMEOUT = 5000; // in milliseconds  連接超時(shí)的時(shí)間
    private final static String DEFAULT_ENCODING = "UTF-8";  //字符串編碼
    private static Logger lg= LoggerFactory.getLogger(HttpUtil.class);

    public static String postData(String urlStr, String data){
        return postData(urlStr, data, null);
    }
    /**
     * post數(shù)據(jù)請(qǐng)求
     * @param urlStr
     * @param data
     * @param contentType
     * @return
     */
    public static String postData(String urlStr, String data, String contentType){
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            if(contentType != null)
                conn.setRequestProperty("content-type", contentType);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if(data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            lg.info("Error connecting to " + urlStr + ": " + e.getMessage());
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
}

MD5Util

public class MD5Util {
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}

PayForUtil

public class PayForUtil {
    private static Logger lg= LoggerFactory.getLogger(PayForUtil.class);

    /**
     * 是否簽名正確,規(guī)則是:按參數(shù)名稱a-z排序,遇到空值的參數(shù)不參加簽名。
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);

        //算出摘要
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();

        return tenpaySign.equals(mysign);
    }

    /**
     * @author pzh
     * @Description:sign簽名
     * @param characterEncoding
     *            編碼格式
     * @return
     */
    public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + API_KEY);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    /**
     * @author pzh
     * @Description:將請(qǐng)求參數(shù)轉(zhuǎn)換為xml格式的string
     * @param parameters
     *            請(qǐng)求參數(shù)
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 取出一個(gè)指定長(zhǎng)度大小的隨機(jī)正整數(shù).
     *
     * @param length
     *            int 設(shè)定所取出隨機(jī)數(shù)的長(zhǎng)度。length小于11
     * @return int 返回生成的隨機(jī)數(shù)。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }

    /**
     * 獲取當(dāng)前時(shí)間 yyyyMMddHHmmss
     *  @author chenp
     * @return String
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }
    /**
     * 獲取本機(jī)IP地址
     * @author pzh
     * @return
     */
    public static String localIp(){
        String ip = null;
        Enumeration allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
                for (InterfaceAddress add : InterfaceAddress) {
                    InetAddress Ip = add.getAddress();
                    if (Ip != null && Ip instanceof Inet4Address) {
                        ip = Ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            lg.warn("獲取本機(jī)Ip失敗:異常信息:"+e.getMessage());
        }
        return ip;
    }
}

WeChatConfig

public class WeChatConfig {
    /**
     * 微信服務(wù)號(hào)APPID
     */
    public static String APPID="";
    /**
     * 微信支付的商戶號(hào)
     */
    public static String MCHID="";
    /**
     * 微信支付的API密鑰
     */
    public static String APIKEY="";
    /**
     * 微信支付成功之后的回調(diào)地址【注意:當(dāng)前回調(diào)地址必須是公網(wǎng)能夠訪問的地址】
     */
    public static String WECHAT_NOTIFY_URL_PC="http://****/wechat_notify_url_pc";
    /**
     * 微信統(tǒng)一下單API地址
     */
    public static String UFDODER_URL="https://api.mch.weixin.qq.com/pay/unifiedorder";
    /**
     * true為使用真實(shí)金額支付,false為使用測(cè)試金額支付(1分)
     */
    public static String WXPAY="false";

}

WeChatParams

public class WeChatParams {
    private String total_fee;//訂單金額【備注:以分為單位】
    private String body;//商品名稱
    private String product_id;//商品ID
    private String out_trade_no;//商戶訂單號(hào)
    private String attach;//附加參數(shù)
    private String memberid;//會(huì)員ID

    public String getTotal_fee() {
        return total_fee;
    }

    public void setTotal_fee(String total_fee) {
        this.total_fee = total_fee;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getOut_trade_no() {
        return out_trade_no;
    }

    public void setOut_trade_no(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }

    public String getAttach() {
        return attach;
    }

    public void setAttach(String attach) {
        this.attach = attach;
    }

    public String getMemberid() {
        return memberid;
    }

    public void setMemberid(String memberid) {
        this.memberid = memberid;
    }

    public String getProduct_id() {
        return product_id;
    }

    public void setProduct_id(String product_id) {
        this.product_id = product_id;
    }
}

XMLUtil

public class XMLUtil {
    /**
     * 解析xml,返回第一級(jí)元素鍵值對(duì)。如果第一級(jí)元素有子節(jié)點(diǎn),則此節(jié)點(diǎn)的值是子節(jié)點(diǎn)的xml數(shù)據(jù)。
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws JDOMException, IOException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if(null == strxml || "".equals(strxml)) {
            return null;
        }
        Map m = new HashMap();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XMLUtil.getChildrenText(children);
            }
            m.put(k, v);
        }
        //關(guān)閉流
        in.close();
        return m;
    }

    /**
     * 獲取子結(jié)點(diǎn)的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(XMLUtil.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
}

wechat_notify_url_pc

/** 
* pc端微信支付之后的回調(diào)方法 
* @param request 
* @param response 
* @throws Exception 
*/  
    @RequestMapping(value="wechat_notify_url_pc",method=RequestMethod.POST)  
public void wechat_notify_url_pc(HttpServletRequest request,HttpServletResponse response) throws Exception{    

        //讀取參數(shù)    
        InputStream inputStream ;    
        StringBuffer sb = new StringBuffer();    
        inputStream = request.getInputStream();    
        String s ;    
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));    
        while ((s = in.readLine()) != null){    
            sb.append(s);    
        }    
        in.close();    
        inputStream.close();    

        //解析xml成map    
        Map<String, String> m = new HashMap<String, String>();    
        m = XMLUtil.doXMLParse(sb.toString());    

        //過濾空 設(shè)置 TreeMap    
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();          
        Iterator<String> it = m.keySet().iterator();    
        while (it.hasNext()) {    
            String parameter = it.next();    
            String parameterValue = m.get(parameter);    

            String v = "";    
            if(null != parameterValue) {    
                v = parameterValue.trim();    
            }    
            packageParams.put(parameter, v);    
        }    
        // 微信支付的API密鑰    
        String key = WeChatConfig.APIKEY; // key    

        lg.info("微信支付返回回來的參數(shù):"+packageParams);    
        //判斷簽名是否正確    
        if(PayForUtil.isTenpaySign("UTF-8", packageParams,key)) {    
            //------------------------------    
            //處理業(yè)務(wù)開始    
            //------------------------------    
            String resXml = "";    
            if("SUCCESS".equals((String)packageParams.get("result_code"))){    
                // 這里是支付成功    
            //執(zhí)行自己的業(yè)務(wù)邏輯開始  
            String app_id = (String)packageParams.get("appid");  
                String mch_id = (String)packageParams.get("mch_id");    
                String openid = (String)packageParams.get("openid");   
                String is_subscribe = (String)packageParams.get("is_subscribe");//是否關(guān)注公眾號(hào)  

                //附加參數(shù)【商標(biāo)申請(qǐng)_0bda32824db44d6f9611f1047829fa3b_15460】--【業(yè)務(wù)類型_會(huì)員ID_訂單號(hào)】  
                String attach = (String)packageParams.get("attach");  
                //商戶訂單號(hào)  
                String out_trade_no = (String)packageParams.get("out_trade_no");    
                //付款金額【以分為單位】  
                String total_fee = (String)packageParams.get("total_fee");    
                //微信生成的交易訂單號(hào)  
                String transaction_id = (String)packageParams.get("transaction_id");//微信支付訂單號(hào)  
                //支付完成時(shí)間  
                String time_end=(String)packageParams.get("time_end");  

                lg.info("app_id:"+app_id);  
                lg.info("mch_id:"+mch_id);    
                lg.info("openid:"+openid);    
                lg.info("is_subscribe:"+is_subscribe);    
                lg.info("out_trade_no:"+out_trade_no);    
                lg.info("total_fee:"+total_fee);    
                lg.info("額外參數(shù)_attach:"+attach);   
                lg.info("time_end:"+time_end);   

                //執(zhí)行自己的業(yè)務(wù)邏輯結(jié)束  
                lg.info("支付成功");    
                //通知微信.異步確認(rèn)成功.必寫.不然會(huì)一直通知后臺(tái).八次之后就認(rèn)為交易失敗了.    
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"    
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";    

            } else {    
                lg.info("支付失敗,錯(cuò)誤信息:" + packageParams.get("err_code"));    
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"    
                        + "<return_msg><![CDATA[報(bào)文為空]]></return_msg>" + "</xml> ";    
            }    
            //------------------------------    
            //處理業(yè)務(wù)完畢    
            //------------------------------    
            BufferedOutputStream out = new BufferedOutputStream(    
                    response.getOutputStream());    
            out.write(resXml.getBytes());    
            out.flush();    
            out.close();  
        } else{    
            lg.info("通知簽名驗(yàn)證失敗");    
        }    
    }  
//微信支付接口
    @RequestMapping("/wxPay")
    public String wxPay(WeChatParams ps) throws Exception {
        ps.setBody("測(cè)試商品3");
        ps.setTotal_fee("1");
        ps.setOut_trade_no("5409550792199999");
        ps.setAttach("xiner");
        ps.setMemberid("888");
        String urlCode = WeixinPay.getCodeUrl(ps);
        System.out.println(urlCode);
        return "";
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容