자바 통합 위 챗 결제 (전체 절차)

자바 통합 위 챗 결제 (전체 절차)
1. 위 챗 결제 신청 능력
 *           ,   app  、     、h5                          。
 *                   、            ,                      。
 *           ,          appId,    32     。

2. 준비 작업
  *     h5  ,              URL IP    ,        5 IP    ,               IP       。
  *          ,  ,          IP    ,  ,     URL       IP     。

3. 집적 시작
 *** APP  **
 
             :
       1:     APP     ,    ,      。(app         )
       2:           ,            。(        )
       3:           prepay_id,             ,      APP。         appid,partnerid,prepayid,noncestr,timestamp,package。  :package     Sign=WXPay(      prepayid          app )
       4:  APP      。(app                 )
       5:          。(              )
       6:          。(           app )
        :
   


 DecimalFormat df = new DecimalFormat("######0.00"); 
    //    id         
	money=df.format(Double.parseDouble(okamiOrder.getReallMoney()));
	//     
	ReturnValue    rv=new ReturnValue();
	String token=request.getParameter("token");
	//     id
	String userId=TokenParmValue.getUserId(token);
	//                 
	String currTime = TenpayUtil.getCurrTime();
	// 8   
	String strTime = currTime.substring(8, currTime.length());
	//      
	String strRandom = TenpayUtil.buildRandom(4) + "";
	// 10    ,      。
	String strReq =strTime+strRandom;
	SONObject retMsgJson = new JSONObject();
   //    
	String  appId="";                //appid
	String  appSecret="";            //    appsecret
	String  partner="";              //     
	String  partnerkey="";           //api  
	//        
	appId=WeixinPayUtil.appid;
    appSecret=WeixinPayUtil.appsecret;
    partner=WeixinPayUtil.partner;
    partnerkey=WeixinPayUtil.partnerkey;
   //********************************************            
	//                  
		String sjbh = RandomUtil.getRandomFileName();
		//     
		TreeMap treeMap = new TreeMap();
		//         appId
		treeMap.put("appid",appId);
		//      
		treeMap.put("mch_id",partner);
		//    
		treeMap.put("nonce_str", strReq);
		//     
		treeMap.put("body",subject);
		//      
		treeMap.put("out_trade_no", sjbh);
		//   ip(       ip),           IP
		treeMap.put("spbill_create_ip", Property.getProperty("weixinIp"));
		//     
		treeMap.put("total_fee",money);
		//                 
		treeMap.put("trade_type",WeixinPayUtil.trade_type);
		//         
		treeMap.put("notify_url",Property.getProperty("okamiWeixinUrl").trim());
		//            
		if("3".equals(payType)){
			treeMap.put("limit_pay","no_credit");   
		}
		StringBuilder sb = new StringBuilder();
		for (String key : treeMap.keySet()) {
			sb.append(key).append("=").append(treeMap.get(key)).append("&");
		}
		sb.append("key="+partnerkey);
		//          
		RequestHandler reqHandler = new RequestHandler(request, response);
		reqHandler.init(appId,appSecret,partnerkey);
		//        
		String sign = reqHandler.createSign(treeMap);//     
		treeMap.put("sign", sign);
		StringBuilder xml = new StringBuilder();
		xml.append("
"); for (Map.Entry entry : treeMap.entrySet()) { if ("body".equals(entry.getKey()) || "sign".equals(entry.getKey())) { xml.append("" + entry.getKey() + ">
"); } else { xml.append("").append(entry.getValue()).append("" + entry.getKey() + ">
"); } } xml.append("
"); // String createOrderURL = WeixinPayUtil.createOrderURL; String prepay_id = ""; try { // prepay_id = GetWxOrderno.getPayNo(createOrderURL,xml.toString()); } catch (Exception e1) { e1.printStackTrace(); rv.setResult("error"); rv.setMsg(ReturnUtil.PAYMENT_FAILURE); return new JsonMapper().toJson(rv); } log.info(" prepay_id :----------------"+prepay_id); // prepayid app SortedMap finalpackage = new TreeMap(); String timestamp = Sha1Util.getTimeStamp(); finalpackage.put("appid",appId); finalpackage.put("noncestr", strReq); finalpackage.put("partnerid", partner); finalpackage.put("timestamp", timestamp); finalpackage.put("package", "Sign=WXPay"); finalpackage.put("prepayid", prepay_id); String wenXinSign=WenXinPay.createSign("UTF-8",finalpackage,partnerkey); retMsgJson.put("appid",appId); retMsgJson.put("timestamp",timestamp); retMsgJson.put("noncestr", strReq); retMsgJson.put("partnerid",partner); retMsgJson.put("prepayid", prepay_id); retMsgJson.put("packageX", "Sign=WXPay"); retMsgJson.put("sign", wenXinSign); // app String json = retMsgJson.toString(); app , app 。 : , , , 。 @RequestMapping(value = "payment/wechatAsynchronous",method=RequestMethod.POST,produces = "text/html;charset=UTF-8") @ResponseBody public void wechatAsynchronous(HttpServletRequest requestWechat,HttpServletResponse response) throws Exception{ log.info(" "+moduleName+" :wechatAsynchronous"); DecimalFormat df = new DecimalFormat("######0.00"); DecimalFormat dformat = new DecimalFormat("######0"); requestWechat.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); InputStream in = requestWechat.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); String msgxml = new String(out.toByteArray(), "utf-8");// xml System.out.println(msgxml); log.info("msgxml :-----------------"+msgxml); Map map = XmlToMap.xmlToMap(msgxml); // TreeMap SortedMap packageParams = new TreeMap(); Iterator it = map.keySet().iterator(); while (it.hasNext()) { String parameter = (String) it.next(); String parameterValue = (String) map .get(parameter); String v = ""; if(null != parameterValue) { v = parameterValue.trim(); } packageParams.put(parameter, v); } log.info(" "+moduleName+" :"+packageParams); // String result_code = (String) map.get("result_code"); // String out_trade_no = (String) map.get("out_trade_no"); // String sign = (String) map.get("sign"); log.info("sign :---------------------"+sign); // String total_fee=(String)map.get("total_fee"); String realMoney=String.valueOf(Double.parseDouble(total_fee)/100); // id String tranId = out_trade_no.replace(" ", ""); log.info(" tranId:" + tranId); log.info(" result_code -----------------------:" + result_code); // id Transaction tran = tranService.findById(tranId); if(tran!=null){ log.info("tran :--------------------"); // id String orderId = tran.getOrderId(); log.info(" orderId:" + orderId); // if (result_code.equals("SUCCESS")){ // long size=requestRedisTemplate.boundValueOps("weixinpay:lock:"+out_trade_no).increment(1); requestRedisTemplate.expire("weixinpay:lock:"+out_trade_no,24,TimeUnit.HOURS); if(size==1){ log.info(" "+moduleName+" !!!"); // asyncService.insertResrcord("weixin",tran.getUserId(),(String)map.get("transaction_id"),realMoney,tranId); // String transaction_id = (String) map.get("transaction_id"); // String mch_id=(String) map.get("mch_id"); // appid----> String appid=(String) map.get("appid"); if(StringUtils.isNotBlank(mch_id)&&StringUtils.isNotBlank(appid)){ log.info(" appid "); // appid // 1 String appId_local_one=WeixinPayUtil.appid; // 2 String appId_local_two=WeixinPayUtil.appid_two; // 3 String appId_local_three=WeixinPayUtil.appid_three; String partner_local=WeixinPayUtil.partner; String partnerKey_local=WeixinPayUtil.partnerkey; String appVersion="1"; // if (mch_id.equals(partner_local)) { log.info(" appid "); // if(WenXinPay.isTenpaySign("UTF-8", packageParams,partnerKey_local)){ log.info(" !!!!!!"); // }else{ response.getWriter().write(setXml("FAIL", "ERROR")); log.info(" !!!!!!"); } }else{ response.getWriter().write(setXml("FAIL", "ERROR")); log.info(" !!!!!!"); } } // xml public static String setXml(String return_code, String return_msg) { return ""; } app , demo , :https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_3 ***h5 ** : 1、 , 。 2、 ( ) : trade_type=MWEB。 3、 , url( “mweb_url”), mweb_url 。 4、 H5 , 。 5、 , 。 6、 , 。 7、 , 。 8,9、 , , 。 10、 。 ** h5 。** : /** * , h5 * @param paramMap * @return */ @Override public Result officialSend(Map paramMap){ Result result=new Result(); String pay_url=""; // TreeMap treeMap = new TreeMap(); // appId treeMap.put("appid",WeiXinConstant.official_app_id); // treeMap.put("mch_id",WeiXinConstant.official_mch_id); // treeMap.put("nonce_str",TenpayUtil.getNonceStr()); // treeMap.put("body",paramMap.get("productname")+""); // treeMap.put("out_trade_no",paramMap.get("orderId")+""); // ip( ip) treeMap.put("spbill_create_ip",paramMap.get("spbill_create_ip")+""); // treeMap.put("total_fee",new Double(Double.valueOf(paramMap.get("money")+"")*100).intValue()+""); // treeMap.put("trade_type","MWEB");//h5 // treeMap.put("notify_url", PropertiesUtil.getDom()+WeiXinConstant.official_notify_url); // treeMap.put("attach",paramMap.get("orderId")+""); JSONObject js=new JSONObject(); JSONObject jb=new JSONObject(); if("1".equals(paramMap.get("source"))){// js.put("type", "Android"); js.put("app_name", "8wan "); js.put("package_name", "com.xianqing.sdk"); jb.put("h5_info", js); }else{//ios js.put("type", "IOS"); js.put("bundle_id", "com.xianqing.sdk"); js.put("app_name", "8wan "); jb.put("h5_info", js); } // treeMap.put("scene_info",jb.toString()); // , //treeMap.put("limit_pay","no_credit"); Map params = SignUtils.paraFilter(treeMap); StringBuilder buf = new StringBuilder((params.size() +1) * 10); SignUtils.buildPayParams(buf,params,false); String preStr = buf.toString(); String sign = MD5.sign(preStr, "&key=" + WeiXinConstant.partnerkey, "utf-8"); treeMap.put("sign", sign); CloseableHttpResponse response = null; CloseableHttpClient client = null; try { HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); StringEntity entityParams = new StringEntity(WXPayUtil.mapToXml(treeMap),"utf-8"); httpPost.setEntity(entityParams); //httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1"); client = HttpClients.createDefault(); response = client.execute(httpPost); if(response != null && response.getEntity() != null){ Map resultMap = WXPayUtil.xmlToMap(new String(EntityUtils.toByteArray(response.getEntity()))); if("SUCCESS".equalsIgnoreCase(resultMap.get("return_code"))){ if("SUCCESS".equalsIgnoreCase(resultMap.get("result_code"))){ String prepay_id=resultMap.get("prepay_id"); String mweb_url=resultMap.get("mweb_url"); logger.info(" mweb_url:"+mweb_url); String packagevalue=""; if(mweb_url.indexOf("&package=")!=-1){ packagevalue=mweb_url.substring(mweb_url.indexOf("&package=")+9,mweb_url.length()); } String type=""; if(PropertiesUtil.getDom().indexOf("test")!=-1){ type="1"; }else{ type="2"; } pay_url=PropertiesUtil.getDom()+"pay/pay_h5_wx.html?prepay_id="+prepay_id+"&packagevalue="+packagevalue+"&type="+type; } }else{ logger.info(" h5 , :"+resultMap.get("return_msg")); } logger.info(" :"+resultMap.toString()); }else{ logger.info(" h5 , "); } } catch (Exception e) { logger.info(" :"+e.getMessage()); } finally { if(response != null){ try { response.close(); } catch (IOException e) { logger.info(" , :"+e.getMessage()); } } if(client != null){ try { client.close(); } catch (IOException e) { logger.info(" , :"+e.getMessage()); } } } JSONObject job=new JSONObject(); if(StringUtils.isNotBlank(pay_url)){ job.put("res",pay_url); }else{ job.put("res",""); } result.setData(job); return result; } , h5 , IP IP , app h5 , app , : h5 function GetRequest() { var url = location.search; // url "?" var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]); } } return theRequest; } var Request = new Object(); Request = GetRequest(); var prepay_id,packagevalue,type,redirect_url; prepay_id = Request['prepay_id']; packagevalue = Request['packagevalue']; type=Request['type']; // 1 2 // if(type==1){ redirect_url="http:// /pay/wxreturn.html"; }else{ redirect_url="http:// pay/wxreturn.html"; } window.location="https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id="+prepay_id+"&package="+packagevalue+"&redirect_url="+redirect_url; : /** * , h5 * @return */ @Override public Result callbackUrlOfficial(HttpServletRequest req) throws Exception{ String resString = XmlUtils.parseRequst(req); logger.info(" h5 :"+resString); Result result = new Result(); if(StringUtils.isNotBlank(resString)){ Map map = WXPayUtil.xmlToMap(resString); logger.info(" h5 map :"+map); String return_code = map.get("return_code"); logger.info(" h5 :"+return_code); if("SUCCESS".equals(return_code)){// SUCCESS: if(map.containsKey("sign")){ if(SignUtils.checkParam(map, WeiXinConstant.partnerkey)){// logger.info(" h5 !!!sign-success"); if("SUCCESS".equals(map.get("result_code"))){// SUCCESS: // // , List list =payServiceImpl.getPayResponse(map.get("out_trade_no")); if(list == null || list.size() == 0){ payServiceImpl.addPayResponse(map.get("out_trade_no"), map.get("transaction_id"), "5", map.toString()); // } return result; }else{ logger.info(" h5 : orderid="+map.get("attach")); result.setCode(SystemStatus.WX_ORDER_PAY_ERROR.CODE); result.setMsg(SystemStatus.WX_ORDER_PAY_ERROR.MSG); return result; } }else{ logger.info(" h5 : orderid="+map.get("attach")); result.setCode(SystemStatus.WX_SIGN_ERR.CODE); result.setMsg(SystemStatus.WX_SIGN_ERR.MSG+" "); return result; } }else{ logger.info(" h5 : orderid="+map.get("attach")); result.setCode(SystemStatus.WX_SIGN_ERR.CODE); result.setMsg(SystemStatus.WX_SIGN_ERR.MSG+" "); return result; } }else{ logger.info(" h5 , "+map.get("return_msg")); result.setCode(SystemStatus.PARAM_ERROR.CODE); result.setMsg(SystemStatus.PARAM_ERROR.MSG); return result; } }else{ result.setCode(SystemStatus.PARAM_ERROR.CODE); result.setMsg(SystemStatus.PARAM_ERROR.MSG); return result; } } h5 , :https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4 * * h5 , , :https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_3 , 。

좋은 웹페이지 즐겨찾기