如果出现签名错误请校验签名
地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=20_1
String mchid = mchid;// 商户id
String appid = appid;// 公众号appid
String key = key; // 商户key
String original_sn = sn;//订单号
String body = "网店订单[" + original_sn + "]";//商品名称
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
Map params = new TreeMap();
params.put("appid", appid);
params.put("mch_id", mchid);
params.put("nonce_str", StringUtil.getRandStr(10));//随机数
params.put("body", body);
params.put("out_trade_no", original_sn);
// 付款金额转为分
Double money = ;//
params.put("total_fee", toFen(money));//将付款金额转为分
params.put("spbill_create_ip", request.getRemoteAddr());//获取ip
params.put("notify_url", );//回调的url
params.put("trade_type", "JSAPI");
//获取openid
String openid = ;
params.put("openid", openid);
System.out.println("openid:"+openid);
String sign = WeixinUtil.createSign(params, key);//签名
params.put("sign", sign);
String result = "";
try {
String xml = WeixinUtil.mapToXml(params);//将结果拼装成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(prepay_id, appid, key,original_sn,bill.getTradeType());
} else {
String err_code = rootEl.element("err_code").getText();
String err_code_des = rootEl.element("err_code_des").getText();
result = "";
}
} else {
result = "";
if ("FAIL".equals(return_code)) {
String return_msg = resultDoc.getRootElement()
.element("return_msg").getText(); // 错误信息
}
}
} catch (Exception e) {
this.logger.error("微信生成支付二维码错误", e);
return "二维码生成错误";
}
return result;
public static String getRandStr(int n) {
Random random = new Random();
String sRand = "";
for (int i = 0; i < n; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
}
return sRand;
}
protected String toFen(Double money) {
String value = BigDecimal.valueOf(money).multiply(new BigDecimal(100)).toString();
NumberFormat numberFormat = new DecimalFormat("##");
return numberFormat.format(new BigDecimal(value));
}
/**
* 生成签名
*
* @param params
* 参数map
* @param key
* 支付key(API密钥)
* @return
*/
public static String createSign(Map params, String key) {
String url = createLinkString(params);
url = url + "&key=" + key;
String sign = DigestUtils.md5Hex(url).toUpperCase();
return sign;
}
public static String createLinkString(Map params) {
List keys = new ArrayList(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if("sign".equals(key)){
continue;
}
if ("".equals(prestr)) {// 拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr +"&" +key + "=" + value ;
}
}
return prestr;
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
try {
writer.close();
}
catch (Exception ex) {
}
return output;
}
public static Document post(String wsPart, String doc_str) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(wsPart);
HttpEntity requestEntity = new StringEntity(doc_str,"UTF-8");
httppost.setEntity(requestEntity);
httppost.setHeader(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity rentity = httpresponse.getEntity();
InputStream in = rentity.getContent();
if (in != null) {
SAXReader reader = new SAXReader();
Document doc = reader.read(in);
return doc;
} else {
throw new RuntimeException("post uri[" + wsPart
+ "]发生错误:[stream 返回Null]");
}
} catch (Throwable e) {
throw new RuntimeException("post uri [" + wsPart + "]发生错误", e);
}
}