Java微信H5支付實際例子
最近看過不少微信H5支付的例子,我是根據這個網址來配置的:https://blog.csdn.net/leigelg/article/details/80456758 這裡已經說的很明白,就是在支付的時候老是提示“網路環境未能通過安全驗證,請稍後重試”後來發現真是IP地址問題,這是我實際專案的程式碼。
//這裡是支付的Controller 用的是spingmvc
@SecurityMapping(display = false, rsequence = 0, title = “wap訂單支付”, value = “/wxwap_submit.htm*”, rtype = “buyer”, rname = “購物流程3”, rcode = “goods_cart”, rgroup = “線上購物”)
@RequestMapping(value = “/pay_submit.htm”,produces=“text/html; charset=UTF-8”)
public String paymentSubmit(HttpServletRequest request,
HttpServletResponse response, String payType, String order_id) {
OrderForm of = this.orderFormService.getObjById(CommUtil.null2Long(order_id)); if (of != null && of.getOrder_status() == 10) { List payments = new ArrayList(); Map params = new HashMap(); // 1為平臺支付: if (this.configService.getSysConfig().getConfig_payment_type() == 1) { params.put("mark", payType); params.put("type", "admin"); payments = this.paymentService.query("select obj from Payment obj where obj.mark=:mark and obj.type=:type", params, -1, -1); } else { params.put("store_id", of.getStore().getId()); params.put("mark", payType); payments = this.paymentService.query("select obj from Payment obj where obj.mark=:mark and obj.store.id=:store_id", params, -1, -1); } // 支付方式已經配置:wap支援支付寶wap支付以及微信公眾號支付 if (payments.size() > 0) { of.setPayment((Payment) payments.get(0)); this.orderFormService.update(of); // 微信公眾號支付weixin_wap if (payType.equals("weixin_wap")) { //以下程式碼才是重點 Map<String, Object> result = new HashMap<String, Object>(); result.put("success", false); try { // 付款金額,必填 String total_fee = request.getParameter("WIDtotal_fee"); // ip地址獲取 這個地方不知道是不是因為寫了轉發分流的原因導致不能使用request.getServerName()。 //也不能寫域名,不知道是不是騰訊直接用IP。 String basePath = "伺服器IP地址:" + request.getServerPort(); // 賬號資訊 String appid = of.getPayment().getWeixin_appId(); // appid String mch_id = of.getPayment().getWeixin_partnerId(); // 商業號 String key = Payment.getWeixin_partnerKey(); // key //訂單號 order_id = request.getParameter("order_id"); String order_id1 = request.getParameter("order_id1"); String currTime = PayCommonUtil.getCurrTime(); String strTime = currTime.substring(8, currTime.length()); String strRandom = PayCommonUtil.buildRandom(4) + ""; String nonce_str = strTime + strRandom; // 價格 注意:價格的單位是分 String order_price = new BigDecimal(total_fee).multiply(new BigDecimal(100)).toString().split("\\.")[0]; // 自己網站上的訂單號 String out_trade_no = order_id1; // 獲取發起電腦 ip ,這個IP地址如果獲取不到 就直接寫127.0.0.1 String spbill_create_ip = HttpUtil.getRealIp(request); // 回撥介面 String userName = request.getParameter("shopuername"); User user = userService.getObjByProperty("userName",userName); String notify_url = Payment.getNOTIFY_URL_H5().replaceAll("localhostUrl", basePath) + user.getId(); // 頁面跳轉同步通知頁面路徑 String trade_type = "MWEB"; // 設定package訂單引數 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("out_trade_no", out_trade_no); packageParams.put("total_fee", order_price); packageParams.put("spbill_create_ip", spbill_create_ip); packageParams.put("notify_url", notify_url); packageParams.put("trade_type", trade_type); packageParams.put("body", Payment.getWeixin_paySignKey() + "-" + request.getParameter("order_des")); packageParams.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"wap網站地址,必須可以訪問到\",\"wap_name\": \"你的網站名稱\"}}"); String sign = PayCommonUtil.createSign("UTF-8", packageParams, key); packageParams.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(packageParams); String resXml = HttpUtil.postData(Payment.getUFDODER_URL(), requestXML); Map map = XMLUtil.doXMLParse(resXml); String urlCode = (String) map.get("code_url"); //確認支付過後跳的地址,需要經過urlencode處理,這裡如果寫了首頁 直接就跳轉到了首頁,而改成下面的訂單地址就能返回訂單???? String urlString = URLEncoder.encode("http://www.****.com/buyer/order.htm", "UTF-8"); String mymweb_url = map.get("mweb_url").toString(); String mweb_url = mymweb_url+"&redirect_url="+urlString; response.sendRedirect(mweb_url); logger.info("before ----"); result.put("sHtmlText", urlCode); result.put("success", true); } catch (Exception e) { logger.info("微信H5支付錯誤資訊:"+e); result.put("errormsg", e.getMessage()); } } else { // 支付方式未配置 return "redirect:" + CommUtil.getURL(request) + "/index.htm?noPayMethod"; } } else { // 該訂單狀態不正確,不能進行付款! return "redirect:" + CommUtil.getURL(request) + "/index.htm?orderError"; } return null;
}
HttpUtil類
package com.***.***.***.util;
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 javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
/**
- Http客戶端工具類
- 這是內部呼叫類,請不要在外部呼叫。
- @author miklchen
*/
public class HttpUtil {
private final static int CONNECT_TIMEOUT = 5000;
private final static String DEFAULE_ENCODING = "UTF-8";
public static String postData(String urlStr, String data) {
return postData(urlStr, data, null);
}
private static String postData(String urlStr, String data, String contentType) {
// TODO Auto-generated method stub
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(), DEFAULE_ENCODING);
if (data ==null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULE_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){
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
/**
* 獲取真實ip地址 通過阿帕奇代理的也能獲取到真實ip
* @param request
* @return
*/
public static String getRealIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip != null) {
if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
int index = ip.indexOf(",");
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
}
}
ip = request.getHeader("X-Real-IP");
if (ip != null) {
if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
}
ip = request.getHeader("Proxy-Client-IP");
if (ip != null) {
if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
}
ip = request.getHeader("WL-Proxy-Client-IP");
if (ip != null) {
if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
}
ip = request.getRemoteAddr();
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
}