微信支付
之前搞了下支付宝微信扫码支付,突然又让搞app支付,大神直接甩个账号,让自己搞,还得一点一点扒拉。在此记一下,以后用到了方便找。service得接口,是支付宝和微信支付公用的,有的参数有点多,单一用的话多余的可以去掉。本篇主要是微信的支付,支付宝的会在另一篇里去写。不多说了,上代码。
主要部分为service实现层。
扫码支付
/**
* 服务端当面付,扫码支付,返回二维码字符串(有前端工具生成二维码)
* @param orderId 订单id
* @param totalCost 费用
* @param body 对一笔交易的具体描述信息。如果是多种商品,请将商品描述字符串累加传给body。
* @param subject 商品的标题/交易标题/订单标题/订单关键字等。(必填)
*/
public InvokeResult commitPay(String orderId, float totalCost, String body,String desc) ;
@Override
public InvokeResult commitPay(String orderId, float totalCost, String body,String desc) {
String cost =String.valueOf(totalCost*100);
cost = cost.substring(0,cost.indexOf("."));
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
packageParams.put("appid", SxlinkWecharConstants.SXLink_APP_ID);
packageParams.put("mch_id", SxlinkWecharConstants.MCH_ID);
packageParams.put("nonce_str", PayCommonUtil.generateNonceStr());
packageParams.put("body", desc);//商品描述
packageParams.put("out_trade_no", orderId); //商品订单
packageParams.put("total_fee", cost); //费用 单位为分
packageParams.put("spbill_create_ip", PayCommonUtil.getHostIP()); //终端IP
packageParams.put("notify_url", SxlinkWecharConstants.NOTIFY_URL);
packageParams.put("trade_type", SxlinkWecharConstants.TRADE_TYPE);
String sign = PayCommonUtil.createSign("UTF-8", packageParams,SxlinkWecharConstants.API_KEY); //获取签名
packageParams.put("sign", sign);
String requestXML = PayCommonUtil.getRequestXml(packageParams);//将请求参数转换成String类型
String resXml = HttpUtil.postData(SxlinkWecharConstants.UNIFIEDORDER_URL_SUFFIX, requestXML); //解析请求之后的xml参数并且转换成String类型
Map map = null;
try {
map = XMLUtil.doXMLParse(resXml);
} catch (Exception e) {
e.printStackTrace();
}
String urlCode = (String) map.get("code_url");
if(urlCode==null){
return errorResult(ErrorCodeConstants.RUNTIME_ERROR, "调用接口失败");
}
return successResult(urlCode);
}
订单查寻
> /**
* 订单查询
* @param orderId
*/
InvokeResult queryOrderStatus(String orderId) ;
@Override
public InvokeResult queryOrderStatus(String orderId) {
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
packageParams.put("appid", SxlinkWecharConstants.SXLink_APP_ID);
packageParams.put("mch_id", SxlinkWecharConstants.MCH_ID);
packageParams.put("nonce_str", PayCommonUtil.generateNonceStr());
packageParams.put("out_trade_no",orderId); //商品订单
String sign = PayCommonUtil.createSign("UTF-8", packageParams,SxlinkWecharConstants.API_KEY); //获取签名
packageParams.put("sign", sign);
String requestXML = PayCommonUtil.getRequestXml(packageParams);//将请求参数转换成String类型
String resXml = HttpUtil.postData(SxlinkWecharConstants.ORDERQUERY_URL_SUFFIX, requestXML); //解析请求之后的xml参数并且转换成String类型
Map map = null;
try {
map = XMLUtil.doXMLParse(resXml);
} catch (Exception e) {
e.printStackTrace();
}
String urlCode = (String) map.get("trade_state");
if(urlCode.equals("SUCCESS")){
return successResult("支付成功");
}
return errorResult(ErrorCodeConstants.RUNTIME_ERROR,"支付未成功");
}
app支付
/**
* app支付
* 注:商户在请求参数中,自己附属的一些额外参数,
* 不要和支付宝系统中约定的key(下表中 公共请求参数\请求参数)重名,否则将可能导致未知的异常。
* @param body 对一笔交易的具体描述信息。如果是多种商品,请将商品描述字符串累加传给body。(微信必填)
* @param subject 商品的标题/交易标题/订单标题/订单关键字等。(支付宝必填)
* @param out_trade_no 商户网站唯一订单号(必填)
* @param timeout_express该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,
* 1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点,
* 如 1.5h,可转换为 90m。 注:若为空,则默认为 90m。
* @param total_amount 订单总金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000] (必填)
* @param product_code 销售产品码,商家和支付宝签约的产品码,为固定值QUICK_MSECURITY_PAY (支付宝必填)
* @return app支付订单信息
*/
InvokeResult appPay(String body,String subject,String out_trade_no,String timeout_express,String total_amount,String product_code);
@Override
public InvokeResult appPay(String body, String subject, String outTradeNo,
String timeoutExpress, String totalAmount, String productCode) {
String cost =String.valueOf(Float.parseFloat(totalAmount)*100);
cost = cost.substring(0,cost.indexOf("."));
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
packageParams.put("appid", SxlinkWecharConstants.SXLinkOpenPlat_APP_ID);
packageParams.put("mch_id", SxlinkWecharConstants.MCH_ID);
packageParams.put("nonce_str", PayCommonUtil.generateNonceStr());
if(body==null){
body ="";
}
packageParams.put("body", body);//商品描述
packageParams.put("out_trade_no", outTradeNo); //商品订单
packageParams.put("total_fee", cost); //费用 单位为分
packageParams.put("spbill_create_ip", PayCommonUtil.getHostIP()); //终端IP
packageParams.put("notify_url", SxlinkWecharConstants.NOTIFY_URL);
packageParams.put("trade_type", SxlinkWecharConstants.TRADE_TYPE_APP);
String sign = PayCommonUtil.createSign("UTF-8", packageParams,SxlinkWecharConstants.API_KEY); //获取签名
packageParams.put("sign", sign);
String requestXML = PayCommonUtil.getRequestXml(packageParams);//将请求参数转换成String类型
String resXml = HttpUtil.postData(SxlinkWecharConstants.UNIFIEDORDER_URL_SUFFIX, requestXML); //解析请求之后的xml参数并且转换成String类型
System.out.println(resXml);
try {
XMLUtil.doXMLParse(resXml);
} catch (Exception e) {
e.printStackTrace();
}
// 预支付交易会话ID
String prepay_id = "";
Map<String, String> m = new HashMap<String, String>();
if (resXml.indexOf("SUCCESS") != -1) {
try {
m = XMLUtil.doXMLParse(resXml);
} catch (Exception e) {
e.printStackTrace();
}
prepay_id = (String) m.get("prepay_id");
}
Map<String,String> signMap = new HashMap<String,String>() ;
//时间戳、随机字符串
String timeStamp = String.valueOf(PayCommonUtil.getCurrentTimestamp());
String nonceStr = PayCommonUtil.generateNonceStr();
signMap.put("appId", SxlinkWecharConstants.SXLinkOpenPlat_APP_ID);
signMap.put("partnerid", SxlinkWecharConstants.MCH_ID);
signMap.put("prepayid", prepay_id);
signMap.put("package","Sign=WXPay");
signMap.put("nonceStr", nonceStr);
signMap.put("timeStamp",timeStamp);
String JSApisign = "";
try {
JSApisign = PayCommonUtil.generateSignature(signMap, SxlinkWecharConstants.API_KEY, SxlinkWecharConstants.SignType.MD5);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("appid", SxlinkWecharConstants.SXLinkOpenPlat_APP_ID);
json.put("partnerid",SxlinkWecharConstants.MCH_ID);
json.put("prepayid",prepay_id);
json.put("package", "Sign=WXPay");
json.put("noncestr", nonceStr);
json.put("timestamp",timeStamp);
json.put("sign", JSApisign);
System.out.println(json.toString());
return successResult(json);
}
最终返回得code是二维码得链接,前台生成二维码就可以了,这个二维码有时间限制,用的时候注意。以下是用到得工具。
/**
* 获取随机字符串 Nonce Str
* @return String 随机字符串
*/
public static String generateNonceStr() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}
/**
* 获取本机的ip地址
* @return String
*/
public static String getHostIP(){
InetAddress addr;
String ip = "";
try {
addr = InetAddress.getLocalHost();
ip=addr.getHostAddress().toString(); //获取本机ip
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
/**
* @Description:将请求参数map转换为xml格式的string
* @param parameters 请求参数
* @return
*/
@SuppressWarnings("unchecked")
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");//注:参数值用XML转义即可,CDATA标签用于说明数据不被XML解析器解析。
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
public static String postData(String urlStr, String data) {
return postData(urlStr, data, null);
}
/**
* post数据请求
* @param urlStr
* @param data
* @param contentType
* @return
*/
public static String postData(String urlStr, String data, String contentType) {
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if (contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if (data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try{
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
/**
* XML格式字符串转换为Map
*
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> doXMLParse(String strXML) throws Exception {
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) {
}
return data;
}
/**
* @Description:sign签名
* @param characterEncoding 编码格式
* @param parameters 请求参数
* @return
*/
@SuppressWarnings("unchecked")
public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* 获取当前时间戳,单位秒
* @return
*/
public static long getCurrentTimestamp() {
return System.currentTimeMillis()/1000;
}
/**
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
* @param data 待签名数据
* @param key API密钥
* @param signType 签名方式
* @return 签名
*/
public static String generateSignature(final Map<String, String> data, String key, SxlinkWecharConstants.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(SxlinkWecharConstants.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 (SxlinkWecharConstants.SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
}
else if (SxlinkWecharConstants.SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
}
else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
好了,微信支付到此结束,其中的商户号,密钥、网关之类,自己照着配置就好了,下面是异步回调的一个controller,处理了微信异步回调的解析,具体该实现自己的逻辑,在判断支付成功里面设置。
/**
* 微信支付回调地址
* @param request
* @param response
*/
@RequestMapping(value = "/wxpaySucc",produces = MediaType.APPLICATION_JSON_VALUE)
public void wxpaySucc(HttpServletRequest request, HttpServletResponse response) throws IOException {
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();
//解析xml成map
Map<String, String> m = new HashMap<String, String>();
try {
m = XMLUtil.doXMLParse(sb.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
//过滤空 设置 TreeMap
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
Iterator<String> it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = it.next();
String parameterValue = m.get(parameter);
String v = "";
if(null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
//判断签名是否正确
String resXml = "";
boolean signVerified = false;
try {
signVerified = PayCommonUtil.isTenpaySign("UTF-8", packageParams,SxlinkWecharConstants.API_KEY);
} catch (Exception e) {
e.printStackTrace();
}
if(signVerified) {
String app_id = (String)packageParams.get("appid");
String mch_id = (String)packageParams.get("mch_id");
if(app_id.equals(SxlinkWecharConstants.SXLinkOpenPlat_APP_ID)&&mch_id.equals(SxlinkWecharConstants.MCH_ID)){
String out_trade_no = "";
String total_fee = "";
try{
//商户订单号
out_trade_no = (String)packageParams.get("out_trade_no");
//付款金额【以分为单位】
total_fee = (String) packageParams.get("total_fee");
}catch (Exception e) {
System.out.println(e);
}
if("SUCCESS".equals((String)packageParams.get("result_code"))){
//TODO 这里是支付成功 、执行自己的业务逻辑开始
//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
}
}else{
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[微信商户号或服务号有误]]></return_msg>" + "</xml> ";
}
} else{
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[验签失败]]></return_msg>" + "</xml> ";
}
//此处输出resXml结果,告知微信异步通知结果时成功还是失败
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
}