java 微信支付工具类

3 篇文章 0 订阅
1 篇文章 0 订阅
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 微信支付api
 * 
 */
public class WxPayApi
{
	private static Logger log = org.apache.log4j.Logger.getLogger(WxPayApi.class);

	/**
	 * 统一下单地址
	 */
	private static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	private static final String APPID = "";
	/**
	 * 微信支付分配的商户号
	 */
	private static final String mch_id = "";
	/**
	 * 异步接收微信支付结果通知的回调地址
	 */
	private static final String notify_url = "";
	/**
	 * 微信商户平台-账户设置-安全设置-api安全,配置32位key
	 */
	public static String KEY = "";

	/**
	 * 统一下单返回预支付id
	 * 
	 * @param data
	 * @param body    商品简单描述
	 * @param OrderNo 商户订单号
	 * @param money   订单总金额,单位为分
	 * @param ip      APP和网页支付提交用户端ip Native支付填调用微信支付API的机器IP
	 * @param openid  公众号支付时 用户的openid
	 * @return prepayId 预支付id
	 * @throws Exception
	 */
	public static String unifiedH5order(String body, String OrderNo, int money, String ip, String openid)
			throws Exception
	{
		String prepayId = "";
		Map<String, String> map = new HashMap<String, String>();
		map.put("appid", APPID);
		map.put("mch_id", mch_id); // 商户号
		map.put("device_info", "WEB"); // PC网页或公众号内支付可以传"WEB"
		map.put("nonce_str", WXPayUtil.generateNonceStr()); // 随机字符串长度要求在32位以内
		map.put("body", body); // 商品简单描述
		map.put("out_trade_no", OrderNo); // 商户订单号
		map.put("total_fee", money + ""); // 订单总金额,单位为分
		map.put("spbill_create_ip", ip); // APP和网页支付提交用户端ip Native支付填调用微信支付API的机器IP
		map.put("notify_url", notify_url); // 订单回调地址
		map.put("trade_type", "JSAPI"); // 交易类型 JSAPI 公众号支付 NATIVE 扫码支付 APP APP支付
		map.put("openid", "openid");
		map.put("sign", WXPayUtil.generateSignature(map, KEY));
		String dataXML = WXPayUtil.mapToXml(map);
		String resultXMlStr = urlPost(UNIFIEDORDER_URL, dataXML);
		log.info("统一下单返回结果-----------------   " + resultXMlStr);
		Map<String, String> result = WXPayUtil.xmlToMap(resultXMlStr);
		prepayId = result.get("prepay_id");
		if (null == prepayId)
		{
			throw new Exception("获取预支付id失败");
		}
		return prepayId;

	}

	/**
	 * 根据预支付id 生成包含所有必须参数的map对象 返回给前端jssdk使用
	 * 
	 * @param prepayId
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> getClientPrepayMap(String prepayId) throws Exception
	{
		Map<String, String> map = new HashMap<String, String>();
		map.put("appId", APPID);
		map.put("timeStamp", String.valueOf(new Date().getTime() / 1000));
		map.put("nonceStr", WXPayUtil.generateNonceStr());
		map.put("package", "prepay_id=" + prepayId);
		map.put("signType", "MD5");
		String sign = WXPayUtil.generateSignature(map, KEY);
		map.put("paySign", sign);
		return map;
	}

	/**
	 * 微信支付回调结果参数解析 接收通知成功必须通知微信成功接收通知
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> payCallBack(HttpServletRequest request) throws Exception
	{
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null)
		{
			sb.append(s);
		}
		in.close();
		inputStream.close();
		return WXPayUtil.xmlToMap(sb.toString());

	}

	public static String urlGet(String url) throws Exception
	{
		GetMethod get = new GetMethod(url);
		HttpClient httpClient = new HttpClient();
		get.getParams().setContentCharset("utf-8");
		httpClient.executeMethod(get);
		return get.getResponseBodyAsString();
	}

	@SuppressWarnings("deprecation")
	public static String urlPost(String url, String postBody) throws Exception
	{
		PostMethod post = new PostMethod(url);
		HttpClient httpClient = new HttpClient();
		post.getParams().setContentCharset("utf-8");
		post.setRequestBody(postBody);
		httpClient.executeMethod(post);
		return post.getResponseBodyAsString();
	}

}


//***********************************************************************************

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;
import java.security.MessageDigest;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import com.github.wxpay.sdk.WXPayConstants.SignType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信支付工具类
 * 
 * @author qxw 2018年3月1日
 */
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"));
			org.w3c.dom.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)
				{
					org.w3c.dom.Element element = (org.w3c.dom.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);
	}

}

//***********************************************************************************

/**
 * 常量
 */
public class WXPayConstants
{

	public enum SignType
	{
		MD5, HMACSHA256
	}

	public static final String DOMAIN_API = "api.mch.weixin.qq.com";
	public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
	public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
	public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";

	public static final String FAIL = "FAIL";
	public static final String SUCCESS = "SUCCESS";
	public static final String HMACSHA256 = "HMAC-SHA256";
	public static final String MD5 = "MD5";

	public static final String FIELD_SIGN = "sign";
	public static final String FIELD_SIGN_TYPE = "sign_type";
	/**
	 * 刷卡支付
	 */
	public static final String MICROPAY_URL_SUFFIX = "/pay/micropay";
	/**
	 * 统一下单
	 */
	public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
	/**
	 * 查询订单
	 */
	public static final String ORDERQUERY_URL_SUFFIX = "/pay/orderquery";
	public static final String REVERSE_URL_SUFFIX = "/secapi/pay/reverse";
	/**
	 * 关闭订单
	 */
	public static final String CLOSEORDER_URL_SUFFIX = "/pay/closeorder";
	/**
	 * 申请退款
	 */
	public static final String REFUND_URL_SUFFIX = "/secapi/pay/refund";
	/**
	 * 查询退款
	 */
	public static final String REFUNDQUERY_URL_SUFFIX = "/pay/refundquery";
	/**
	 * 下载对账单
	 */
	public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
	/**
	 * 交易保障
	 */
	public static final String REPORT_URL_SUFFIX = "/payitil/report";
	public static final String SHORTURL_URL_SUFFIX = "/tools/shorturl";
	public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";

	// sandbox
	public static final String SANDBOX_MICROPAY_URL_SUFFIX = "/sandboxnew/pay/micropay";
	public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
	public static final String SANDBOX_ORDERQUERY_URL_SUFFIX = "/sandboxnew/pay/orderquery";
	public static final String SANDBOX_REVERSE_URL_SUFFIX = "/sandboxnew/secapi/pay/reverse";
	public static final String SANDBOX_CLOSEORDER_URL_SUFFIX = "/sandboxnew/pay/closeorder";
	public static final String SANDBOX_REFUND_URL_SUFFIX = "/sandboxnew/secapi/pay/refund";
	public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX = "/sandboxnew/pay/refundquery";
	public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
	public static final String SANDBOX_REPORT_URL_SUFFIX = "/sandboxnew/payitil/report";
	public static final String SANDBOX_SHORTURL_URL_SUFFIX = "/sandboxnew/tools/shorturl";
	public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";

}

转载:https://gitee.com/qinxuewu/codes/nix6d9y8zw5crja7v4pel16

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值