废话不多说直接上代码:
调用类:
public class WeixinPayClient{
Logger log = Logger.getLogger(WeixinPayClient.class);
private static final String WEIXIN_APPID = " ";
private static final String WEIXIN_MCHID = " ";
private static final String WXPAY_APIKEY = "";
private static final String WEIXIN_API = "https://api.mch.weixin.qq.com";
private static final String APP_NAME = "";
private static final String SERVICEIP = " ";
private static final String WEIXIN_NOTIFY = "";//业务回调地址
public static final WeixinPayClient instance = new WeixinPayClient();
private static final String ORDERQUERY = "/pay/orderquery";
private static final String UNIFIEDORDER = "/pay/unifiedorder";
private static final String REFUND = "/secapi/pay/refund";
private static final String charset = "UTF-8";
private static final String PATH = "";//证书路径
public static WeixinPayClient getInstance()
{
return instance;
}
@SuppressWarnings("rawtypes")
public boolean verif(String escOrderId, String state)
{
TreeMap<String, String> params = new TreeMap();
params.put("appid", WEIXIN_APPID);
params.put("mch_id", WEIXIN_MCHID);
params.put("nonce_str", RandomUtils.getNumCode(6));
params.put("out_trade_no", escOrderId);
params.put("sign", sign(params,WXPAY_APIKEY));
String body = buildParam(params);
HttpClient client = new HttpClient();
String resultStr = client.post("https://api.mch.weixin.qq.com/pay/orderquery", body, "UTF-8");
TreeMap<String, String> resultParams = checkSign(resultStr, WXPAY_APIKEY);
String trade_state = (String)resultParams.get("trade_state");
return (StringUtils.isNotEmpty(trade_state)) && (trade_state.equals(state));
}
public static void main(String[] args)
{
getInstance().refund(" ", 0.01, 0.01);
}
/**
* 证书退款
*
* @param escOrderId
* @param payAmount
* @param refundAmount
*/
public void refund(String escOrderId, Double payAmount, Double refundAmount) {
// 设置参数
TreeMap<String, String> params = new TreeMap<>();
//公众账号ID
params.put("appid", WEIXIN_APPID);
//商户号
params.put("mch_id", WEIXIN_MCHID);
//随机字符串
String rands = RandomUtils.getNumCode(32);
params.put("nonce_str", rands);
//商户订单号
// params.put("out_trade_no", escOrderId);
params.put("transaction_id", escOrderId);
//商户退款单号
String rands1 = RandomUtils.getNumCode(32);
params.put("out_refund_no",rands1);
//订单金额
params.put("total_fee", String.valueOf((int) (payAmount.doubleValue() * 100)));
//退款金额
params.put("refund_fee", String.valueOf((int) (refundAmount.doubleValue() * 100)));
//params.put("op_user_id", ConfigConts.WEIXIN_MCHID);
//签名
//params.put("sign", sign(params, ConfigConts.WXPAY_APIKEY));
CloseableHttpClient httpclient =null;
try {
//指定读取证书格式为PKCS12
KeyStore keyStore = KeyStore.getInstance("PKCS12");
//读取本机存放的PKCS12证书文件
FileInputStream instream = new FileInputStream(new File(PATH));
try {
//指定PKCS12的密码(商户ID)
keyStore.load(instream, "1494494902".toCharArray());
} finally {
instream.close();
}
//信任自己的CA和自签名证书
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WEIXIN_MCHID .toCharArray()).build();
//指定TLS版本
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//设置httpclient的SSLSocketFactory
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
com.yscoco.seveng.common.utils.Log.getCommon().error("-------------------生成签名失败-------------退款失败------------------------------");
throw new BizException(Code.ERR_REFUND);
}
String xml="<xml>"
+"<appid>"+WEIXIN_APPID+"</appid>"
+ "<mch_id>"+WEIXIN_MCHID+"</mch_id>"
+ "<nonce_str>"+rands+"</nonce_str>"
// + "<out_trade_no>"+escOrderId+"</out_trade_no>"
+ "<transaction_id>"+escOrderId+"</transaction_id>"
+ "<out_refund_no>"+rands1+"</out_refund_no>"
+ "<refund_fee>"+String.valueOf((int) (refundAmount.doubleValue() * 100))+"</refund_fee>"
+ "<total_fee>"+String.valueOf((int) (payAmount.doubleValue() * 100))+"</total_fee>"
+ "<sign>"+sign(params, WXPAY_APIKEY)+"</sign>"
+"</xml>";
/*----5.发送数据到微信的退款接口---- */
HttpPost httpost= new HttpPost(WEIXIN_API+REFUND);
httpost.setEntity(new StringEntity(xml, "UTF-8"));
String xmlStr ="";
try {
HttpResponse weixinResponse = httpclient.execute(httpost);
xmlStr = EntityUtils.toString(weixinResponse.getEntity(), "UTF-8");
Log.getCommon().error(xmlStr);
} catch (Exception e) {
Log.getCommon().error("-------------------网络请求失败-------------退款失败------------------------------");
throw new BizException(Code.ERR_REFUND);
}
Log.getCommon().error(xmlStr);
// Map<String, String> result = new HashMap<String, String>();
Map<String, String> respData = new HashMap<String, String>();;
try {
respData = WXPayUtil.xmlToMap(xmlStr);
} catch (Exception e) {
e.printStackTrace();
}
if("success".equalsIgnoreCase((String) respData.get("return_code")) && "SUCCESS".equalsIgnoreCase((String) respData.get("result_code"))){
Log.getCommon().error("-------------------"+escOrderId+"-------------退款成功------------------------------");
}else{
Log.getCommon().error("-------------------"+escOrderId+"-------------退款失败------------------------------"+respData.get("err_code_des"));
throw new BizException(respData.get("err_code_des"),Code.ERR_REFUND);
}
/*
String body = buildParam(params);
if(null == body){
System.out.println("body is null!");
}else{
System.out.println("发送的内容:"+body);
}
HttpClient client = new HttpClient();
String resultStr = client.post(REFUND, body , CHARSET);
Log.getOrder().info("票务退款:"+resultStr);
checkSign(resultStr, ConfigConts.WXPAY_APIKEY);
*/
}
//下单
public String unifiedorder(String name, String escOrderId, Double payAmount, String tradeType)
{
@SuppressWarnings("rawtypes")
TreeMap<String, String> params = new TreeMap();
params.put("appid", WEIXIN_APPID);
params.put("mch_id", WEIXIN_MCHID);
params.put("nonce_str", RandomUtils.getNumCode(6));
params.put("body", APP_NAME);
params.put("out_trade_no", escOrderId);
System.out.println("金额---------------------------"+payAmount);
params.put("total_fee", new BigDecimal(""+payAmount).multiply(new BigDecimal("100")).intValue()+"");
params.put("spbill_create_ip", SERVICEIP);
params.put("notify_url", WEIXIN_NOTIFY);
params.put("trade_type", tradeType);
params.put("sign", sign(params,WXPAY_APIKEY));
String body = buildParam(params);
HttpClient client = new HttpClient();
String resultStr = client.post(WEIXIN_API+UNIFIEDORDER , body,charset );
TreeMap<String, String> resultParams = checkSign(resultStr, WXPAY_APIKEY);
return (String)resultParams.get("prepay_id");
}
private String buildParam(TreeMap<String, String> params)
{
Document document = DocumentHelper.createDocument();
Element xml = document.addElement("xml");
for (Map.Entry<String, String> entry : params.entrySet())
{
Element ele = xml.addElement((String)entry.getKey());
ele.addCDATA((String)entry.getValue());
}
StringWriter out = new StringWriter(1024);
XMLWriter xw = new XMLWriter(out);
try
{
xw.write(document);
}
catch (IOException e)
{
this.log.error("生成支付XML参数", e);
throw new BizException(Code.ERROR);
}
return out.toString();
}
public Map<String, String> checkSign(InputStream inputStream) {
Document result;
try {
SAXReader reader = new SAXReader();
result = reader.read(inputStream);
} catch (DocumentException e) {
log.error("支付失败",e);
throw new BizException(Code.ERR_PAY);
} finally {
IOUtils.closeQuietly(inputStream);
}
return checkSign(result, WXPAY_APIKEY);
}
private TreeMap<String, String> checkSign(String resultStr, String wxpayKey) {
Document result;
try {
result = DocumentHelper.parseText(resultStr);
} catch (DocumentException e) {
log.error("支付失败",e);
throw new BizException(Code.ERR_PAY);
}
return checkSign(result, wxpayKey);
}
@SuppressWarnings("rawtypes")
private TreeMap<String, String> checkSign(Document result, String wxpayKey)
{
this.log.error("---------------------------------->body-->" + result.asXML());
boolean igSign = false;
String resultSign = null;
TreeMap<String, String> resultParams = new TreeMap();
Element resultXml = result.getRootElement();
for (Object resultObj : resultXml.elements())
{
Element resultEle = (Element)resultObj;
if ((igSign) || (!"sign".equals(resultEle.getName())))
{
resultParams.put(resultEle.getName(), resultEle.getText());
this.log.error(resultEle.getName() + "--------------------------------------------------->" + resultEle.getText());
}
else
{
resultSign = resultEle.getText();
igSign = true;
}
}
checkErr(resultParams);
if ((StringUtils.isEmpty(resultSign)) || (!resultSign.equals(sign(resultParams, wxpayKey)))) {
throw new BizException(Code.ERR_PAY);
}
return resultParams;
}
public String sign(TreeMap<String, String> params, String wxpayKey)
{
StringBuffer psb = new StringBuffer(1024);
for (Map.Entry<String, String> entry : params.entrySet()) {
if (!StringUtils.isBlank((CharSequence)entry.getValue())) {
psb.append((String)entry.getKey()).append("=").append((String)entry.getValue()).append("&");
}
}
psb.append("key=").append(wxpayKey);
String psbStr = psb.toString();
this.log.error(psbStr);
String sign = DigestUtils.md5Hex(psbStr).toUpperCase();
return sign;
}
private void checkErr(Map<String, String> result)
{
String returnCode = (String)result.get("return_code");
if (!"SUCCESS".equals(returnCode)) {
throw new BizException(Code.ERR_PAY);
}
}
@SuppressWarnings("rawtypes")
public Map<String, String> signAPP(String paySeq)
{
TreeMap<String, String> params = new TreeMap();
params.put("appid",WEIXIN_APPID);
params.put("partnerid",WEIXIN_MCHID);
params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000L));
params.put("noncestr", RandomUtils.getNumCode(6));
params.put("prepayid", paySeq);
params.put("package", "Sign=WXPay");
String paySign = sign(params,WXPAY_APIKEY);
params.put("sign", paySign);
return params;
}
赠送阿里云内部优惠劵:https://www.aliyun.com/minisite/goods?userCode=2f0qw1rz
工具类:
public class WXPayUtil {
/**
* XML格式字符串转换为Map
*
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
data.put(element.getNodeName(),element.getTextContent());//自己改了
}
}
try {
stream.close();
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception ex) {
WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
throw ex;
}
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, String> 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;
}
/**
* 生成带有 sign 的 XML 格式字符串
*
* @param data Map类型数据
* @param key API密钥
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
return generateSignedXml(data, key, SignType.MD5);
}
/**
* 生成带有 sign 的 XML 格式字符串
*
* @param data Map类型数据
* @param key API密钥
* @param signType 签名类型
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
String sign = generateSignature(data, key, signType);
data.put(WXPayConstants.FIELD_SIGN, sign);
return mapToXml(data);
}
/**
* 判断签名是否正确
*
* @param xmlStr XML格式数据
* @param key API密钥
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
Map<String, String> data = xmlToMap(xmlStr);
if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_SIGN);
return generateSignature(data, key).equals(sign);
}
/**
* 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
*
* @param data Map类型数据
* @param key API密钥
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
return isSignatureValid(data, key, SignType.MD5);
}
/**
* 判断签名是否正确,必须包含sign字段,否则返回false。
*
* @param data Map类型数据
* @param key API密钥
* @param signType 签名方式
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception {
if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_SIGN);
return generateSignature(data, key, signType).equals(sign);
}
/**
* 生成签名
*
* @param data 待签名数据
* @param key API密钥
* @return 签名
*/
public static String generateSignature(final Map<String, String> data, String key) throws Exception {
return generateSignature(data, key, SignType.MD5);
}
/**
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
*
* @param data 待签名数据
* @param key API密钥
* @param signType 签名方式
* @return 签名
*/
public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
}
else if (SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
}
else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
/**
* 获取随机字符串 Nonce Str
*
* @return String 随机字符串
*/
public static String generateNonceStr() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}
/**
* 生成 MD5
*
* @param data 待处理数据
* @return MD5结果
*/
public static String MD5(String data) throws Exception {
java.security.MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 生成 HMACSHA256
* @param data 待处理数据
* @param key 密钥
* @return 加密结果
* @throws Exception
*/
public static String HMACSHA256(String data, String key) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 日志
* @return
*/
public static Logger getLogger() {
Logger logger = LoggerFactory.getLogger("wxpay java sdk");
return logger;
}
/**
* 获取当前时间戳,单位秒
* @return
*/
public static long getCurrentTimestamp() {
return System.currentTimeMillis()/1000;
}
/**
* 获取当前时间戳,单位毫秒
* @return
*/
public static long getCurrentTimestampMs() {
return System.currentTimeMillis();
}
/**
* 生成 uuid, 即用来标识一笔单,也用做 nonce_str
* @return
*/
public static String generateUUID() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}
}
赠送阿里云内部优惠劵:
https://www.aliyun.com/minisite/goods?userCode=2f0qw1rz
回调方法:
@ResponseBody
@RequestMapping("wxpay")
@ApiOperation(value = "微信支付回调" ,httpMethod = "POST" )
public String wxPay() {
String returnStr = null;
try {
Log.getCommon().info("微信支付回调: "+JSONObject.toJSONString(request.getParameterMap()));
Map<String, String> wxdata = WeixinPayClient.getInstance().checkSign(request.getInputStream());
String orderNo =wxdata.get("out_trade_no");
String alipayNo = wxdata.get("transaction_id");
System.out.println("微信开始进入 ============================================");
if ( WeixinPayClient.getInstance().verif(orderNo, "SUCCESS")) {
System.out.println("微信开始已经进入-------------------------------------");
//你要处理的业务方法。
//承接各种app小程序公众号代码业务。
}else{
Log.getCommon().error("微信支付回调签名错误");
}
} catch (Exception e) {
Log.getCommon().error(e.getMessage(), e);
}
returnStr = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
return returnStr;
}
//接不通可VX:wang01208888
赠送阿里云内部优惠劵:
https://www.aliyun.com/minisite/goods?userCode=2f0qw1rz