JAVA微信扫码支付模式二线上支付功能实现以及回调
一、准备工作
首先吐槽一下微信关于支付这块,本身支持的支付模式就好几种,但是官方文档特别零散,连像样的java相关的demo也没几个。本人之前没有搞过微信支付,一开始真是被它搞晕,折腾两天终于调通了,特此写下来,以享后人吧!
关于准备工作,就“微信扫码支付模式二”官方文档地址在这 可以先看看,实际上需要准备的东西有以下几个:
其中app_id和app_secret可以在公众平台找着,mch_id和api_key则在商户平台找到,特别是api_key要在商户平台设置好,对于“微信扫码支付模式二”(支付与回调)实际只会用到app_id、mch_id和api_key,其他的都不用。
关于开发环境,我就不罗嗦了,不管你是springmvc、struts2又或者直接serverlet,都差不多,只要你能保证对应的方法能调用起来就行。关于引用第三方的jar包,我这里只用到了一个xml操作的jdom,记住是1.*的版本,不是官网上最新的2.*,两者不兼容。具体是jdom-1.1.3.jar,依赖包jaxen-1.1.6.jar,就这两个包,我没用到有些例子中使用的httpclient,感觉没必要,而且依赖包特别繁杂,当然你是maven当我没说。
二、开发实战
1、首先是接入微信接口,获取微信支付二维码。
public string weixin_pay() throws exception { // 账号信息 string appid = payconfigutil.app_id; // appid //string appsecret = payconfigutil.app_secret; // appsecret string mch_id = payconfigutil.mch_id; // 商业号 string key = payconfigutil.api_key; // key string currtime = paycommonutil.getcurrtime(); string strtime = currtime.substring(8, currtime.length()); string strrandom = paycommonutil.buildrandom(4) + ""; string nonce_str = strtime + strrandom; string order_price = 1; // 价格 注意:价格的单位是分 string body = "goodssssss"; // 商品名称 string out_trade_no = "11338"; // 订单号 // 获取发起电脑 ip string spbill_create_ip = payconfigutil.create_ip; // 回调接口 string notify_url = payconfigutil.notify_url; string trade_type = "native"; sortedmap<object,object> packageparams = new treemap<object,object>(); packageparams.put("appid", appid); packageparams.put("mch_id", mch_id); packageparams.put("nonce_str", nonce_str); packageparams.put("body", body); packageparams.put("out_trade_no", out_trade_no); packageparams.put("total_fee", order_price); packageparams.put("spbill_create_ip", spbill_create_ip); packageparams.put("notify_url", notify_url); packageparams.put("trade_type", trade_type); string sign = paycommonutil.createsign("utf-8", packageparams,key); packageparams.put("sign", sign); string requestxml = paycommonutil.getrequestxml(packageparams); system.out.println(requestxml); string resxml = httputil.postdata(payconfigutil.ufdoder_url, requestxml); map map = xmlutil.doxmlparse(resxml); //string return_code = (string) map.get("return_code"); //string prepay_id = (string) map.get("prepay_id"); string urlcode = (string) map.get("code_url"); return urlcode; }
如果不出意外的话,这里就从微信服务器获取了一个支付url,形如weixin://wxpay/bizpayurl?pr=pixxxxx,之后我们就需要把这个url生成一个二维码,然后就可以使用自己手机微信端扫码支付了。关于二维码生成有很多种方法,各位各取所需吧,我这里提供一个google的二维码生成接口:
public static string qrfromgoogle(string chl) throws exception { int widhtheight = 300; string ec_level = "l"; int margin = 0; chl = urlencode(chl); string qrfromgoogle = "http://chart.apis.google.com/chart?chs=" + widhtheight + "x" + widhtheight + "&cht=qr&chld=" + ec_level + "|" + margin + "&chl=" + chl; return qrfromgoogle; }
// 特殊字符处理 public static string urlencode(string src) throws unsupportedencodingexception { return urlencoder.encode(src, "utf-8").replace("+", "%20"); }
上面代码中涉及到几个工具类:payconfigutil、paycommonutil、httputil和xmlutil,其中payconfigutil放的就是上面提到一些配置及路径,paycommonutil涉及到了获取当前事件、产生随机字符串、获取参数签名和拼接xml几个方法,代码如下:
public class paycommonutil { /** * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 * @return boolean */ public static boolean istenpaysign(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(!"sign".equals(k) && null != v && !"".equals(v)) { sb.append(k + "=" + v + "&"); } } sb.append("key=" + api_key); //算出摘要 string mysign = md5util.md5encode(sb.tostring(), characterencoding).tolowercase(); string tenpaysign = ((string)packageparams.get("sign")).tolowercase(); //system.out.println(tenpaysign + " " + mysign); return tenpaysign.equals(mysign); } /** * @author * @date 2016-4-22 * @description:sign签名 * @param characterencoding * 编码格式 * @param parameters * 请求参数 * @return */ 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; } /** * @author * @date 2016-4-22 * @description:将请求参数转换为xml格式的string * @param parameters * 请求参数 * @return */ 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 + ">"); } else { sb.append("<" + k + ">" + v + "</" + k + ">"); } } sb.append("</xml>"); return sb.tostring(); } /** * 取出一个指定长度大小的随机正整数. * * @param length * int 设定所取出随机数的长度。length小于11 * @return int 返回生成的随机数。 */ public static int buildrandom(int length) { int num = 1; double random = math.random(); if (random < 0.1) { random = random + 0.1; } for (int i = 0; i < length; i++) { num = num * 10; } return (int) ((random * num)); } /** * 获取当前时间 yyyymmddhhmmss * * @return string */ public static string getcurrtime() { date now = new date(); simpledateformat outformat = new simpledateformat("yyyymmddhhmmss"); string s = outformat.format(now); return s; } }
httputil和xmlutil如下:
public class httputil { private static final log logger = logs.get(); private final static int connect_timeout = 5000; // in milliseconds private final static string default_encoding = "utf-8"; public static string postdata(string urlstr, string data){ return postdata(urlstr, data, null); } 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; } }
public class xmlutil { /** * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。 * @param strxml * @return * @throws jdomexception * @throws ioexception */ public static map doxmlparse(string strxml) throws jdomexception, ioexception { strxml = strxml.replacefirst("encoding=\".*\"", "encoding=\"utf-8\""); if(null == strxml || "".equals(strxml)) { return null; } map m = new hashmap(); inputstream in = new bytearrayinputstream(strxml.getbytes("utf-8")); saxbuilder builder = new saxbuilder(); document doc = builder.build(in); element root = doc.getrootelement(); list list = root.getchildren(); iterator it = list.iterator(); while(it.hasnext()) { element e = (element) it.next(); string k = e.getname(); string v = ""; list children = e.getchildren(); if(children.isempty()) { v = e.gettextnormalize(); } else { v = xmlutil.getchildrentext(children); } m.put(k, v); } //关闭流 in.close(); return m; } /** * 获取子结点的xml * @param children * @return string */ public static string getchildrentext(list children) { stringbuffer sb = new stringbuffer(); if(!children.isempty()) { iterator it = children.iterator(); while(it.hasnext()) { element e = (element) it.next(); string name = e.getname(); string value = e.gettextnormalize(); list list = e.getchildren(); sb.append("<" + name + ">"); if(!list.isempty()) { sb.append(xmlutil.getchildrentext(list)); } sb.append(value); sb.append("</" + name + ">"); } } return sb.tostring(); } }
当然还有一个md5计算工具类
public class md5util { private static string bytearraytohexstring(byte b[]) { stringbuffer resultsb = new stringbuffer(); for (int i = 0; i < b.length; i++) resultsb.append(bytetohexstring(b[i])); return resultsb.tostring(); } private static string bytetohexstring(byte b) { int n = b; if (n < 0) n += 256; int d1 = n / 16; int d2 = n % 16; return hexdigits[d1] + hexdigits[d2]; } public static string md5encode(string origin, string charsetname) { string resultstring = null; try { resultstring = new string(origin); messagedigest md = messagedigest.getinstance("md5"); if (charsetname == null || "".equals(charsetname)) resultstring = bytearraytohexstring(md.digest(resultstring .getbytes())); else resultstring = bytearraytohexstring(md.digest(resultstring .getbytes(charsetname))); } catch (exception exception) { } return resultstring; } private static final string hexdigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; }
2、支付回调
支付完成后,微信会把相关支付结果和用户信息发送到我们上面指定的那个回调地址,我们需要接收处理,并返回应答。对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功。 (通知频率为15/15/30/180/1800/1800/1800/1800/3600,单位:秒)
关于支付回调接口,我们首先要对于支付结果通知的内容进行签名验证,然后根据支付结果进行相应的处理流程即可。
public void weixin_notify(httpservletrequest request,httpservletresponse response) 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(); //解析xml成map map<string, string> m = new hashmap<string, string>(); m = xmlutil.doxmlparse(sb.tostring()); //过滤空 设置 treemap sortedmap<object,object> packageparams = new treemap<object,object>(); iterator it = m.keyset().iterator(); while (it.hasnext()) { string parameter = (string) it.next(); string parametervalue = m.get(parameter); string v = ""; if(null != parametervalue) { v = parametervalue.trim(); } packageparams.put(parameter, v); } // 账号信息 string key = payconfigutil.api_key; // key logger.info(packageparams); //判断签名是否正确 if(paycommonutil.istenpaysign("utf-8", packageparams,key)) { //------------------------------ //处理业务开始 //------------------------------ string resxml = ""; if("success".equals((string)packageparams.get("result_code"))){ // 这里是支付成功 //////////执行自己的业务逻辑//////////////// string mch_id = (string)packageparams.get("mch_id"); string openid = (string)packageparams.get("openid"); string is_subscribe = (string)packageparams.get("is_subscribe"); string out_trade_no = (string)packageparams.get("out_trade_no"); string total_fee = (string)packageparams.get("total_fee"); logger.info("mch_id:"+mch_id); logger.info("openid:"+openid); logger.info("is_subscribe:"+is_subscribe); logger.info("out_trade_no:"+out_trade_no); logger.info("total_fee:"+total_fee); //////////执行自己的业务逻辑//////////////// logger.info("支付成功"); //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了. resxml = "<xml>" + "<return_code><![cdata[success]]></return_code>" + "<return_msg><![cdata[ok]]></return_msg>" + "</xml> "; } else { logger.info("支付失败,错误信息:" + packageparams.get("err_code")); resxml = "<xml>" + "<return_code><![cdata[fail]]></return_code>" + "<return_msg><![cdata[报文为空]]></return_msg>" + "</xml> "; } //------------------------------ //处理业务完毕 //------------------------------ bufferedoutputstream out = new bufferedoutputstream( response.getoutputstream()); out.write(resxml.getbytes()); out.flush(); out.close(); } else{ logger.info("通知签名验证失败"); } }
签名验证算法和签名生成的算法类似,在上面paycommonutil工具类中提供。
三、后话
感觉微信扫描支付体验效果还是挺好的,唯一缺点就是相关文档零散,官方的demo居然没有java编写的,希望之后微信官方能够逐步完善吧!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。