1. 程式人生 > >微信公眾號支付java版本

微信公眾號支付java版本


回撥函式


@RequestMapping("/toPay")
	public String toPay(HttpServletRequest request, HttpServletResponse response, Model model){
		System.out.println("toPay success");
		try {
			String orderId = request.getParameter("orderId");
			System.out.println("in toPay,orderId:" + orderId);
			
			String totalFeeStr = request.getParameter("totalFee");
			Float totalFee = 0.0f;
			
			if(StringUtils.isNotBlank(totalFeeStr)){
				totalFee = new Float(totalFeeStr);
			}

			//網頁授權後獲取傳遞的引數
			//String userId = request.getParameter("userId"); 	
			String code = request.getParameter("code");
			System.out.println("code:"+code);
			//System.out.println("userId:"+userId);
			
			//獲取統一下單需要的openid
			String openId ="";
			String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ WxPayConfig.appid + "&secret=" + WxPayConfig.appsecret + "&code=" + code + "&grant_type=authorization_code";
			System.out.println("URL:"+URL);
			JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
			if (null != jsonObject) {
				openId = jsonObject.getString("openid");
				System.out.println("openId:" + openId);
			}
			
			//獲取openId後呼叫統一支付介面https://api.mch.weixin.qq.com/pay/unifiedorder
			//隨機數 
			//String nonce_str = "1add1a30ac87aa2db72f57a2375d8fec";
			String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
			//商品描述
			String body = orderId;
			//商戶訂單號
			String out_trade_no = orderId;
			//訂單生成的機器 IP
			String spbill_create_ip = request.getRemoteAddr();
			//總金額
			//TODO
			Integer total_fee = Math.round(totalFee*100);
			//Integer total_fee = 1;
			
			//商戶號
			//String mch_id = partner;
			//子商戶號  非必輸
			//String sub_mch_id="";
			//裝置號   非必輸
			//String device_info="";
			//附加資料
			//String attach = userId;
			//總金額以分為單位,不帶小數點
			//int total_fee = intMoney;
			//訂 單 生 成 時 間   非必輸
			//String time_start ="";
			//訂單失效時間      非必輸
			//String time_expire = "";
			//商品標記   非必輸
			//String goods_tag = "";
			//非必輸
			//String product_id = "";
					
			//這裡notify_url是 支付完成後微信發給該連結資訊,可以判斷會員是否支付成功,改變訂單狀態等。
			String notify_url = baseUrl + "/wx/notifyUrl.do";
			
			SortedMap<String, String> packageParams = new TreeMap<String, String>();
			packageParams.put("appid", WxPayConfig.appid);
			packageParams.put("mch_id", WxPayConfig.partner);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", total_fee+"");
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", WxPayConfig.trade_type);  
			packageParams.put("openid", openId);  

			RequestHandler reqHandler = new RequestHandler(request, response);
			reqHandler.init(WxPayConfig.appid, WxPayConfig.appsecret, WxPayConfig.partnerkey);
			
			String sign = reqHandler.createSign(packageParams);
			System.out.println("sign:"+sign);
			String xml="<xml>"+
					"<appid>"+WxPayConfig.appid+"</appid>"+
					"<mch_id>"+WxPayConfig.partner+"</mch_id>"+
					"<nonce_str>"+nonce_str+"</nonce_str>"+
					"<sign>"+sign+"</sign>"+
					"<body><![CDATA["+body+"]]></body>"+
					"<out_trade_no>"+out_trade_no+"</out_trade_no>"+
					"<total_fee>"+total_fee+""+"</total_fee>"+
					"<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
					"<notify_url>"+notify_url+"</notify_url>"+
					"<trade_type>"+WxPayConfig.trade_type+"</trade_type>"+
					"<openid>"+openId+"</openid>"+
					"</xml>";
			System.out.println("xml:"+xml);
			
			String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
			String prepay_id="";
			try {
				prepay_id = WeixinPayUtil.getPayNo(createOrderURL, xml);
				System.out.println("prepay_id:" + prepay_id);
				if(prepay_id.equals("")){
					request.setAttribute("ErrorMsg", "統一支付介面獲取預支付訂單出錯");
					response.sendRedirect("error.jsp");
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			String timestamp = Sha1Util.getTimeStamp();
			String packages = "prepay_id="+prepay_id;
			finalpackage.put("appId", WxPayConfig.appid);
			finalpackage.put("timeStamp", timestamp);
			finalpackage.put("nonceStr", nonce_str);
			finalpackage.put("package", packages);
			finalpackage.put("signType", WxPayConfig.signType);
			String finalsign = reqHandler.createSign(finalpackage);
			System.out.println("/jsapi?appid="+WxPayConfig.appid+"&timeStamp="+timestamp+"&nonceStr="+nonce_str+"&package="+packages+"&sign="+finalsign);
			
			model.addAttribute("appid", WxPayConfig.appid);
			model.addAttribute("timeStamp", timestamp);
			model.addAttribute("nonceStr", nonce_str);
			model.addAttribute("packageValue", packages);
			model.addAttribute("sign", finalsign);
			
			model.addAttribute("bizOrderId", orderId);
			model.addAttribute("orderId", orderId);
			model.addAttribute("payPrice", total_fee);
			System.out.println("orderId:---------------"+orderId);
			return "/jsapi";
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return null;
	}