写下一篇微信h5的支付代码 以免自己忘记了
微信支付的话 首先 你需要 在公众号里面填写一些配置 ,不会的话 百度吧 ,这个我就不说了 ,相对来说 这个是比较容易的。下面开始微信支付开发。
1.看文档啊 ,虽然那玩意 写的不咋地,反正对于我这个菜鸟来说就是很难看懂。
2.微信支付其中最重要的就是一些签名问题,这东西把我给折磨了两三天。
3.最后的问题就是在返回支付结果这里了,微信支付成功了以后会给你返回一串支付数据,你需要 核对是否和你数据库中的一致,并给微信返回是否成功标志,如果你不返回,嘿嘿。。麻烦大了 ,微信会一直给你返回信息,虽然文档上说的是只会发送8次,但是实际是我这边最多给我发过11次 后面不知道是不是间隔时间太长了一直没发过来我就把服务停了。
4.关于支付测试问题,这个你是无法在模拟器上测试的 ,即使是微信官方提供的web开发工具都不可以,你只能在真机上测试。
下面开始代码
首先看文档 ,文档上只提供了一段js代码,
function onBridgeReady(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId":"wx2421b1c4370ec43b", //公众号名称,由商户传入 "timeStamp":"1395712654", //时间戳,自1970年以来的秒数 "nonceStr":"e61463f8efa94090b1f366cccfbbb444", //随机串 "package":"prepay_id=u802345jgfjsdfgsdg888", "signType":"MD5", //微信签名方式: "paySign":"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 }, function(res){ if(res.err_msg == "get_brand_wcpay_request:ok" ) {} // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。 } ); } if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } }else{ onBridgeReady(); }
就是这段 ,这段代码最重要的就是参数,而那些参数是需要我们自己在后台通过算法算发出来的,所以在调用这个h5支付的时候,我们需要先在后端算出数据并返回到前端完成h5请求。
随机串算法
public String nonceStr() { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 32; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }
时间戳算法
System.currentTimeMillis()/1000L;
微信签名算法
SortedMap<String, String> pay= new TreeMap<String, String>(); pay.put("appId", ""); pay.put("timeStamp", time+""); pay.put("nonceStr", nonce); pay.put("package", "prepay_id="+(String)map.get("prepay_id")); pay.put("signType", "MD5");
//签名算法
public static String createSign(String characterEncoding,SortedMap<String,String> parameters){ StringBuffer sb = new StringBuffer(); Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序) Iterator it = es.iterator(); while(it.hasNext()) { 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 + "&"); } } String s=sb.toString()+"key=“ ”; String sign = MD5Util.MD5Encode(s, characterEncoding).toUpperCase(); return sign; }
//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" }; }
characterEncoding 这个参数的意思是编码方式 至于那个key的话 就要你自己去自己的商户号上设置那个api秘钥了 (微信商户号上的 api秘钥就是这个 key)
以上就是签名算法 ,下面来一个最关键的东西了 prepay_id 这个参数 是无法直接得到的,我们需要先请求微信提供的统一下单号 接口 来获取返回值 并解析出 prepay_id 。
public List unifiedOrder(String copenid,String nonce,String money){ // copenid 这是付款用户的openid nonce 这是随机码 money 这是付款金额 String appid = "wx1d37de7c5c798720";//appid String attach = "123"; String body = "123";//商品描述 String mch_id = "1467300102";//微信支付商户号 String nonce_str =nonce;//随机码 String notify_url = " ";//这里要填写你的回调路径 ,一定要写 不写的话就会请求失败 String openid = copenid; String out_trade_no = getCurrTime();//商品订单号(随意填 只要和你其他的订单号不重复就可以) String total_fee = money;//总金额 不支持小数点 单位是分 String trade_type = "JSAPI";//公众号支付 // String product_id = "qwertyu1234567";//商品编号(随意了) // String time_start =getCurrTime();//交易起始时间(订单生成时间非必须) SortedMap<String, String> params = new TreeMap<String, String>(); params.put("appid", appid); params.put("attach", attach);//商品描述 params.put("body", body);//商品描述 params.put("mch_id", mch_id); params.put("nonce_str", nonce_str); params.put("notify_url", notify_url); params.put("openid", openid); params.put("out_trade_no", out_trade_no); // params.put("product_id", product_id); // params.put("time_start", time_start); params.put("total_fee", total_fee); params.put("trade_type", trade_type); String sign = createSign("UTF-8",params);//签名(该签名本应使用微信商户平台的API证书中的密匙key,但此处使用的是微信公众号的密匙APP_SECRET) //参数xml化 String xmlParams = parseString2Xml(params,sign); //判断返回码 String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; Map map = new GetWxOrderno().getPayNo(createOrderURL, xmlParams);// 调用支付接口 List<Object> list =new ArrayList<Object>(); Object time=System.currentTimeMillis()/1000L; list.add(time); list.add(nonce); list.add((String) map.get("prepay_id")); SortedMap<String, String> pay= new TreeMap<String, String>(); pay.put("appId", "wx1d37de7c5c798720"); pay.put("timeStamp", time+""); pay.put("nonceStr", nonce); pay.put("package", "prepay_id="+(String)map.get("prepay_id")); pay.put("signType", "MD5"); String paysign = createSign("UTF-8",pay); list.add(paysign); return list; }
public static String parseString2Xml(Map<String, String> map,String sign){ StringBuffer sb = new StringBuffer(); sb.append("<xml>"); Set es = map.entrySet(); Iterator iterator = es.iterator(); while(iterator.hasNext()){ Map.Entry entry = (Map.Entry)iterator.next(); String k = (String)entry.getKey(); String v = (String)entry.getValue(); sb.append("<"+k+">"+v+"</"+k+">"); } sb.append("<sign>"+sign+"</sign>"); sb.append("</xml>"); return sb.toString(); }
public class GetWxOrderno { public static DefaultHttpClient httpclient; static { httpclient = new DefaultHttpClient(); httpclient = (DefaultHttpClient)HttpClientConnectionManager.getSSLInstance(httpclient); } public static Map getPayNo(String url,String xmlParam){ System.out.println("xml是:"+xmlParam); DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); HttpPost httpost= HttpClientConnectionManager.getPostMethod(url); String prepay_id = ""; String sign=""; Map map = null ; try { httpost.setEntity(new StringEntity(xmlParam, "UTF-8")); HttpResponse response = httpclient.execute(httpost); String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8"); Map<String, Object> dataMap = new HashMap<String, Object>(); System.out.println("json是:"+jsonStr); if(jsonStr.indexOf("FAIL")!=-1){ return null; } map = doXMLParse(jsonStr); String return_code = (String) map.get("return_code"); prepay_id = (String) map.get("prepay_id"); sign = (String) map.get("sign"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /** * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。 * @param strxml * @return * @throws JDOMException * @throws IOException */ public static Map doXMLParse(String strxml) throws Exception { if(null == strxml || "".equals(strxml)) { return null; } Map m = new HashMap(); InputStream in = String2Inputstream(strxml); 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 = 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(getChildrenText(list)); } sb.append(value); sb.append("</" + name + ">"); } } return sb.toString(); } public static InputStream String2Inputstream(String str) { return new ByteArrayInputStream(str.getBytes()); } }
其中我返回的list集合 是返回给前端的数据 , 用于请求h5支付的,可以看到我在请求 统一下单号的时候算了一次签名,在返回list集合的时候我又重新计算了一次,原因是这个签名微信那边也会计算的,微信计算用的参数都是我们这边上传的参数,所以 我们的签名每请求一次最好就是重新算一次 这样 我们前端所需要的参数都有了,就可以调起h5支付了