1. 程式人生 > >Java實現微信掃碼支付---方式二

Java實現微信掃碼支付---方式二

話不多說直接上程式碼:

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
import java.net.URL;  
import java.net.URLConnection;  


import org.apache.log4j.Logger;  


/** 
 * http請求工具類 
 * @author chenp 
 * 
 */  
public class
HttpUtil {
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds 連線超時的時間 private final static String DEFAULT_ENCODING = "UTF-8"; //字串編碼 private static Logger lg=Logger.getLogger(HttpUtil.class); public static String postData(String urlStr, String data){ return
postData(urlStr, data, null); } /** * post資料請求 * @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:

import java.security.MessageDigest;  
/** 
 * Md5加密類 
 * @author chenp 
 * 
 */  
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 :

import java.net.Inet4Address;  
import java.net.InetAddress;  
import java.net.InterfaceAddress;  
import java.net.NetworkInterface;  
import java.net.SocketException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Enumeration;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
import java.util.Set;  
import java.util.SortedMap;  


import org.apache.log4j.Logger;  


public class PayForUtil {  

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

/**  
     * 是否簽名正確,規則是:按引數名稱a-z排序,遇到空值的引數不參加簽名。  
     * @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 chenp 
     * @Description:sign簽名  
     * @param characterEncoding  
     *            編碼格式  
     * @param parameters  
     *            請求引數  
     * @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 chenp 
     * @Description:將請求引數轉換為xml格式的string  
     * @param parameters  
     *            請求引數  
     * @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();    
    }    

    /**  
     * 取出一個指定長度大小的隨機正整數.  
     *   
     * @param length  
     *            int 設定所取出隨機數的長度。length小於11  
     * @return int 返回生成的隨機數。  
     */    
    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));    
    }    

    /**  
     * 獲取當前時間 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;    
    }  
    /** 
     * 獲取本機IP地址 
     * @author chenp 
     * @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("獲取本機Ip失敗:異常資訊:"+e.getMessage());  
        }  
        return ip;  
    }  

}  

WeChatConfig :
說明:此類與原文相比稍作了修改,大家也可以根據自己需要修改相關程式碼。

import com.iptop.service.base.ConfigProperties;  


/** 
 * 微信支付配置檔案 
 * @author chenp 
 * 
 */  
public class WeChatConfig {  

/** 
* 微信服務號APPID 
*/  
public static String APPID="";  
/** 
* 微信支付的商戶號 
*/  
public static String MCHID="";  
/** 
* 微信支付的API金鑰 
*/  
public static String APIKEY="";  
/** 
* 微信支付成功之後的回撥地址【注意:當前回撥地址必須是公網能夠訪問的地址】 
*/  
public static String WECHAT_NOTIFY_URL_PC="";   
/** 
* 微信統一下單API地址 
*/  
public static String UFDODER_URL="https://api.mch.weixin.qq.com/pay/unifiedorder";  
/** 
* true為使用真實金額支付,false為使用測試金額支付(1分) 
*/  
public static String WXPAY="";  

}  

WeChatParams :

/** 
 * 微信支付需要的一些引數 
 * @author chenp 
 * 
 */ 
 @Data//此註解代替了set、get方法,如果不想用這個註解也可以自己寫set、get方法。 
public class WeChatParams {  

public String total_fee;//訂單金額【備註:以分為單位】  
public String body;//商品名稱  
public String out_trade_no;//商戶訂單號  
public String attach;//附加引數  
public String memberid;//會員ID  

}  

XMLUtil :

import java.io.ByteArrayInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.HashMap;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  


import org.jdom.Document;  
import org.jdom.Element;  
import org.jdom.JDOMException;  
import org.jdom.input.SAXBuilder;  


public class XMLUtil {  

/**  
     * 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml資料。  
     * @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);    
        }    

        //關閉流    
        in.close();    

        return m;    
    }    

    /**  
     * 獲取子結點的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();    
    }    

}  

WeixinPay :

import java.awt.image.BufferedImage;  
import java.io.IOException;  
import java.io.UnsupportedEncodingException;  
import java.net.URLEncoder;  
import java.util.HashMap;  
import java.util.Map;  
import java.util.SortedMap;  
import java.util.TreeMap;  
import javax.imageio.ImageIO;  
import javax.servlet.http.HttpServletResponse;  
import org.apache.commons.lang.StringUtils;  
import org.apache.log4j.Logger;  
import com.google.zxing.BarcodeFormat;  
import com.google.zxing.MultiFormatWriter;  
import com.google.zxing.WriterException;  
import com.google.zxing.common.BitMatrix;  


public class WeixinPay {  

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

/** 
* 獲取微信支付的二維碼地址 
* @return 
* @author chenp 
* @throws Exception 
*/  
public static String getCodeUrl(WeChatParams ps) throws Exception {    
        /** 
         * 賬號資訊   
         */  
        String appid = WeChatConfig.APPID;//微信服務號的appid    
        String mch_id = WeChatConfig.MCHID; //微信支付商戶號    
        String key = WeChatConfig.APIKEY; // 微信支付的API金鑰    
        String notify_url = WeChatConfig.WECHAT_NOTIFY_URL_PC;//回撥地址【注意,這裡必須要使用外網的地址】       
        String ufdoder_url=WeChatConfig.UFDODER_URL;//微信下單API地址  
        String trade_type = "NATIVE"; //型別【網頁掃碼支付】  

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

        /** 
         * 引數封裝 
         */  
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();    
        packageParams.put("appid", appid);    
        packageParams.put("mch_id", mch_id);  
        packageParams.put("nonce_str", nonce_str);//隨機字串  
        packageParams.put("body", ps.body);//支付的商品名稱    
        packageParams.put("out_trade_no", ps.out_trade_no+nonce_str);//商戶訂單號【備註:每次發起請求都需要隨機的字串,否則失敗。】  
        packageParams.put("total_fee", ps.total_fee);//支付金額  
        packageParams.put("spbill_create_ip", PayForUtil.localIp());//客戶端主機  
        packageParams.put("notify_url", notify_url);  
        packageParams.put("trade_type", trade_type);  
        packageParams.put("attach", ps.attach);//額外的引數【業務型別+會員ID+支付型別】  


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

        String requestXML = PayForUtil.getRequestXml(packageParams);//將請求引數轉換成String型別    
        lg.info("微信支付請求引數的報文"+requestXML);    
        String resXml = HttpUtil.postData(ufdoder_url,requestXML);  //解析請求之後的xml引數並且轉換成String型別  
        Map map = XMLUtil.doXMLParse(resXml);    
        lg.info("微信支付響應引數的報文"+resXml);   
        String urlCode = (String) map.get("code_url");    

        return urlCode;    
}    

  /** 
   * 將路徑生成二維碼圖片 
   * @author chenp 
   * @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();  
     }           
 }  
  /** 
  * 型別轉換 
  * @author chenp 
  * @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");    
}  

}  

最後還有一段支付後的回撥程式碼。

/** 
* pc端微信支付之後的回撥方法 
* @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{    

        //讀取引數    
        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());    

        //過濾空 設定 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("微信支付返回回來的引數:"+packageParams);    
        //判斷簽名是否正確    
        if(PayForUtil.isTenpaySign("UTF-8", packageParams,key)) {    
            //------------------------------    
            //處理業務開始    
            //------------------------------    
            String resXml = "";    
            if("SUCCESS".equals((String)packageParams.get("result_code"))){    
                // 這裡是支付成功    
            //執行自己的業務邏輯開始  
            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");//是否關注公眾號  

                //附加引數【商標申請_0bda32824db44d6f9611f1047829fa3b_15460】--【業務型別_會員ID_訂單號】  
                String attach = (String)packageParams.get("attach");  
                //商戶訂單號  
                String out_trade_no = (String)packageParams.get("out_trade_no");    
                //付款金額【以分為單位】  
                String total_fee = (String)packageParams.get("total_fee");    
                //微信生成的交易訂單號  
                String transaction_id = (String)packageParams.get("transaction_id");//微信支付訂單號  
                //支付完成時間  
                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("額外引數_attach:"+attach);   
                lg.info("time_end:"+time_end);   

                //執行自己的業務邏輯結束  
                lg.info("支付成功");    
                //通知微信.非同步確認成功.必寫.不然會一直通知後臺.八次之後就認為交易失敗了.    
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"    
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";    

            } else {    
                lg.info("支付失敗,錯誤資訊:" + packageParams.get("err_code"));    
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"    
                        + "<return_msg><![CDATA[報文為空]]></return_msg>" + "</xml> ";    
            }    
            //------------------------------    
            //處理業務完畢    
            //------------------------------    
            BufferedOutputStream out = new BufferedOutputStream(    
                    response.getOutputStream());    
            out.write(resXml.getBytes());    
            out.flush();    
            out.close();  
        } else{    
            lg.info("通知簽名驗證失敗");    
        }    

    }  

因為採用的是微信掃碼支付的第二種方式,這種方式較第一種業務邏輯相對簡單,也不需要在商戶平臺進行設定什麼的(我這裡就沒有進行什麼設定,沿用的還是以前的設定,但是我看了文件很明顯此種掃碼支付方式沒有用到以前的配置,文件中也沒有提到要進行什麼設定。僅供參考!!!!!!!!)
完成上述程式碼之後,寫一個測試介面:

//微信支付介面
    @RequestMapping("/wxPay")
    public String wxPay(WeChatParams ps) throws Exception {
        ps.setBody("測試商品3");
        ps.setTotal_fee("1");
        ps.setOut_trade_no("hw5409550792199899");
        ps.setAttach("xiner");
        ps.setMemberid("888");
        String urlCode = WeixinPay.getCodeUrl(ps);
        System.out.println(urlCode);
        return "";

    }

直接在瀏覽器中訪問此介面,控制檯列印以下資訊:

這裡寫圖片描述

接收到以上返回資訊後我們將code_url對應的連結地址轉成二維碼,然後用微信中的掃一掃,掃碼生成的二維碼進行支付。
這裡寫圖片描述

我們點選立即支付,輸入密碼完成支付。
這裡寫圖片描述

在我們完成支付的同時,微信會呼叫我們的回撥介面。告訴我們支付結果,我們就可以根據這個支付結果進行業務處理,同時告知微信端我們收到了支付結果通知。
另附上使用者支付完成是控制檯列印的資訊:
這裡寫圖片描述