1. 程式人生 > >java 微信掃碼支付

java 微信掃碼支付

/**
 * 統一下單工具類
 * @author why
 *
 */
public class TyxdUtil {
	/**
	 * json資料
	 * @param tyxd
	 * @return
	 */
	public static String makeTyxdMessage(Tyxd tyxd){
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		parameters.put("appid", tyxd.getAppid());
		parameters.put("mch_id", tyxd.getMch_id());
		parameters.put("nonce_str", tyxd.getNonce_str());
		parameters.put("body", tyxd.getBody());
		parameters.put("out_trade_no", tyxd.getOut_trade_no());
		parameters.put("total_fee", tyxd.getTotal_fee());
		parameters.put("spbill_create_ip",tyxd.getSpbill_create_ip());
		parameters.put("notify_url", tyxd.getNotify_url());
		parameters.put("trade_type", tyxd.getTrade_type());
		parameters.put("openid", tyxd.getOpenid());
		String sign = PayCommonUtil.createSign("UTF-8", parameters);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		return requestXML;
	}
	/**
	 * 呼叫統一下單介面
	 * @param requestXML
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> sendTyxdMessage(String requestXML) throws Exception{
		String result =CommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		Map<String, String> map = XMLUtil.doXMLParse(result);//解析微信返回的資訊,以Map形式儲存便於取值
		return map;
	}
	public static void main(String[] args) throws Exception {
		Tyxd t = new Tyxd();
		t.setAppid(ConfigUtil.APPID);//公眾號id
		t.setMch_id(ConfigUtil.MCH_ID);//商戶號
		t.setNonce_str(PayCommonUtil.CreateNoncestr());//隨機字串
//		t.setSign(sign);
		t.setBody("支付測試");//商品描述
		t.setOut_trade_no("1441332471849");//訂單號
		t.setTotal_fee("1");//總金額
		t.setSpbill_create_ip("127.0.0.1");//終端ip
		t.setNotify_url(ConfigUtil.NOTIFY_URL);//通知地址
		t.setTrade_type("NATIVE");//交易型別
		t.setOpenid("");//使用者標示
		Map<String, String> map = TyxdUtil.sendTyxdMessage(TyxdUtil.makeTyxdMessage(t));
		System.out.println(map);
	}
	
	
}

public class PayCommonUtil {
	private static Logger log = LoggerFactory.getLogger(PayCommonUtil.class);
	public static String CreateNoncestr(int length) {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < length; i++) {
			Random rd = new Random();
			res += chars.indexOf(rd.nextInt(chars.length() - 1));
		}
		return res;
	}

	public static String CreateNoncestr() {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < 16; i++) {
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}
	
	/**
     * 獲取一定長度的隨機字串
     * @param length 指定字串長度
     * @return 一定長度的字串
     */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    /**
     * 格式為yyyyMMddHHmmss的訂單時間
     * @return
     */
    public static String getOrderTime(){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    	return sdf.format(new Date());
    }
    /**
     *時間戳
     */
    public static String getTimeStamp(){
    	Long date = System.currentTimeMillis();
    	return date.toString().substring(0, date.toString().length()-3);
    }
	
	/**
	 * @author why
	 * @Description:sign簽名
	 * @param characterEncoding 編碼格式
	 * @param parameters 請求引數
	 * @return
	 */
	public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
		System.out.println(parameters);
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			Object v = entry.getValue();
			if(null != v && !"".equals(v) 
					&& !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + ConfigUtil.API_KEY);
		System.out.println(sb.toString());
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}
	/**
	 * @author why
	 * @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();
	}
	/**
	 * @author why
	 * @Description:返回給微信的引數
	 * @param return_code 返回編碼
	 * @param return_msg  返回資訊
	 * @return
	 */
	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}
}

/**
 * 通用工具類
 * @author why
 * @date 2014-11-21下午9:10:30
 */
public class CommonUtil {
	private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
	/**
	 * 傳送https請求
	 * @param requestUrl 請求地址
	 * @param requestMethod 請求方式(GET、POST)
	 * @param outputStr 提交的資料
	 * @return 返回微信伺服器響應的資訊
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		try {
			// 建立SSLContext物件,並使用我們指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 從上述SSLContext物件中得到SSLSocketFactory物件
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 設定請求方式(GET/POST)
			conn.setRequestMethod(requestMethod);
			conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
			// 當outputStr不為null時向輸出流寫資料
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				// 注意編碼格式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 從輸入流讀取返回內容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 釋放資源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			return buffer.toString();
		} catch (ConnectException ce) {
			log.error("連線超時:{}", ce);
		} catch (Exception e) {
			log.error("https請求異常:{}", e);
		}
		return null;
	}
	
	public static String urlEncodeUTF8(String source){
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
}

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();
	}
	
}

/**
 * 統一下單實體類
 * @author why
 *
 */
public class Tyxd {
	private String appid;//公眾賬號
	private String mch_id;//商戶號
	private String nonce_str;//隨機字串
	private String sign;//簽名
	private String body;//商品描述
	private String out_trade_no;//商戶訂單號
	private String total_fee;//總金額
	private String spbill_create_ip;//終端ip
	private String notify_url;//通知地址
	private String trade_type;//交易型別
	private String openid;//使用者標示
	public Tyxd() {
		super();
	}
	public Tyxd(String appid, String mch_id, String nonce_str, String sign,
			String body, String out_trade_no, String total_fee,
			String spbill_create_ip, String notify_url, String trade_type,
			String openid) {
		super();
		this.appid = appid;
		this.mch_id = mch_id;
		this.nonce_str = nonce_str;
		this.sign = sign;
		this.body = body;
		this.out_trade_no = out_trade_no;
		this.total_fee = total_fee;
		this.spbill_create_ip = spbill_create_ip;
		this.notify_url = notify_url;
		this.trade_type = trade_type;
		this.openid = openid;
	}
	public String getAppid() {
		return appid;
	}
	public void setAppid(String appid) {
		this.appid = appid;
	}
	public String getMch_id() {
		return mch_id;
	}
	public void setMch_id(String mch_id) {
		this.mch_id = mch_id;
	}
	public String getNonce_str() {
		return nonce_str;
	}
	public void setNonce_str(String nonce_str) {
		this.nonce_str = nonce_str;
	}
	public String getSign() {
		return sign;
	}
	public void setSign(String sign) {
		this.sign = sign;
	}
	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 getTotal_fee() {
		return total_fee;
	}
	public void setTotal_fee(String total_fee) {
		this.total_fee = total_fee;
	}
	public String getSpbill_create_ip() {
		return spbill_create_ip;
	}
	public void setSpbill_create_ip(String spbill_create_ip) {
		this.spbill_create_ip = spbill_create_ip;
	}
	public String getNotify_url() {
		return notify_url;
	}
	public void setNotify_url(String notify_url) {
		this.notify_url = notify_url;
	}
	public String getTrade_type() {
		return trade_type;
	}
	public void setTrade_type(String trade_type) {
		this.trade_type = trade_type;
	}
	public String getOpenid() {
		return openid;
	}
	public void setOpenid(String openid) {
		this.openid = openid;
	}
}