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

}

猜你喜欢

转载自blog.csdn.net/qq_28766679/article/details/84333361