微信H5支付demo

近来对支付来点兴趣,搞了一个微信H5的支付demo供大家参考一下。

@RequestMapping(value ="/H5",method = {RequestMethod.POST,RequestMethod.GET})

public String H5(){
return "text_jsp/h5";//微信订单的页面
}


/**
 * 微信H5 支付
 * 注意:必须再web页面中发起支付且域名已添加到开发配置中
 * @throws DocumentException 
 * @throws IOException 
 */


@RequestMapping(value ="/H5Pay",method = {RequestMethod.POST,RequestMethod.GET})
public void H5Pay(HttpServletRequest request,HttpServletResponse response,String ip) throws IOException, DocumentException{
String value =  String.valueOf(System.currentTimeMillis());//随机生成的微信订单号
SortedMap<String, String> packageParams = new TreeMap<String, String>();
String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");//生成随机32位字符串
String spbill_create_ip = request.getRemoteAddr();//获取客户端的IP,在没有转发的情况下可以用这个获取IP,转发了就不可以了!
        String khdIP = getIpAddr(request);//转发获取客户端IP的方法
packageParams.put("appid", appID);// 公众账号ID
packageParams.put("body", "美人");//商品描述
packageParams.put("mch_id", mchID);//商户号
packageParams.put("nonce_str", nonce_str);//随机字符串
packageParams.put("out_trade_no", value);//订单号
packageParams.put("total_fee", "1");//金额
packageParams.put("spbill_create_ip",khdIP);//客户端IP
packageParams.put("notify_url", h5_notify_url);//回调函数
packageParams.put("trade_type", "MWEB");  //支付类型,H5是MWEB类型
packageParams.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://g.lotut.com\",\"wap_name\": \"美人\"}}");//场景信息
RequestHandler reqHandler = new RequestHandler(request, response);
reqHandler.init(appID, secret, partnerKey);
String sign = reqHandler.createSign(packageParams);//获取微信签名
Map<Object, Object> params =new HashMap<Object,Object>();
params.put("appid",appID );//同上
params.put("body", "美人");
params.put("mch_id", mchID);
params.put("nonce_str", nonce_str);
params.put("out_trade_no",value);
params.put("total_fee","1" );
params.put("spbill_create_ip",khdIP);
params.put("notify_url", h5_notify_url);
params.put("trade_type", "MWEB");
params.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://g.lotut.com\",\"wap_name\": \"美人\"}}");
params.put("sign", sign);//添加签名
String xmlStr = WePayInfo.getRequestXml(params);//封装成XML的格式
String responseXml = HttpUtil.excutePostRequest(WePayInfo.INTERFACE_URL, xmlStr);//转发到微信统一下单的接口
Map<String, String> resultMap = WeixinXmlParse.xmlParse(responseXml);//解析微信返回的结果集
String return_code = resultMap.get("return_code");
String return_msg = resultMap.get("return_msg");
if (!PaymentKit.codeIsOK(return_code)) {
log.error("return_code>"+return_code+" return_msg>"+return_msg);
throw new RuntimeException(return_msg);
}
String result_code = resultMap.get("result_code");
if (!PaymentKit.codeIsOK(result_code)) {
log.error("result_code>"+result_code+" return_msg>"+return_msg);
throw new RuntimeException(return_msg);
}
String prepay_id = resultMap.get("prepay_id");
String mweb_url = resultMap.get("mweb_url")+"&redirect_url=https%3A%2F%2Fwww.baidu.com";//后面是添加的回调页面
try {
response.sendRedirect(mweb_url);//转发到微信的支付页面
} catch (IOException e) {
e.printStackTrace();
}
}


@RequestMapping(value = "/pay_notify",method={RequestMethod.POST,RequestMethod.GET})
public String pay_notify(HttpServletRequest request) {
String xmlMsg = HttpKit.readData(request);
Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
String result_code  = params.get("result_code");
// String openId      = params.get("openid");
// //交易类型
// String trade_type      = params.get("trade_type");
// //付款银行
// String bank_type      = params.get("bank_type");
// // 总金额
// String total_fee     = params.get("total_fee");
// //现金支付金额
// String cash_fee     = params.get("cash_fee");
// // 微信支付订单号
// String transaction_id      = params.get("transaction_id");
// // 商户订单号
String out_trade_no      = params.get("out_trade_no");
// // 支付完成时间,格式为yyyyMMddHHmmss
// String time_end      = params.get("time_end");

/以下是附加参数///

String attach      = params.get("attach");
// String fee_type      = params.get("fee_type");
// String is_subscribe      = params.get("is_subscribe");
// String err_code      = params.get("err_code");
// String err_code_des      = params.get("err_code_des");
// 注意重复通知的情况,同一订单号可能收到多次通知,请注意一定先判断订单状态
// 避免已经成功、关闭、退款的订单被再次更新
// Order order = Order.dao.getOrderByTransactionId(transaction_id);
// if (order==null) {
WxPayApiConfigKit.setThreadLocalWxPayApiConfig(getApiConfig());
if(PaymentKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey())){
if (("SUCCESS").equals(result_code)) {
//更新订单信息
//内部订单处理逻辑
//发送通知等
System.out.println("订单已经完成=======================================================");
Map<String, String> xml = new HashMap<String, String>();
xml.put("return_code", "SUCCESS");
xml.put("return_msg", "OK");
return PaymentKit.toXml(xml);
}
}
// }

return null;
}


/** 
 * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址, 
 * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值 
 *  
 * @return ip
 */
private String getIpAddr(HttpServletRequest request) {
   String ip = request.getHeader("x-forwarded-for"); 
   System.out.println("x-forwarded-for ip: " + ip);
   if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {  
       // 多次反向代理后会有多个ip值,第一个ip才是真实ip
       if( ip.indexOf(",")!=-1 ){
           ip = ip.split(",")[0];
       }
   }  
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
       ip = request.getHeader("Proxy-Client-IP");  
       System.out.println("Proxy-Client-IP ip: " + ip);
   }  
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
       ip = request.getHeader("WL-Proxy-Client-IP");  
       System.out.println("WL-Proxy-Client-IP ip: " + ip);
   }  
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
       ip = request.getHeader("HTTP_CLIENT_IP");  
       System.out.println("HTTP_CLIENT_IP ip: " + ip);
   }  
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
       ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
       System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
   }  
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
       ip = request.getHeader("X-Real-IP");  
       System.out.println("X-Real-IP ip: " + ip);
   }  
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
       ip = request.getRemoteAddr();  
       System.out.println("getRemoteAddr ip: " + ip);
   } 
   System.out.println("获取客户端ip: " + ip);
   return ip;  
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页