(Notice:以下所有經(jīng)驗也是我根據(jù)網(wǎng)上的經(jīng)驗整理的秀存,如有侵權(quán)可以聯(lián)系我刪除羔杨,Wx:IT_Ezra,QQ 654303408窿吩。 有問題討論也可聯(lián)系我茎杂,QQ同上。)
(Tips:我是第一次開發(fā)纫雁,一個剛畢業(yè)的java工程師煌往,我覺得我并非天賦異稟,我能學(xué)會轧邪,相信聰敏的你刽脖,一定可以)
(PS:目前微信擁有無可撼動的人口基數(shù),越來越多的項目開發(fā)是基于微信小程序忌愚,或者APP曲管。但是支付方式無非兩種,一種是支付寶硕糊,一種是微信支付院水。那么我們來了解一下微信支付。(首先去讀5遍微信支付開發(fā)文檔简十,地址https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1)檬某,了解原理以及它的過程和參數(shù)列表。)
Controller類
@RestController
@RequestMapping("")
public class PayController {
@RequestMapping(value = "/wxPay", method = RequestMethod.POST)
public JSONObject wxPay(HttpServletRequest request) {
try {
//生成的隨機字符串
String nonce_str = getRandomStringByLength(32);
//商品名稱
String body = "測試商品名稱";
//獲取客戶端的ip地址
String spbill_create_ip = getIpAddr(request);
//組裝參數(shù)勺远,用戶生成統(tǒng)一下單接口的簽名
Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid", WechatConfig.appid);
packageParams.put("mch_id", WechatConfig.mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", body);
packageParams.put("out_trade_no", payOrderId + "");//商戶訂單號,自己的訂單ID
packageParams.put("total_fee", 100 + "");//支付金額橙喘,這邊需要轉(zhuǎn)成字符串類型,否則后面的簽名會失敗
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", WechatConfig.notify_url);//支付成功后的回調(diào)地址
packageParams.put("trade_type", WechatConfig.TRADETYPE);//支付方式
packageParams.put("openid", openId + "");//用戶的openID胶逢,自己獲取
String prestr = PayUtil.createLinkString(packageParams); // 把數(shù)組所有元素厅瞎,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串
//MD5運算生成簽名,這里是第一次簽名初坠,用于調(diào)用統(tǒng)一下單接口
String mysign = PayUtil.sign(prestr, WechatConfig.key, "utf-8").toUpperCase();
//拼接統(tǒng)一下單接口使用的xml數(shù)據(jù)和簸,要將上一步生成的簽名一起拼接進(jìn)去
String xml = "<xml>" + "<appid>" + WechatConfig.appid + "</appid>"
+ "<body><![CDATA[" + body + "]]></body>"
+ "<mch_id>" + WechatConfig.mch_id + "</mch_id>"
+ "<nonce_str>" + nonce_str + "</nonce_str>"
+ "<notify_url>" + WechatConfig.notify_url + "</notify_url>"
+ "<openid>" + openid + "</openid>"
+ "<out_trade_no>" + payOrderId + "</out_trade_no>"
+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
+ "<total_fee>" + 100 + "</total_fee>"http://支付的金額,單位:分
+ "<trade_type>" + WechatConfig.TRADETYPE + "</trade_type>"
+ "<sign>" + mysign + "</sign>"
+ "</xml>";
//調(diào)用統(tǒng)一下單接口碟刺,并接受返回的結(jié)果
String result = PayUtil.httpRequest(WechatConfig.pay_url, "POST", xml);
// 將解析結(jié)果存儲在HashMap中
Map map = PayUtil.doXMLParse(result);
String return_code = (String) map.get("return_code");//返回狀態(tài)碼
String result_code = (String) map.get("result_code");//返回狀態(tài)碼
Map<String, Object> response = new HashMap<String, Object>();//返回給小程序端需要的參數(shù)
if (return_code == "SUCCESS" && return_code.equals(result_code)) {
String prepay_id = (String) map.get("prepay_id");//返回的預(yù)付單信息
response.put("nonceStr", nonce_str);
response.put("package", "prepay_id=" + prepay_id);
Long timeStamp = System.currentTimeMillis() / 1000;
response.put("timeStamp", timeStamp + "");//這邊要將返回的時間戳轉(zhuǎn)化成字符串锁保,不然小程序端調(diào)用wx.requestPayment方法會報簽名錯誤
//拼接簽名需要的參數(shù)
String stringSignTemp = "appId=" + WechatConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
//再次簽名,這個簽名用于小程序端調(diào)用wx.requesetPayment方法
String paySign = PayUtil.sign(stringSignTemp, WechatConfig.key, "utf-8").toUpperCase();
response.put("paySign", paySign);
}
response.put("appid", WechatConfig.appid);
return Response.succ(response);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//這里是支付回調(diào)接口半沽,微信支付成功后會自動調(diào)用
@RequestMapping(value = "/wxNotify", method = RequestMethod.POST)
public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
//sb為微信返回的xml
String notityXml = sb.toString();
String resXml = "";
Map map = PayUtil.doXMLParse(notityXml);
String returnCode = (String) map.get("return_code");
if ("SUCCESS".equals(returnCode)) {
//驗證簽名是否正確
Map<String, String> validParams = PayUtil.paraFilter(map); //回調(diào)驗簽時需要去除sign和空值參數(shù)
String prestr = PayUtil.createLinkString(validParams);
//根據(jù)微信官網(wǎng)的介紹爽柒,此處不僅對回調(diào)的參數(shù)進(jìn)行驗簽,還需要對返回的金額與系統(tǒng)訂單的金額進(jìn)行比對等
if (PayUtil.verify(prestr, (String) map.get("sign"), WechatConfig.key, "utf-8")) {
/**此處添加自己的業(yè)務(wù)邏輯代碼start**/
//注意要判斷微信支付重復(fù)回調(diào)者填,支付成功后微信會重復(fù)的進(jìn)行回調(diào)
/**此處添加自己的業(yè)務(wù)邏輯代碼end**/
//通知微信服務(wù)器已經(jīng)支付成功
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> ";
}
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
}
/* 訂單查詢函數(shù) 浩村。有待細(xì)化
@ResponseBody
@RequestMapping("orderQuery")
public OrderQueryResult orderQuery(HttpServletRequest request, HttpServletResponse response) throws Exception {
OrderQueryResult orderQueryResult = null;
OrderQueryParams orderQueryParams = new OrderQueryParams();
orderQueryParams.setAppid(WechatConfig.APP_ID);
orderQueryParams.setMch_id(WechatConfig.MCH_ID);
orderQueryParams.setNonce_str(PayUtil.createNonceStr());
orderQueryParams.setTransaction_id(""); //二者選其一,推薦transaction_id
//orderQueryParams.setOut_trade_no("");
//請求的xml
String orderQueryXml = wechatPayService.abstractPayToXml(orderQueryParams);//簽名合并到service
// 返回<![CDATA[SUCCESS]]>格式的XML
String orderQueryResultXmL = HttpReqUtil.HttpsDefaultExecute(HttpReqUtil.POST_METHOD,WechatConfig.ORDER_QUERY_URL, null, orderQueryXml);
// 進(jìn)行簽名校驗
if (SignatureUtil.checkIsSignValidFromWeiXin(orderQueryResultXmL)) {
orderQueryResult = XmlUtil.getObjectFromXML(orderQueryResultXmL, OrderQueryResult.class);
}
return orderQueryResult;
}
*/
//獲取隨機字符串
private 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();
}
//獲取IP
private String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
//多次反向代理后會有多個ip值占哟,第一個ip才是真實ip
int index = ip.indexOf(",");
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
return request.getRemoteAddr();
}
}
上面代碼用到了PayUtil和WechatConfig這兩個類心墅,一個是配置類酿矢,一個是工具類,代碼如下:
public class PayUtil {
/**
* 簽名字符串
*
* @param text 需要簽名的字符串
* @param key 密鑰
* @param input_charset 編碼格式
* @return 簽名結(jié)果
*/
public static String sign(String text, String key, String input_charset) {
text = text + "&key=" + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 簽名字符串
*
* @param text 需要簽名的字符串
* @param sign 簽名結(jié)果
* @param key 密鑰
* @param input_charset 編碼格式
* @return 簽名結(jié)果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if (mysign.equals(sign)) {
return true;
} else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws java.security.SignatureException
* @throws UnsupportedEncodingException
*/
public static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5簽名過程中出現(xiàn)錯誤,指定的編碼集不對,您目前指定的編碼集是:" + charset);
}
}
private static boolean isValidChar(char ch) {
if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
return true;
if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
return true;// 簡體中文漢字編碼
return false;
}
/**
* 除去數(shù)組中的空值和簽名參數(shù)
*
* @param sArray 簽名參數(shù)組
* @return 去掉空值與簽名參數(shù)后的新簽名參數(shù)組
*/
public static Map<String, String> paraFilter(Map<String, String> sArray) {
Map<String, String> result = new HashMap<String, String>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
|| key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把數(shù)組所有元素排序怎燥,并按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串
*
* @param params 需要排序并參與字符拼接的參數(shù)組
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接時瘫筐,不包括最后一個&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
* @param requestUrl 請求地址
* @param requestMethod 請求方法
* @param outputStr 參數(shù)
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
// 創(chuàng)建SSLContext
StringBuffer buffer = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//往服務(wù)器端寫內(nèi)容
if (null != outputStr) {
OutputStream os = conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
// 讀取服務(wù)器端返回的內(nèi)容
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 解析xml,返回第一級元素鍵值對。如果第一級元素有子節(jié)點铐姚,則此節(jié)點的值是子節(jié)點的xml數(shù)據(jù)策肝。
*
* @param strxml
* @return
* @throws org.jdom2.JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws Exception {
if (null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = String2Inputstream(strxml);
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 = getChildrenText(children);
}
m.put(k, v);
}
//關(guān)閉流
in.close();
return m;
}
/**
* 獲取子結(jié)點的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(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
public static InputStream String2Inputstream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
}
WechatConfig
public class WechatConfig {
//小程序appid 開發(fā)者自己擁有的
public static final String appid = "";
//微信支付的商戶id 開發(fā)者去問自己id的前端同事或者領(lǐng)導(dǎo)。
public static final String mch_id = "";
//微信支付的商戶密鑰 開發(fā)者問領(lǐng)導(dǎo)隐绵,去微信商戶平臺去申請(要下插件等等)
public static final String key = "";
//支付成功后的服務(wù)器回調(diào)url驳糯,這里填PayController里的回調(diào)函數(shù)地址
public static final String notify_url = "";
//簽名方式,固定值
public static final String SIGNTYPE = "MD5";
//交易類型氢橙,小程序支付的固定值為JSAPI
public static final String TRADETYPE = "JSAPI";
//微信統(tǒng)一下單接口地址
public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
}
實現(xiàn)這些就已經(jīng)可以支付了酝枢。其中有一些要注意的地方:
1.我們一般會在外網(wǎng)調(diào)試,而回調(diào)函數(shù)是需要在外網(wǎng)訪問的悍手。所以帘睦,如果不發(fā)布到外網(wǎng),是無法對回調(diào)函數(shù)進(jìn)行測試(但是能夠支付)坦康。
2.XML文件配置順序一定要按順序竣付,網(wǎng)上有很多順序列表。并且也有很多種關(guān)于XML解析的方法滞欠,我這只是其中的一種古胆。
3.回調(diào)函數(shù)的地址 根據(jù)自己的框架來實現(xiàn),有springMVC的筛璧,有Struts的逸绎,我是使用的springMVC。URL不同夭谤,可以網(wǎng)上參考棺牧,相信你自己一定也會寫。
4.目前訂單查詢函數(shù)還沒有完全細(xì)化朗儒。 To be continue.....