1. 程式人生 > >javaweb微信支付開發,掃碼+H5支付

javaweb微信支付開發,掃碼+H5支付

公司專案框架是spring+struts2+mybatis。

最近,因公司專案需要用到微信支付,第一次接觸走了很多彎路,在看了很多大神的demo之後,終於搞定了。記住這不是微信公眾號支付,是PC端掃二維碼跟手機端H5點選支付按鈕的微信支付。

一、工具包

需要用到的工具包有生成二維碼的工具包。

這裡我用的是谷歌的ZXing包——core-3.2.1.jar,這個可以上百度去找,很容易下載。

首先是工具包(建個util包全裝起來),裡面引入的包都挺好找的

HttpUtil

訪問微信支付地址需要用到

package com.yc.weixinutil;

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

public class HttpUtil {
	//private static final Log logger = Logs.get();  
    private final static int CONNECT_TIMEOUT = 5000; // in milliseconds  
    private final static String DEFAULT_ENCODING = "UTF-8";  
      
    public static String postData(String urlStr, String data){  
        return postData(urlStr, data, null);  
    }  
      
    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) {  
            //logger.error("Error connecting to " + urlStr + ": " + e.getMessage());  
            System.out.println("Error connecting to " + urlStr + ": " + e.getMessage());  
        } finally {  
            try {  
                if (reader != null)  
                    reader.close();  
            } catch (IOException e) {  
            }  
        }  
        return null;  
    }  
}

MatrixToImageWriter

這個是谷歌生成二維碼的類

package com.yc.weixinutil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;

public class MatrixToImageWriter {
	private static final int BLACK = 0xFF000000;

	private static final int WHITE = 0xFFFFFFFF;

	private MatrixToImageWriter() {
	}

	public static BufferedImage toBufferedImage(BitMatrix matrix) {

		int width = matrix.getWidth();

		int height = matrix.getHeight();

		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	public static void writeToFile(BitMatrix matrix, String format, File file)

	throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, file)) {
			throw new IOException("Could not write an image of format "
					+ format + " to " + file);
		}
	}

	public static void writeToStream(BitMatrix matrix, String format,
			OutputStream stream) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format "
					+ format);
		}
	}
}

MD5Util

千篇一律的MD5轉碼

package com.yc.weixinutil;

import java.security.MessageDigest;

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" };
}

PayToolUtil

生成微信簽名

package com.yc.weixinutil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class PayToolUtil {
	/**
	 * 是否簽名正確,規則是:按引數名稱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();

		// System.out.println(tenpaySign + "    " + mysign);
		return tenpaySign.equals(mysign);
	}

	/**
	 * @author
	 * @date 2016-4-22
	 * @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
	 * @date 2016-4-22
	 * @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
	 * 
	 * @return String
	 */
	public static String getCurrTime() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String s = outFormat.format(now);
		return s;
	}
}

PayConfigUtil

微信支付需要用到的常量

package com.yc.weixinutil;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class PayConfigUtil {
	// 這個就是自己要保管好的私有Key了(切記只能放在自己的後臺程式碼裡,不能放在任何可能被看到原始碼的客戶端程式中)
	// 每次自己Post資料給API的時候都要用這個key來對所有欄位進行簽名,生成的簽名會放在Sign這個欄位,API收到Post資料的時候也會用同樣的簽名演算法對Post過來的資料進行簽名和驗證
	// 收到API的返回的時候也要用這個key來對返回的資料算下簽名,跟API的Sign資料進行比較,如果值不一致,有可能資料被第三方給篡改
	
	// API_KEY 在微信商戶號上獲取,不懂找度娘
	public static String API_KEY = "XXXXXXXXXXXXXXXXXX";

	// 微信分配的公眾號ID(開通公眾號之後可以獲取到)
	public static String APP_ID = "wx97a1ceeXXXXXXXXX";

	// 微信支付分配的商戶號ID(開通公眾號的微信支付功能之後可以獲取到)
	public static String MCH_ID = "123456789012";

	// 機器IP
	public static String CREATE_IP = getLocalHostAddress();

	// 回撥地址,很重要
	public static String NOTIFY_URL = "http://www.回撥域名.com/加你的回撥地址";

	// 獲取微信支付返回xml的地址
	public static String UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

	public static String getLocalHostAddress() {
		InetAddress addr = null;
		try {
			// 獲取本機的相關資訊並儲存在addr
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return addr.getHostAddress().toString();
	}

}

XMLUtil

將引數封裝成xml,這裡需用到jar包——jdom4.jar,找度娘下載

package com.yc.weixinutil;

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();
		
		//-----------------------2018-07-21---------------------------------------------
        // 參考  http://www.cnblogs.com/hero123/p/9282753.html
        // 這是優先選擇. 如果不允許DTDs (doctypes) ,幾乎可以阻止所有的XML實體攻擊
        String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
        builder.setFeature(FEATURE, true);
 
        FEATURE = "http://xml.org/sax/features/external-general-entities";
        builder.setFeature(FEATURE, false);
 
        FEATURE = "http://xml.org/sax/features/external-parameter-entities";
        builder.setFeature(FEATURE, false);
 
        FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        builder.setFeature(FEATURE, false);
        System.out.println("2018-07-21 加入了修復XXE攻擊漏洞");
        //------------------------------------------------------------------------------
        
		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();
	}
}

二、掃碼支付

開始上程式碼,這是正題。我將生成二維碼,執行微信支付,還有回撥地址都放同一controller,這樣方便我。溫馨提示,記得配置action

package com.yc.business.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom.JDOMException;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.yc.adapter.CommonAdapter;
import com.yc.controller.BaseController;
import com.yc.util.JSONUtil;
import com.yc.weixinutil.HttpUtil;
import com.yc.weixinutil.MatrixToImageWriter;
import com.yc.weixinutil.PayConfigUtil;
import com.yc.weixinutil.PayToolUtil;
import com.yc.weixinutil.XMLUtil;

public class WeixinPayController extends BaseController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private CommonAdapter commonAdapter;

	private Map<String, Object> paramMap = new HashMap<String, Object>();

	private Map<String, Object> resultMap = new HashMap<String, Object>();

	/**
	 * 微信支付二維碼生成
	 */
	public void qrcode() {
		//doEncoding();
		try {
			String bId = (String)paramMap.get("bId");
			// 獲取支付url 
			String text = weixinPay(bId);
			// 根據url來生成生成二維碼
			int width = 300;
			int height = 300;
			// 二維碼的圖片格式
			String format = "gif";
			Hashtable hints = new Hashtable();
			// 內容所使用編碼
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix bitMatrix;
			try {
				bitMatrix = new MultiFormatWriter().encode(text,
						BarcodeFormat.QR_CODE, width, height, hints);
				MatrixToImageWriter.writeToStream(bitMatrix, format,
						response.getOutputStream());
			} catch (WriterException e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 執行微信支付
	 * */ 
	public static String weixinPay(String bId) {
		// 以下的各種引數,不懂得在微信支付開發文件裡面可以查詢
		
		String out_trade_no = "yc3312" + System.currentTimeMillis(); // 訂單號
		// (調整為自己的生產邏輯)
		// 賬號資訊
		String appid = PayConfigUtil.APP_ID; // appid
		// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
		String mch_id = PayConfigUtil.MCH_ID; // 商戶號
		String key = PayConfigUtil.API_KEY; // key

		String currTime = PayToolUtil.getCurrTime();
		String strTime = currTime.substring(8, currTime.length());
		String strRandom = PayToolUtil.buildRandom(4) + "";
		String nonce_str = strTime + strRandom; // 隨機字串

		// 獲取發起電腦 ip
		String spbill_create_ip = PayConfigUtil.CREATE_IP;
		// 回撥介面
		String notify_url = PayConfigUtil.NOTIFY_URL;
		// 這裡說明支付是什麼型別,NATIVE(二維碼),MWEB(H5)
		String trade_type = "NATIVE";

		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", appid);
		// 這裡可以傳你要執行業務需要的引數,可以嘗試傳個MAP過去,我也沒試過
		packageParams.put("attach", bId);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", "測試"); // (調整為自己的名稱)
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("total_fee", "1"); // 價格的單位為分
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);
		packageParams.put("trade_type", trade_type);
		// 簽名
		String sign = PayToolUtil.createSign("UTF-8", packageParams, key);
		packageParams.put("sign", sign);
		// 將引數轉換成xml
		String requestXML = PayToolUtil.getRequestXml(packageParams);
		// 訪問支付地址
		String resXml = HttpUtil
				.postData(PayConfigUtil.UFDODER_URL, requestXML);

		Map map = new HashMap();
		try {
			map = XMLUtil.doXMLParse(resXml);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 獲取支付的url
		String urlCode = (String) map.get("code_url");

		return urlCode;
	}
	
	/**
	 * 回撥方法,修改業務,返回成功資訊給微信支付
	 * */ 
	public void weixinNotify() {
		// 讀取引數
		InputStream inputStream;
		try {
			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 it = m.keySet().iterator();
			while (it.hasNext()) {
				String parameter = (String) it.next();
				String parameterValue = m.get(parameter);

				String v = "";
				if (null != parameterValue) {
					v = parameterValue.trim();
				}
				packageParams.put(parameter, v);
			}

			// 賬號資訊
			String key = PayConfigUtil.API_KEY; // key

			// 判斷簽名是否正確
			if (PayToolUtil.isTenpaySign("UTF-8", packageParams, key)) {
				// ------------------------------
				// 處理業務開始
				// ------------------------------
				String resXml = "";
				if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
					// 這裡是支付成功
					// ////////執行自己的業務邏輯////////////////
					//String mch_id = (String) packageParams.get("mch_id");
					//String openid = (String) packageParams.get("openid");
					//String is_subscribe = (String) packageParams.get("is_subscribe");
					//String out_trade_no = (String) packageParams.get("out_trade_no");
					//String total_fee = (String) packageParams.get("total_fee");
					
					// 獲取剛剛設定的ID
					String bId = (String) packageParams.get("attach");
					
					// ////////執行自己的業務邏輯////////////////
					// 暫時使用最簡單的業務邏輯來處理:只是將業務處理結果儲存到session中
					// (根據自己的實際業務邏輯來調整,很多時候,我們會操作業務表,將返回成功的狀態保留下來)
					paramMap.put("currentStatus", 1);
					paramMap.put("bId", bId);
					commonAdapter.doRunUpdateSql(paramMap, "print.UPDATE_RECORD_PRINT_BY_ID");
					
					// 通知微信.非同步確認成功.必寫.不然會一直通知後臺.八次之後就認為交易失敗了.
					resXml = "<xml>"
							+ "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>"
							+ "</xml> ";

				} else {
					resXml = "<xml>"
							+ "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[報文為空]]></return_msg>"
							+ "</xml> ";
				}
				// ------------------------------
				// 處理業務完畢
				// ------------------------------
				try {
					BufferedOutputStream out = new BufferedOutputStream(
							response.getOutputStream());
					out.write(resXml.getBytes());
					out.flush();
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("通知簽名驗證失敗");
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/***
	 * 輪詢方法
	 */
	public void haPay(){
		//doEncoding();
		try {
			Map<String, Object> map = commonAdapter.queryEntity4Map(paramMap, "print.QUERY_RECORD_PRINT_BY_BID");
			resultMap.put("result",map.get("CURRENTSTATUS"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.doOutResult(JSONUtil.doConvertObject2Json(resultMap));
	}
	
	public CommonAdapter getCommonAdapter() {
		return commonAdapter;
	}

	public void setCommonAdapter(CommonAdapter commonAdapter) {
		this.commonAdapter = commonAdapter;
	}

	public Map<String, Object> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, Object> paramMap) {
		this.paramMap = paramMap;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public void setResultMap(Map<String, Object> resultMap) {
		this.resultMap = resultMap;
	}
}

網頁程式碼

這裡需要用到兩個js。layer.js、jquery-3.3.1.min.js

點選觸發payMoney方法

var t1 = 0;
		/*
		 * 點選支付
		 */
		function patMoney(par){
 			var bId = $(par).parent().find("input").val();
			top.layer.open({
				area : [ '300px', '300px' ],
				type : 2,
				closeBtn : false,
				title : false,
				shift : 2,
				shadeClose : true,
				content : '<%=basePath%>page/weixin/qrcode?paramMap.bId=' + bId,
				end : function (){
					window.clearInterval(t1);
				}
			});
			// 支付進行時,會一直輪詢
		  	t1 = window.setInterval("modifyStatus('"+ bId +"')",3000);
		};
		
		function modifyStatus(bId){
			var url = '<%=basePath%>page/weixin/haPay';
			//輪詢是否已經付費
			$.ajax({
				type : 'post',
				url : url,
				data : {"paramMap.bId" : bId},
				dataType: "json",
				cache : false,
				async : true,
				success : function(res) {
					// 我的資料返回的是狀態1,不明看controller
					// 當該狀態為1時,關閉模態框,重新整理網頁
					if(res.result == "1"){
						top.layer.closeAll();
						window.clearInterval(t1);
						location.reload();
					}
				},
				error : function() {
					layer.msg("執行錯誤!", 8);
				}
			});
		}

以上就是二維碼支付的全部了。

三、H5支付

因為公司框架的原因。controller的執行微信支付方法,我寫在了jsp上。基本一樣,就是加多了一個點選支付完成後,微信幫你返回的地址。

頁面名稱:weixinpay.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.yc.weixinutil.*" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="org.jdom.JDOMException" %>
<%@ page import="java.io.*" %>
<%
	
	String out_trade_no = "yc3312" + System.currentTimeMillis();  // 訂單號
	// (調整為自己的生產邏輯)
	// 賬號資訊
	String appid = PayConfigUtil.APP_ID; // appid
	// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
	String mch_id = PayConfigUtil.MCH_ID; // 商業號	
	String key = PayConfigUtil.API_KEY; // key

	String currTime = PayToolUtil.getCurrTime();
	String strTime = currTime.substring(8, currTime.length());
	String strRandom = PayToolUtil.buildRandom(4) + "";
	String nonce_str = strTime + strRandom;
	// ip地址獲取
	String basePath = request.getServerName() + ":"
			+ request.getServerPort();
	// 獲取發起電腦 ip
	String ip = request.getHeader("x-forwarded-for");
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
        ip = request.getHeader("Proxy-Client-IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
        ip = request.getRemoteAddr();
    }
	String spbill_create_ip = ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	// 回撥介面
	String notify_url = PayConfigUtil.NOTIFY_URL;
	String trade_type = "MWEB";

	SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
	packageParams.put("appid", appid);
	packageParams.put("mch_id", mch_id);
	packageParams.put("attach", request.getParameter("bId"));
	packageParams.put("nonce_str", nonce_str);
	packageParams.put("body", "列印檔案支付"); // (調整為自己的名稱)
	packageParams.put("out_trade_no", out_trade_no);
	packageParams.put("total_fee", "1"); // 價格的單位為分
	packageParams.put("spbill_create_ip", spbill_create_ip);
	packageParams.put("notify_url", notify_url);
	packageParams.put("trade_type", trade_type);
	packageParams.put("scene_info","{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.myssci.com\",\"wap_name\": \"奧科\"}}");

	String sign = PayToolUtil.createSign("UTF-8", packageParams, key);
	packageParams.put("sign", sign);
	String requestXML = PayToolUtil.getRequestXml(packageParams);
	String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL,
			requestXML);
	Map map = new HashMap();
	try {
		map = XMLUtil.doXMLParse(resXml);
		System.out.println(resXml);
		//確認支付過後跳的地址,需要經過urlencode處理
		String urlString = URLEncoder.encode("http://www.域名.com/返回的頁面路徑", "GBK");
		String mweb_url = map.get("mweb_url") + "&redirect_url=" + urlString;
		response.sendRedirect(mweb_url);
	} catch (JDOMException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

%>

當然,頁面上的只有一個按鈕而已,我呼叫了這個方法

/*
		 * 點選支付
		 */
		function patMoney(par){
			var bId = $(par).parent().find("input").val();
 			window.location.href = basePath + "weixinPay.jsp?bId="+bId; 
 			
		};

H5支付也完成了。

總結

第一次開發,難免很多東西不會。建議準備好需要用到的東西在來開發(必須有域名)。

第一次寫,我也不知道寫的怎麼樣。希望你們都能測試成功。