java微信支付代码
/** * 接口编号【125】 接口描述【微信支付】 * * @param price * 充值金额 * @author chenp * @return * @throws Exception */ @RequestMapping(value = "v1/wechat_recharge", method = RequestMethod.POST) public @ResponseBody RespValue<Object> WeiXinPayFor(HttpServletRequest request, HttpServletResponse response, int price) throws Exception { if (this.unlawfulRequest(125, request)) { return new RespValue<Object>(null, RespCode.UNLAWFULREQ); } if (price <= 0) { throw new ServiceException("参数不能为空!"); } UserLogin userLogin = (UserLogin) request.getSession().getAttribute( "userLogin"); if (null == userLogin) { return new RespValue<Object>(null, RespCode.TIMEOUT); } WeChatParams ps = new WeChatParams(); // 附加参数【业务类型_会员ID_订单号】 ps.attach = "会员充值" + "_" + userLogin.getId(); ps.out_trade_no = StringUtils.getBetOrderNo(); if ("true".equalsIgnoreCase(WeChatConfig.WXPAY)) { ps.total_fee = String.valueOf(price * 100); } else { ps.total_fee = "1";// 以分为单位 } // 商品名称 ps.body = "会员充值"; Map<Object, Object> map = WeixinPayApp.getCodeUrl(ps); return new RespValue<Object>(map, "获取成功", RespValue.SUCCESS); } /** * APP端微信充值【回调方法】 * * @param request * @param response * @throws Exception */ @SuppressWarnings({ "unchecked", "unused" }) @RequestMapping(value = "v1/app_wechat_notify_url", method = RequestMethod.POST) public void wechat_notify_url_app(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<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); } // 微信支付的API密钥 String key = WeChatConfig.APIKEY_APP; // key // 判断签名是否正确 if (PayForUtil.isTenpaySign("UTF-8", packageParams, key)) { // ------------------------------ // 处理业务开始 // ------------------------------ String resXml = ""; if ("SUCCESS".equals((String) packageParams.get("result_code"))) { // 这里是支付成功 // 执行自己的业务逻辑开始 String app_id = (String) packageParams.get("appid"); String mch_id = (String) packageParams.get("mch_id"); String openid = (String) packageParams.get("openid"); String is_subscribe = (String) packageParams .get("is_subscribe");// 是否关注公众号 // 附加参数【会员充值_0bda32824db44d6f9611f1047829fa3b】--【业务类型_会员ID_订单号】 String attach = (String) packageParams.get("attach"); // 商户订单号 String out_trade_no = (String) packageParams .get("out_trade_no"); // 付款金额【以分为单位】 String total_fee = (String) packageParams.get("total_fee"); // 微信生成的交易订单号 String transaction_id = (String) packageParams .get("transaction_id");// 微信支付订单号 // 支付完成时间 String time_end = (String) packageParams.get("time_end"); String businessType = "";// 业务类型 String memberId = "";// 会员ID if (attach.indexOf("_") > -1) { String[] bodys = attach.split("_"); businessType = bodys[0]; memberId = bodys[1]; } if (businessType.equals("会员充值") && memberId.length() > 0) { // -----------------修改用户充值记录----------------// PayInfo pay = new PayInfo(); pay.setAddtime(new Date()); pay.setBody(attach); pay.setMemberId(memberId); pay.setOut_trade_no(out_trade_no); pay.setPaytype(2); pay.setTotal_fee(Integer.parseInt(total_fee) / 100 + ""); pay.setTradeno(transaction_id); pay.setBuz_type(businessType); userService.recharge(pay); } // 执行自己的业务逻辑结束 // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了. 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> "; } // ------------------------------ // 处理业务完毕 // ------------------------------ BufferedOutputStream out = new BufferedOutputStream( response.getOutputStream()); out.write(resXml.getBytes()); out.flush(); out.close(); } }
package com.lottery.wechat.utils; /** * 微信支付需要的一些参数 * @author chenp * */ public class WeChatParams { public String total_fee;//订单金额【备注:以分为单位】 public String body;//商品名称 public String out_trade_no;//商户订单号 public String attach;//附加參數 public String memberid;//会员ID }
package com.lottery.wechat.utils;/** * 微信支付配置文件 * @author chenp * */ public class WeChatConfig { /** * 微信服务号APPID */ public static String APPID_APP="wxa9dc06113fe3c758"; /** * 微信支付的商户号 */ public static String MCHID_APP="1463625102"; /** * 微信支付的API密钥 */ public static String APIKEY_APP="OchYg8NUN1sXagp8m1GYRujj7lc1fozG"; /** * 微信支付成功之后的回调地址【注意:当前回调地址必须是公网能够访问的地址】 */ public static String WECHAT_NOTIFY_URL_APP="http://118.89.35.44/app/v1/app_wechat_notify_url.do"; /** * 微信下单API地址 */ public static String UFDODER_URL="https://api.mch.weixin.qq.com/pay/unifiedorder"; /** * true为使用真实金额支付,false为使用测试金额支付(1分) */ public static String WXPAY="false"; }
package com.lottery.wechat.utils; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; /** * 微信支付【app】 * @author Administrator * */ public class WeixinPayApp { public static Logger lg=Logger.getLogger(WeixinPayApp.class); private static final int BLACK = 0xff000000; private static final int WHITE = 0xFFFFFFFF; /** * 获取微信支付的二维码地址 * @return * @author chenp * @throws Exception */ public static Map<Object,Object> getCodeUrl(WeChatParams ps) throws Exception { /** * 账号信息 */ String appid = WeChatConfig.APPID_APP;//微信服务号的appid String mch_id = WeChatConfig.MCHID_APP; //微信支付商户号 String key = WeChatConfig.APIKEY_APP; // 微信支付的API密钥 String notify_url = WeChatConfig.WECHAT_NOTIFY_URL_APP;//回调地址【注意,这里必须要使用外网的地址】 String ufdoder_url=WeChatConfig.UFDODER_URL;//微信下单API地址 String trade_type = "APP"; //类型【app支付】 /** * 时间字符串 */ String currTime = PayForUtil.getCurrTime(); String strTime = currTime.substring(8, currTime.length()); String strRandom = PayForUtil.buildRandom(4) + ""; String nonce_str = strTime + strRandom; /** * 参数封装 */ 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", ps.body);//支付的商品名称 packageParams.put("out_trade_no", ps.out_trade_no+nonce_str);//商户订单号【备注:每次发起请求都需要随机的字符串,否则失败。】 packageParams.put("total_fee", ps.total_fee);//支付金额 packageParams.put("spbill_create_ip", PayForUtil.localIp());//客户端主机 packageParams.put("notify_url", notify_url); packageParams.put("trade_type", trade_type); packageParams.put("attach", ps.attach);//额外的参数【业务类型+会员ID+支付类型】 String sign = PayForUtil.createSign("UTF-8", packageParams,key); //获取签名 System.out.println("sign:---"+sign); packageParams.put("sign", sign); String requestXML = PayForUtil.getRequestXml(packageParams);//将请求参数转换成String类型 lg.info("微信支付请求参数的报文"+requestXML); String resXml = HttpUtil.postData(ufdoder_url,requestXML); //解析请求之后的xml参数并且转换成String类型 lg.info("微信支付响应参数的报文"+resXml); Map<Object,Object>map = XMLUtil.doXMLParse(resXml); if("SUCCESS".equals(map.get("result_code"))){ //二次签名 SortedMap<Object,Object> sp = new TreeMap<Object,Object>(); sp.put("appid", appid); sp.put("partnerid", mch_id); sp.put("prepayid", map.get("prepay_id")); sp.put("noncestr", map.get("nonce_str")); sp.put("timestamp", (System.currentTimeMillis()/1000)+""); sp.put("package", "Sign=WXPay"); String spsign=PayForUtil.createSign("UTF-8",sp,key); //签名 System.out.println("spsign:---"+spsign); map.put("sign", spsign); map.put("timestamp", sp.get("timestamp")); map.put("packageValue", "Sign=WXPay"); }else{ lg.info("调用微信统一下单接口失败"); } return map; } /** * 将路径生成二维码图片 * @author chenp * @param content * @param response */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void encodeQrcode(String content,HttpServletResponse response){ if(StringUtils.isBlank(content)) return; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); BitMatrix bitMatrix = null; try { bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 250, 250,hints); BufferedImage image = toBufferedImage(bitMatrix); //输出二维码图片流 try { ImageIO.write(image, "png", response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } catch (WriterException e1) { e1.printStackTrace(); } } /** * 类型转换 * @author chenp * @param matrix * @return */ public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE); } } return image; } // 特殊字符处理 public static String UrlEncode(String src) throws UnsupportedEncodingException { return URLEncoder.encode(src, "UTF-8").replace("+", "%20"); } }
相关推荐
-
Sftp 上传下载 java
2019-1-8
-
ssm整合配置 java
2019-1-12
-
Spring防止Xss配置 java
2019-1-8
-
jdbc封装代码 java
2019-1-7
-
读取a.txt和b.txt中有序的序列,合并有序序列保存成c.txt java
2019-1-13
-
XStream 工具类 [ XmlUtil ] java
2019-1-8
-
图片处理工具类 java
2019-1-7
-
使用POI做的一个生成Excel的工具类。包含了导出Excel和解析Excel方法。 java
2019-1-7
-
使用Java实现八种基本排序 java
2019-1-8
-
基于apache-commons-email1.4 邮件发送 java
2019-1-8