涉及隐私关键参数未显示 参数都为必传参数 非必传参数涉及
为学微信支付饶了很多弯路、希望以此文章能给初接触微信支付的同学一些帮助,如有不对的地方,欢迎批评指正。
/**
-
微信支付无封装
-
@author sun
*/
public class MyWxMemberController extends WxWapBaseController{private static final Logger LOGGER = LoggerFactory.getLogger(WxActivityAdminController.class);
/**- 公众号id
/
// private static String appid=“xxx”;
private static String appid=“xxx”;
/* - 商户号
/
// private static String mch_id=“xxx”;
private static String mch_id=“xxx”;
/key为商户平台设置的密钥key/
// static String Key=“xxxx”;
static String Key=“xxx”;
/ - 设备号
/
private static String device_info=“1000”;
/* 商品描述*/
private static String body=“test”;
public void wechatpay() {
// 开始微信支付
//第一次签名
SortedMap<Object, Object> parameters = getPayParams(“xxxx”, “测试”, Util.generateOrderNo(new Date()), 10, “oS4qR1EhfNoUumJv__zAAcTQ3ocE”);
String respXML = sendPrepayRequest(“https://api.mch.weixin.qq.com/pay/unifiedorder”, parameters);
LOGGER.info(“xml====”, respXML);
Map<String, String> respMap = null;
try {
respMap = XmlUtil.doXMLParse(respXML);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (null == respMap) {
throw new RuntimeException(“解析xml失败!”);
}
String prepayId = respMap.get(“prepay_id”);
String prePay = “prepay_id=” + prepayId;// 第二次签名 SortedMap<Object, Object> payParameters = new TreeMap<>(); payParameters.put("appId", appid); payParameters.put("nonce_str", createNoncestr()); payParameters.put("package", prePay); payParameters.put("signType", "MD5"); payParameters.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000)); String paySign = creatSign(payParameters); Map<String, String> packageParams = getPackageParams(prepayId, paySign); String payJSON = JsonUtils.toJson(packageParams); setAttr("payjson", payJSON); // 支付调起页面 renderJsp("/npweb/wxpay/payment.jsp");
}
public void callback() throws JDOMException, IOException {
LOGGER.info(“业务订单支付回调…”);PublicTenpay tenpay = PublicTenpay.getInstance(); SortedMap<String, String> responseMap = tenpay.doPayNotify(getRequest()); // 回调业务逻辑处理
- 公众号id
// doTenpayNotify(responseMap);
renderText(tenpay.convertMap2Xml(responseMap), "text/xml");
}
//=---------------------------------------------------------
public Map<String, String> getPackageParams(String prepayId, String paySign) {
Map<String, String> packageParams = new HashMap<>(6);
packageParams.put("appId", appid);
packageParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
packageParams.put("nonceStr", String.valueOf(System.currentTimeMillis()));
packageParams.put("package", "prepay_id=" + prepayId);
packageParams.put("signType", "MD5");
packageParams.put("paySign", paySign);
return packageParams;
}
private String sendPrepayRequest(String url, SortedMap<Object, Object> parameters) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
String requestXml = convertMap2Xml(parameters);
LOGGER.info("Request XML: {}", requestXml);
// 避免汉字乱码导致请求失败,
StringEntity reqEntity = new StringEntity(requestXml, StandardCharsets.UTF_8.name());
// 设置类型
reqEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = getResponseContent(entity);
EntityUtils.consume(entity);
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 将Map转为XML
*/
public String convertMap2Xml(SortedMap<Object, Object> parameters) {
StringBuilder xml = new StringBuilder("<xml>");
Set<Map.Entry<Object, Object>> es = parameters.entrySet();
for (Map.Entry<Object, Object> entry : es) {
xml.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append("</").append(entry.getKey()).append(">");
}
xml.append("</xml>");
return xml.toString();
}
private String getResponseContent(HttpEntity entity) throws IOException {
if (null == entity) {
return null;
}
LOGGER.info("Response content length: {}", entity.getContentLength());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
LOGGER.info(line);
result.append(line);
}
return result.toString();
}
private SortedMap<Object,Object> getPayParams(String ip, String digest, String tradeNo, Integer price, String openId) {
SortedMap<Object, Object> parameters = new TreeMap<>();
parameters.put("appid", appid);
parameters.put("mch_id", mch_id);
parameters.put("device_info", device_info);
parameters.put("body", body);
parameters.put("nonce_str", createNoncestr());
parameters.put("trade_type", "JSAPI");
parameters.put("notify_url", "xxx");
parameters.put("total_fee", 10);
parameters.put("openid", openId);
parameters.put("spbill_create_ip", ip);
parameters.put("out_trade_no",tradeNo);
parameters.put("sign", creatSign(parameters));
return parameters;
}
public String getSign(){
SortedMap<Object, Object> parameters = new TreeMap<>();
// wxcfc21fb30650f8a3
parameters.put("appid",appid);
// 1538595811
parameters.put("mch_id",mch_id);
// WEB
parameters.put("device_info",device_info);
// test
parameters.put("body",body);
parameters.put("nonce_str","ibuaiVcKdpRxkhJA");
return creatSign(parameters);
}
private String creatSign(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator<?> it = es.iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");}
}
sb.append("key="+Key);
String sign = Md5Util.md5(sb.toString()).toUpperCase();
LOGGER.info("签名--------》"+sign);
return sign;
}
private String createNoncestr() {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder res = new StringBuilder();
for (int i = 0; i < 16; i++) {
Random rd = new Random();
res.append(chars.charAt(rd.nextInt(chars.length() - 1)));
}
return res.toString();
}
}