微信实现Java
微信APP支付接口,是很好調(diào)試的,(不像微信公眾平臺,需要80端口),可以直接在本地就可以進行調(diào)試。 具體業(yè)務(wù)就不細說,直接看代碼就懂了。
1 基礎(chǔ)信息配置
?
package com.cat.common.pay.weiChat.config;import java.util.Properties;import com.cat.common.properties.PropertiesUtil;public class WeiChartConfig {/*** 預(yù)支付請求地址*/public static final String PrepayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";/*** 查詢訂單地址*/public static final String OrderUrl = "https://api.mch.weixin.qq.com/pay/orderquery";/*** 關(guān)閉訂單地址*/public static final String CloseOrderUrl = "https://api.mch.weixin.qq.com/pay/closeorder";/*** 申請退款地址*/public static final String RefundUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";/*** 查詢退款地址*/public static final String RefundQueryUrl = "https://api.mch.weixin.qq.com/pay/refundquery";/*** 下載賬單地址*/public static final String DownloadBillUrl = "https://api.mch.weixin.qq.com/pay/downloadbill";/*** 商戶APPID*/public static final String AppId = "wx1234567890";/*** 商戶賬戶*/public static final String MchId = "1234567890";/*** 商戶秘鑰*/public static final String AppSercret = "123456789098765432123";/*** 服務(wù)器異步通知頁面路徑*/public static String notify_url = getProperties().getProperty("notify_url");/*** 頁面跳轉(zhuǎn)同步通知頁面路徑*/public static String return_url = getProperties().getProperty("return_url");/*** 退款通知地址*/public static String refund_notify_url = getProperties().getProperty("refund_notify_url");/*** 退款需要證書文件,證書文件的地址*/public static String refund_file_path = getProperties().getProperty("refund_file_path");/*** 商品名稱*/public static String subject = getProperties().getProperty("subject");/*** 商品描述*/public static String body = getProperties().getProperty("body");private static Properties properties;public static synchronized Properties getProperties(){if(properties == null){ // String path = System.getenv(RSystemConfig.KEY_WEB_HOME_CONF) + "/weichart.properties";//自定義配置文件路徑String path = "d://weichart.properties";//測試路徑properties = PropertiesUtil.getInstance().getProperties(path);}return properties;}}這里是 PropertiesUtil 類
package com.cat.common.properties;import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties;public class PropertiesUtil{private static PropertiesUtil instance;private Properties properties = new Properties();public synchronized static PropertiesUtil getInstance() {if(null == instance) {instance = new PropertiesUtil();}return instance;}/*** 獲取配置* @param fileUrl* @return*/public Properties getProperties(String fileUrl){readProperties(fileUrl);return properties;}/*** 讀取properties的全部信息* @param filePath*/public void readProperties(String filePath){InputStream in = null;try{in = new BufferedInputStream(new FileInputStream(filePath));properties.load(in);}catch(Exception e){e.printStackTrace();}finally{try{if(in != null)in.close();}catch(IOException e){e.printStackTrace();}}} }2 http /https請求的工具類
其中有需要證書的,也有不需要證書的。
證書是在需要退款接口的時候需要使用,直接把證書放在服務(wù)器上,然后傳路徑
4 調(diào)用API接口
其中包含 XML生成,和解析XML,請求參數(shù)字典排序,拼接密鑰,MD5加密
這里是核心和微信交互的類。
package com.cat.common.pay.weiChat;import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Set;import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element;import com.cat.common.pay.weiChat.config.WeiChartConfig; import com.cat.common.pay.weiChat.util.HttpClientUtil;public class WeiChartUtil{/*** 返回狀態(tài)碼*/public static final String ReturnCode = "return_code";/*** 返回信息*/public static final String ReturnMsg = "return_msg";/*** 業(yè)務(wù)結(jié)果*/public static final String ResultCode = "result_code";/*** 預(yù)支付交易會話標識*/public static final String PrepayId = "prepay_id";/*** 得到微信預(yù)付單的返回ID* @param orderId 商戶自己的訂單號* @param totalFee 總金額 (分)* @return*/public static Map<String, String> getPreyId(String orderId,String totalFee,String schoolLabel){Map<String, String> reqMap = new HashMap<String, String>();reqMap.put("appid", WeiChartConfig.AppId);reqMap.put("mch_id", WeiChartConfig.MchId);reqMap.put("nonce_str", getRandomString());reqMap.put("body", "【"+schoolLabel+"】"+ WeiChartConfig.body);//reqMap.put("detail", WeiChartConfig.subject); //非必填//reqMap.put("attach", "附加數(shù)據(jù)"); //非必填reqMap.put("out_trade_no", orderId); //商戶系統(tǒng)內(nèi)部的訂單號,reqMap.put("total_fee", totalFee); //訂單總金額,單位為分reqMap.put("spbill_create_ip", getHostIp()); //用戶端實際ip// reqMap.put("time_start", "172.16.40.18"); //交易起始時間 非必填// reqMap.put("time_expire", "172.16.40.18"); //交易結(jié)束時間 非必填// reqMap.put("goods_tag", "172.16.40.18"); //商品標記 非必填reqMap.put("notify_url", WeiChartConfig.notify_url); //通知地址reqMap.put("trade_type", "APP"); //交易類型//reqMap.put("limit_pay", "no_credit"); //指定支付方式,no_credit 指定不能使用信用卡支 非必填reqMap.put("sign", getSign(reqMap));String reqStr = creatXml(reqMap);String retStr = HttpClientUtil.postHtpps(WeiChartConfig.PrepayUrl, reqStr);return getInfoByXml(retStr);}/*** 關(guān)閉訂單* @param orderId 商戶自己的訂單號* @return*/public static Map<String, String> closeOrder(String orderId){Map<String, String> reqMap = new HashMap<String, String>();reqMap.put("appid", WeiChartConfig.AppId);reqMap.put("mch_id", WeiChartConfig.MchId);reqMap.put("nonce_str", getRandomString());reqMap.put("out_trade_no", orderId); //商戶系統(tǒng)內(nèi)部的訂單號,reqMap.put("sign", getSign(reqMap));String reqStr = creatXml(reqMap);String retStr = HttpClientUtil.postHtpps(WeiChartConfig.CloseOrderUrl, reqStr);return getInfoByXml(retStr);}/*** 查詢訂單* @param orderId 商戶自己的訂單號* @return*/public static String getOrder(String orderId){Map<String, String> reqMap = new HashMap<String, String>();reqMap.put("appid", WeiChartConfig.AppId);reqMap.put("mch_id", WeiChartConfig.MchId);reqMap.put("nonce_str", getRandomString());reqMap.put("out_trade_no", orderId); //商戶系統(tǒng)內(nèi)部的訂單號,reqMap.put("sign", getSign(reqMap));String reqStr = creatXml(reqMap);String retStr = HttpClientUtil.postHtpps(WeiChartConfig.OrderUrl, reqStr);return retStr;}/*** 退款* @param orderId 商戶訂單號* @param refundId 退款單號* @param totralFee 總金額(分)* @param refundFee 退款金額(分)* @param opUserId 操作員ID* @return*/public static Map<String, String> refundWei(String orderId,String refundId,String totralFee,String refundFee,String opUserId){Map<String, String> reqMap = new HashMap<String, String>();reqMap.put("appid", WeiChartConfig.AppId);reqMap.put("mch_id", WeiChartConfig.MchId);reqMap.put("nonce_str", getRandomString());reqMap.put("out_trade_no", orderId); //商戶系統(tǒng)內(nèi)部的訂單號,reqMap.put("out_refund_no", refundId); //商戶退款單號reqMap.put("total_fee", totralFee); //總金額reqMap.put("refund_fee", refundFee); //退款金額reqMap.put("op_user_id", opUserId); //操作員reqMap.put("sign", getSign(reqMap));String reqStr = creatXml(reqMap);String retStr = "";try{retStr = HttpClientUtil.postHttplientNeedSSL(WeiChartConfig.RefundUrl, reqStr, WeiChartConfig.refund_file_path, WeiChartConfig.MchId);}catch(Exception e){e.printStackTrace();return null;}return getInfoByXml(retStr);}/*** 退款查詢* @param refundId 退款單號* @return*/public static Map<String, String> getRefundWeiInfo(String refundId){Map<String, String> reqMap = new HashMap<String, String>();reqMap.put("appid", WeiChartConfig.AppId);reqMap.put("mch_id", WeiChartConfig.MchId);reqMap.put("nonce_str", getRandomString());reqMap.put("out_refund_no", refundId); //商戶退款單號reqMap.put("sign", getSign(reqMap));String reqStr = creatXml(reqMap);String retStr = HttpClientUtil.postHtpps(WeiChartConfig.RefundQueryUrl, reqStr);return getInfoByXml(retStr);}/**這個方法 可以自己寫,以前我使用的是我公司封裝的類,后來很多人找我要JAR包,所以我改成了這樣,方便部分人直接使用代碼,我自己未測試,不過應(yīng)該問題不大,歡迎使用有問題的找我。* 傳入map 生成頭為XML的xml字符串,例:<xml><key>123</key></xml>* @param reqMap* @return*/public static String creatXml(Map<String, String> reqMap){Set<String> set = reqMap.keySet();StringBuffer b = new StringBuffer();b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");b.append("<xml>");for(String key : set){b.append("<"+key+">").append(reqMap.get(key)).append("</"+key+">");}b.append("</xml>");return b.toString();}/*** 得到加密值* @param map* @return*/public static String getSign(Map<String, String> map){String[] keys = map.keySet().toArray(new String[0]);Arrays.sort(keys);StringBuffer reqStr = new StringBuffer();for(String key : keys){String v = map.get(key);if(v != null && !v.equals("")){reqStr.append(key).append("=").append(v).append("&");}}reqStr.append("key").append("=").append(WeiChartConfig.AppSercret);return WeiMd5.encode(reqStr.toString()).toUpperCase();}/*** 得到10 位的時間戳* 如果在JAVA上轉(zhuǎn)換為時間要在后面補上三個0 * @return*/public static String getTenTimes(){String t = new Date().getTime()+"";t = t.substring(0, t.length()-3);return t;}/*** 得到隨機字符串* @param length* @return*/public static String getRandomString(){int length = 32;String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";Random random = new Random();StringBuffer sb = new StringBuffer();for(int i = 0; i < length; ++i){int number = random.nextInt(62);//[0,62) sb.append(str.charAt(number));}return sb.toString();}/*** 得到本地機器的IP* @return*/private static String getHostIp(){String ip = "";try{ip = InetAddress.getLocalHost().getHostAddress();}catch(UnknownHostException e){e.printStackTrace();}return ip;}public static Map<String, String> getInfoByXml(String xmlStr){try{Map<String, String> m = new HashMap<String, String>();Document d = DocumentHelper.parseText(xmlStr);Element root = d.getRootElement();for ( Iterator<?> i = root.elementIterator(); i.hasNext(); ) {Element element = (Element) i.next();String name = element.getName();if(!element.isTextOnly()){//不是字符串 跳過。確定了微信放回的xml只有根目錄continue;}else{m.put(name, element.getTextTrim());}}//對返回結(jié)果做校驗.去除sign 字段再去加密String retSign = m.get("sign");m.remove("sign");String rightSing = getSign(m);if(rightSing.equals(retSign)){return m;}}catch(DocumentException e){// TODO Auto-generated catch blocke.printStackTrace();}return null; }/*** 將金額轉(zhuǎn)換成分* @param fee 元格式的* @return 分*/public static String changeToFen(Double fee){String priceStr = "";if(fee != null){int p = (int)(fee * 100); //價格變?yōu)榉謕riceStr = Integer.toString(p);}return priceStr;}}?這個是這里面使用的MD5加密方法
package com.cat.common.pay.weiChat;import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** MD5 算法 */ public class WeiMd5 {// 全局數(shù)組private final static String[] strDigits = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };// 返回形式為數(shù)字跟字符串private static String byteToArrayString(byte bByte) {int iRet = bByte;// System.out.println("iRet="+iRet);if (iRet < 0) {iRet += 256;}int iD1 = iRet / 16;int iD2 = iRet % 16;return strDigits[iD1] + strDigits[iD2];}// 轉(zhuǎn)換字節(jié)數(shù)組為16進制字串private static String byteToString(byte[] bByte) {StringBuffer sBuffer = new StringBuffer();for (int i = 0; i < bByte.length; i++) {sBuffer.append(byteToArrayString(bByte[i]));}return sBuffer.toString();}public static String encode(String strObj) {String resultString = null;try {resultString = new String(strObj);MessageDigest md = MessageDigest.getInstance("MD5");// md.digest() 該函數(shù)返回值為存放哈希值結(jié)果的byte數(shù)組try{resultString = byteToString(md.digest(strObj.getBytes("UTF-8")));}catch(UnsupportedEncodingException e){// TODO Auto-generated catch blocke.printStackTrace();}} catch (NoSuchAlgorithmException ex) {ex.printStackTrace();}return resultString;}}在微信支付的調(diào)試過程中,發(fā)現(xiàn)了一個困擾了很長時間的BUG,或者說是一個問題。
就是微信請求預(yù)支付的時候如果傳了中文,就是body中給的是中文,就會報body不是UTF-8格式。如果強行對字段進行編碼,又會報 加密錯誤。
但是這不是最主要的讓人困擾的地方,最讓我煩惱的是,我用本地的JDK調(diào)試的時候,它是OK 的。 但是用TOMCAT 部署的時候 卻一直都不行
在網(wǎng)上有很多的說法,有的說,對body 進行編碼轉(zhuǎn)換UTF-8,有的說對整個請求的XML,進行編碼。
還有的說編碼格式用統(tǒng)一的。iso900…等等,巴拉巴拉的。。
反正我都不行。
最后在大神的幫助下,慢慢梳理,對發(fā)送請求的post方法上面想辦法。
然后就是下面的 這句關(guān)鍵
小結(jié):很多人看了我的這篇文章后,就直接COPY了我的代碼去使用,然后在我之前發(fā)的版本中,有幾個生成XML 和 解析XML的 類是我自己封裝的JAR包,沒有放上來,就很多人找我,加我的QQ留言說 要我給源碼。其實那是很簡單的一些東西。沒必要那么復(fù)雜。
我的建議是 我的是一個啟發(fā)的DEMO。讓你能夠盡快的上手使用,但是你自己一定需要好好的去看官方的文檔,弄懂所有的流程,才能真正的掌握這個技巧。
原文鏈接:https://blog.csdn.net/walle167/article/details/50957503
總結(jié)
- 上一篇: elasticsearch启动常见错误
- 下一篇: 自旋锁使用场景和实现分析(转载)