/**
* 调用统一下单,获得下单结果
*
* @return 统一下单结果
* @throws WxPayException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws NoSuchAlgorithmException
* @throws org.xml.sax.SAXException
* openid 用户标识
* total_fee 标价金额
* @失败时抛异常WxPayException
*/
public WxPayData GetUnifiedOrderResult(String openid, String total_fee, String orderid)
throws WxPayException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException,
org.xml.sax.SAXException {
// 统一下单
WxPayData data = new WxPayData();
Order order = new Order();
if(StringUtils.isNotBlank(orderid)){
Order order1 = new Order();
order1.setOrderno(orderid);
order = orderService.getByOrderNo(order1);
}else{
order.setShopname("零售商品");
}
data.SetValue("body", order.getShopname());
data.SetValue("attach", "微信支付");
if(StringUtils.isBlank(orderid)){
orderid = WxPayApi.GenerateOutTradeNo();
}
data.SetValue("out_trade_no", orderid);
data.SetValue("total_fee", total_fee);
data.SetValue("goods_tag", "test");
data.SetValue("trade_type", "JSAPI");
data.SetValue("openid", openid);
WxPayData result = WxPayApi.UnifiedOrder(data, 0);
if (!result.IsSet("appid") || !result.IsSet("prepay_id")
|| result.GetValue("prepay_id").toString().equalsIgnoreCase("")) {
Log.error("UnifiedOrder response error!");
throw new WxPayException("UnifiedOrder response error!");
}
return result;
}
/**
*
* 统一下单
*
* @param WxPaydata
* inputObj 提交给统一下单API的参数
* @param int timeOut 超时时间
* @throws WxPayException
* @return 成功时返回,其他抛异常
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut)
throws WxPayException, NoSuchAlgorithmException,
ParserConfigurationException, SAXException, IOException {
timeOut = (timeOut == 0 ? 6 : timeOut);
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
// 检测必填参数
if (!inputObj.IsSet("out_trade_no")) {
throw new WxPayException("缺少统一支付接口必填参数out_trade_no!");
} else if (!inputObj.IsSet("body")) {
throw new WxPayException("缺少统一支付接口必填参数body!");
} else if (!inputObj.IsSet("total_fee")) {
throw new WxPayException("缺少统一支付接口必填参数total_fee!");
} else if (!inputObj.IsSet("trade_type")) {
throw new WxPayException("缺少统一支付接口必填参数trade_type!");
}
// 关联参数
if (inputObj.GetValue("trade_type").toString()
.equalsIgnoreCase("JSAPI")
&& !inputObj.IsSet("openid")) {
throw new WxPayException(
"统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
}
if (inputObj.GetValue("trade_type").toString()
.equalsIgnoreCase("NATIVE")
&& !inputObj.IsSet("product_id")) {
throw new WxPayException(
"统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
}
// 异步通知url未设置,则使用配置文件中的url
if (!inputObj.IsSet("notify_url")) {
inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);// 异步通知url
}
inputObj.SetValue("appid", WxPayConfig.APPID);// 公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);// 商户号
inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);// 终端ip
inputObj.SetValue("nonce_str", GenerateNonceStr());// 随机字符串
// 签名
inputObj.SetValue("sign", inputObj.MakeSign("MD5"));
String xml = inputObj.ToXml();
long start = System.currentTimeMillis();
Log.debug("UnfiedOrder request : " + xml);
String response = HttpService.Post(xml, url, false, timeOut);
Log.debug("UnfiedOrder response : " + response);
long end = System.currentTimeMillis();
int timeCost = (int) ((end - start));
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);// 测速上报
return result;
}
//微信统一下单支付发送信息给微信服务端进行支付
public static String Post(String xml, String url, boolean isUseCert,
int timeout) throws WxPayException {
System.gc(); // 垃圾回收,回收没有正常关闭的http连接
String result = "";// 返回结果
HttpURLConnection request = null;
InputStream response = null;
OutputStream reqStream = null;
try {
/***************************************************************
* 下面设置HttpWebRequest的相关属性
* ************************************************************/
if (url.toLowerCase().startsWith("https")) {
HttpsURLConnection httpsRequest = (HttpsURLConnection) new URL(
url).openConnection();
// 是否使用证书
if (isUseCert) {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new Cert().getClass().getResourceAsStream(
WxPayConfig.SSLCERT_PATH),
WxPayConfig.SSLCERT_PASSWORD.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, WxPayConfig.SSLCERT_PASSWORD.toCharArray());
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(kmf.getKeyManagers(), null, null);
httpsRequest.setSSLSocketFactory(sc.getSocketFactory());
}
request = httpsRequest;
} else {
request = (HttpURLConnection) new URL(url).openConnection();
}
Log.info("请求连接:"+request);
request.setRequestMethod("POST");
request.setDoOutput(true);
request.setConnectTimeout(timeout * 1000);
// 设置POST的数据类型和长度
request.addRequestProperty("Content-Type", "text/xml");
byte[] data = xml.getBytes("UTF-8");
// 往服务器写入数据
reqStream = request.getOutputStream();
reqStream.write(data, 0, data.length);
// 获取服务端返回
response = request.getInputStream();
StringBuffer sb = new StringBuffer();
byte[] d = new byte[1024];
int chunk = 0;
while ((chunk = response.read(d)) != -1) {
sb.append(new String(d, 0, chunk, "UTF-8"));
}
result = sb.toString();
} catch (Exception e) {
Log.error(e.toString());
throw new WxPayException(e.toString());
} finally {
// 关闭连接和流
if (reqStream != null) {
try {
reqStream.close();
} catch (IOException e) {
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
return result;
}