package com.qxwljs.app.waiter.component.plugin.paymentWeixin;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.qxwljs.app.cms.payment.model.PayCfg;
import com.qxwljs.app.cms.payment.model.PayEnable;
import com.qxwljs.app.cms.payment.plugin.AbstractPaymentPlugin;
import com.qxwljs.app.cms.payment.plugin.IPaymentEvent;
import com.qxwljs.app.shop.core.order.model.Order;
import com.qxwljs.app.shop.core.order.service.IOrderManager;
import com.qxwljs.app.weixin.component.payment.plugin.WeixinUtil;
import com.qxwljs.framework.context.webcontext.ThreadContextHolder;
import com.qxwljs.framework.util.CurrencyUtil;
import com.qxwljs.framework.util.DateUtil;
import com.qxwljs.framework.util.StringUtil;
import com.qxwljs.jxp.SystemSetting;
import com.qxwljs.jxp.resource.model.JxpSite;
@Component
public class AppWeixinPaymentPlugin extends AbstractPaymentPlugin implements IPaymentEvent {
@Autowired
protected IOrderManager orderManager;
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public String onPay(PayCfg payCfg, PayEnable order) {
Map<String, String> cfgparams = paymentManager.getConfigParams(this.getId());
String mchid = cfgparams.get("mch_id");
String appid = cfgparams.get("appid");
String key = cfgparams.get("key");
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
Map params = new TreeMap();
params.put("appid", appid);
params.put("mch_id", mchid);
params.put("key", key);
String nonce_str = StringUtil.getRandStr(10);
params.put("nonce_str", nonce_str);
String original_sn=order.getSn();
String orderName = JxpSite.getInstance().getSitename();
String body = orderName+"订单["+ original_sn +"]";
// String body =original_sn ;
params.put("body", body);
String OrderNo=order.getSn()+StringUtil.getRandStr(6);//"20141104000003789253";
params.put("out_trade_no",OrderNo);
// 应付转为分
Double money = order.getNeedPayMoney();
params.put("total_fee", toFen(money));
params.put("spbill_create_ip", request.getRemoteAddr());
System.out.println("-----" + this.getCallBackUrl(payCfg, order));
params.put("notify_url", this.getCallBackUrl(payCfg, order));
params.put("trade_type", "APP");
String sign = WeixinUtil.createSign(params, key);
params.put("sign", sign);
String result = "";
String xml = "";
String re = params.toString();
try {
xml = WeixinUtil.mapToXml(params);
// System.out.println(xml);
// Document resultDoc = WeixinUtil.post(
// "https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
// Element rootEl = resultDoc.getRootElement();
// String return_code = rootEl.element("return_code").getText(); // 返回码
// if ("SUCCESS".equals(return_code)) {
//
// String result_code = rootEl.element("result_code").getText(); // 业务码
//
// if ("SUCCESS".equals(result_code)) {
// String prepay_id = rootEl.element("prepay_id").getText(); // 预支付订单id
//
// result = this.getPayScript(mchid,prepay_id, appid, key,original_sn,nonce_str);
//
// } else {
//
// String err_code = rootEl.element("err_code").getText();
// String err_code_des = rootEl.element("err_code_des").getText();
//
// result = "支付意外错误,请联系技术人员:"
// + err_code + "【"+err_code_des+"】'";
// }
// } else {
//
// if ("FAIL".equals(return_code)) {
// String return_msg = resultDoc.getRootElement()
// .element("return_msg").getText(); // 错误信息
// this.logger.error("微信端返回错误" + return_code + "["
// + return_msg + "]");
// this.logger.debug("-----------post xml-----------");
// this.logger.debug(xml);
// result = "'支付意外错误,请联系技术人员:" + return_code + " 【" + return_msg + "】'";
// }else {
// result = "'支付意外错误,请联系技术人员:" + return_code + "'";
// }
//
// }
} catch (RuntimeException e) {
this.logger.error("支付意外错误", e);
}
System.out.println(re);
return re;
}
private String toFen(Double money) {
money = CurrencyUtil.mul(money, 100);
BigDecimal bg=new BigDecimal(money);
String str = bg.toPlainString();
return str;
}
/**
* 获取wap的url
* @return
*/
public static String getWapDomainUrl(){
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
int port = request.getServerPort();
String portstr="";
if(port!=80){
portstr=":"+port;
}
String contextPath = request.getContextPath();
if(contextPath.equals("/")){
contextPath="";
}
String severname= SystemSetting.getWap_domain();
String url = "http://"+severname+portstr+contextPath;
return url;
}
/**
* 生成支付的脚本
*
* @param prepay_id
* 预支付订单id
* @return
*/
private String getPayScript(String partnerid,String prepay_id, String appid, String weixinkey,String original_sn,String nonce_str) {
Map<String, String> params = new TreeMap();
params.put("appId", appid);
params.put("partnerid", partnerid);
params.put("prepayid", prepay_id);
// params.put("nonceStr", StringUtil.getRandStr(10));
params.put("nonceStr", nonce_str);
params.put("timeStamp", String.valueOf(DateUtil.getDateline()));
params.put("package", "Sign=WXPay");
String sign = WeixinUtil.createSign(params, weixinkey);
params.put("sign", sign);
String result = WeixinUtil.mapToXml(params);
return result;
}
//成功后的回调
@Override
public String onCallBack(String ordertype) {
Map<String, String> cfgparams = paymentManager.getConfigParams(this
.getId());
String key = cfgparams.get("key");
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
Map map = new HashMap();
try {
SAXReader saxReadr = new SAXReader();
Document document = saxReadr.read(request.getInputStream());
/** 调试时可以打开下面注释 ,以观察通知的xml内容 **/
// String docstr = WeixinUtil.doc2String(document);
// this.logger.debug("--------post xml-------");
// this.logger.debug(docstr);
// this.logger.debug("--------end-------");
System.err.println("ordertype+"+ordertype);
Map<String, String> params = WeixinUtil.xmlToMap(document);
System.err.println("params+"+params);
String return_code = params.get("return_code");
String result_code = params.get("result_code");
System.err.println("return_code+"+return_code+"-----result_code---"+result_code);
if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
String ordersn = params.get("out_trade_no");
String total_fee = params.get("total_fee");
String sign = WeixinUtil.createSign(params, key);
if (sign.equals(params.get("sign"))) {
ordersn=ordersn.substring(0, ordersn.length()-6);
Order order = orderManager.get(ordersn);
if(order.getNeed_pay_money()<=Double.valueOf(total_fee)*0.01){
System.out.println("order.getNeed_pay_money()----"+order.getNeed_pay_money());
System.out.println("Integer.valueOf(total_fee)----"+Double.valueOf(total_fee));
System.out.println(order.getNeed_pay_money()<=Double.valueOf(total_fee)*0.01);
System.out.println("开始判断");
this.paySuccess(ordersn, "", "app",ordertype);
}else{
map.put("return_code", "FAIL");
map.put("return_msg", "");
}
map.put("return_code", "SUCCESS");
this.logger.debug("签名校验成功");
} else {
this.logger.debug("-----------签名校验失败---------");
this.logger.debug("weixin sign:" + params.get("sign"));
this.logger.debug("my sign:" + sign);
map.put("return_code", "FAIL");
map.put("return_msg", "参数错误");
}
} else {
map.put("return_code", "FAIL");
this.logger.debug("微信通知的结果为失败");
}
} catch (IOException e) {
map.put("return_code", "FAIL");
map.put("return_msg", "");
e.printStackTrace();
} catch (DocumentException e) {
map.put("return_code", "FAIL");
map.put("return_msg", "");
e.printStackTrace();
}
HttpServletResponse response = ThreadContextHolder.getHttpResponse();
response.setHeader("Content-Type", "text/xml");
return WeixinUtil.mapToXml(map);
}
@Override
public String onReturn(String ordertype) {
return null;
}
@Override
public String getId() {
return "appWeixinPaymentPlugin";
}
@Override
public String getName() {
return "微信APP支付";
}
}