微信扫码支付

一、发起付款请求

用于获取用户输入的商品名称,生成订单号,获取短链接并生成二维码,跳转显示页面

@Controller
@SessionAttributes(names = {"image"})
public class PayController {
    @Resource
    private OrderService orderService;
   @RequestMapping("/pay")
   public String pay(String orderId,String money,String body, Model model){
       String url = null;
       try {
           url = PayCommonUtil.weixin_pay("1",body,orderId);
       } catch (Exception e) {
           e.printStackTrace();
       }
       //生成付款二维码
       BufferedImage image = ZxingUtil.createImage(url,300,300);
       model.addAttribute("image",image);
       model.addAttribute("oid",orderId);
       return "payment";

   }
   @RequestMapping("/showImg")
   public void showImg(@SessionAttribute("image")BufferedImage image, HttpServletResponse response){
       if(image!=null){
           //发送到页面上
           try {
               ImageIO.write(image,"JPEG",response.getOutputStream());
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }
}

二、回调

@Controller
public class PayResultController {
    @Resource
    private OrderService orderService;

    @RequestMapping("/check")
    @ResponseBody
    public Integer check(String oid){
        Order order =  orderService.findById(oid);
        return order.getOrderStatus();
    }

    @RequestMapping("/result")
    public void result(HttpServletRequest request, HttpServletResponse response){
        try {
            weixin_notify(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void weixin_notify(HttpServletRequest request, HttpServletResponse response) throws Exception{
        InputStream inputStream ;
        //获取微信支付返回的xml结果
        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<String, String> m = XMLUtil.doXMLParse(sb.toString());

        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
        System.err.println(packageParams);
        //订单号
        String out_trade_no = (String)packageParams.get("out_trade_no");
        GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-e7e1c0ae2b064a78926f4b4d94c09296");
        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 total_fee = (String)packageParams.get("total_fee");
                System.err.println("mch_id:"+mch_id);
                System.err.println("openid:"+openid);
                System.err.println("is_subscribe:"+is_subscribe);
                System.err.println("out_trade_no:"+out_trade_no);
                System.err.println("total_fee:"+total_fee);
                System.err.println("支付成功");
                //通知微信,异步确认成功,必写
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                //修改数据库的订单状态
                orderService.update(out_trade_no,true);
                //发送者发送过来的消息

                goEasy.publish("pay_result", "true");


            } else {
                System.err.println("订单:"+out_trade_no+"支付失败,错误信息:"+ packageParams.get("err_code"));
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                orderService.update(out_trade_no,false);
                goEasy.publish("pay_result", "false");
            }
            //告诉微信已收到它返回的结果
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } else{
            System.err.println("通知签名验证失败");
            orderService.update(out_trade_no,false);
            goEasy.publish("pay_result", "false");
        }
    }

    @RequestMapping("/success")
    public String success(Model model){
        Integer type = SwingConstant.orderStatus.PENDING_DELIVERY;
        return "redirect:/myOrder?t="+ type;
    }

    @RequestMapping("/failed")
    public String failed(Model model){
        Integer type = SwingConstant.orderStatus.PENDING_PAY;
        return "redirect:/myOrder?t="+ type;
    }
}

三、工具类

1、HttpUtil

public class HttpUtil {
    private final static int CONNECT_TIMEOUT = 5000;
    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 (Exception e){
            System.err.println("ERROR connecting to "+urlStr +":"+e.getMessage());
        }finally {
            try{
                if(reader!=null){
                    reader.close();
                }
            }catch (Exception e){
            }
        }
        return null;
    }
}

2、MD5Util

public class MD5Util {
    /**
     * 编码,将字节数组转成可识别的字符串
     */
    private static String byteAarrayToHexString(byte b[]){
        StringBuffer resultSb = new StringBuffer();
        for(int i=0;i<b.length;i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }
    /**
     * 将自己转成可识别字符串
     * @param b
     * @return
     */
    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];
    }
    /**
     * 获取指定内容的MD5值
     */
    public static String MD5Encode(String origin,String charsetname) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String resultString = null;
        try{
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if(charsetname == null || "".equals(charsetname)){
                resultString = byteAarrayToHexString(md.digest(resultString.getBytes()));
            }else {
                resultString = byteAarrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultString;
    }
    private static final String hexDigits[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f",};
    public static String UrlEncode(String src)throws UnsupportedEncodingException{
        return URLEncoder.encode(src,"UTF-8".replace("+","%20"));
    }
}

3、PayCommonUtil

public class PayCommonUtil {
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object,Object> packageParams, String API_KEY) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        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();
        return tenpaySign.equals(mysign);
    }


    public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        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;
    }


    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();
    }

    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));
    }

    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    public static String weixin_pay( String order_price,String body, String out_trade_no) throws Exception {
        String appid = PayConfigUtil.APP_ID;
        String mch_id = PayConfigUtil.MCH_ID;
        String key = PayConfigUtil.API_KEY;
        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayCommonUtil.buildRandom(4) + "";
        String nonce_str = strTime + strRandom;
        //获取发起电脑的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);
        System.out.println("packageParams+======"+packageParams);
        String requestXML = PayCommonUtil.getRequestXml(packageParams);
        System.out.println("requestXML+======"+requestXML);
        String resXml = HttpUtil.postData(PayConfigUtil.UFDOOER_URL, requestXML);
        System.out.println("resXml+======"+resXml);
        Map map = XMLUtil.doXMLParse(resXml);
        String urlCode = (String) map.get("code_url");
        //返回付款的二维码的链接
        return urlCode;
    }
}

4、PayConfigUtil

public class PayConfigUtil {
    public static String APP_ID = "wx632c8f211f8122c6";
    public static String MCH_ID = "1497984412";
    public static String API_KEY = "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC";
    public static String UFDOOER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    public static String NOTIFY_URL = "http://47.99.221.117:8080/lefeng/result";
    public static String CREATE_IP = "114.242.26.51";
}

5、XMLUtil

public class XMLUtil {

    /**
     * 解析xml,返回第一级元素键值对
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml)throws JDOMException,IOException{
        System.out.println("strxml====="+strxml);
        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
     */
    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();
    }
}

6、ZxingUtil

public class ZxingUtil {
        public static Boolean encode(String contents, String format, int width, int height, String saveImgFilePath) {
            Boolean bool = false;
            BufferedImage image = createImage(contents,width,height);
            if (image != null) {
                bool = writeToFile(image, format, saveImgFilePath);
            }
            return bool;
        }
        
        public static void encode(String contents, int width, int height) {
            createImage(contents,width, height);
        }
        
        public static BufferedImage createImage(String contents ,int width, int
                height) {
            BufferedImage bufImg=null;
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 10);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            try {
                BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                        BarcodeFormat.QR_CODE, width, height, hints);
                MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001,
                        0xFFFFFFFF);
                bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bufImg;
        }

        public static Boolean writeToFile(BufferedImage bufImg, String format, String saveImgFilePath) {
            Boolean bool = false;
            try {
                bool = ImageIO.write(bufImg, format, new File(saveImgFilePath));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return bool;
            }
        }
}

四、页面接收GoEasy消息

<script type="text/javascript" th:src="@{http://cdn-hangzhou.goeasy.io/goeasy.js}"></script>
<script type="text/javascript">
    var goEasy = new GoEasy({
        appkey: 'BC-e7e1c0ae2b064a78926f4b4d94c09296'
    });
    //GoEasy-OTP可以对appkey进行有效保护,详情请参考:GoEasy-Reference
    goEasy.subscribe({
        channel:'pay_result',
        onMessage: function(message) {
            var data = message.content;
            alert(data);
            if(data == "true"){
               alert("付款成功");
               var s = $("#status");
               s.val(1);

			}else {
                alert("付款失败");
                var s = $("#status");
                s.val(0);
			}
            $("#form1").submit();
        }
    });
</script>

五、导包

<!--解析xml-->
		<dependency>
			<groupId>org.jdom</groupId>
			<artifactId>jdom</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>jaxen</groupId>
			<artifactId>jaxen</artifactId>
			<version>1.1.6</version>
		</dependency>
		<!--生成图片二维码-->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.2.3</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>io.goeasy</groupId>
			<artifactId>goeasy-sdk</artifactId>
			<version>0.3.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.8</version>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>goeasy</id>
			<name>goeasy</name>
			<url>http://maven.goeasy.io/content/repositories/releases/</url>
		</repository>
	</repositories>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值