java版微信支付开发

每次开发微信的产品都很多坑,无论是微信第三方登录还是支付,文档不齐全,api也不是很好用,这又是填坑帖子。

首先要到微信开放者平台申请,https://open.weixin.qq.com,经过很多繁琐的审核步骤,此处略过。。。

直接上代码。因为涉及到支付宝,如果没有用到可以直接删除支付宝的代码。


/**
 * @author lqz
 * @create 2017-04-26 14:39
 * @comment
 **/
public class WXpayConfig {
    public static final String APP_ID = "";
    public static final String APP_SECRET = "";
    public static final String MCH_ID = "";//商户号
    public static final String KEY_API = "";//KEY API密钥

}



/**
 * @author lqz
 * @create 2017-04-12 9:27
 * @comment  支付工具
 **/
public class PayUtils {

    /**
     * 生成订单
     * @param
     */
    public static ResponseResult createPayOrder(PayInfo payInfo){
        if (PayType.AliPay.equals(payInfo.getPaytype())){ //假如是支付宝
            return createAliPayOrder(payInfo);
        }else  if (PayType.WXPay.equals(payInfo.getPaytype())){ //假如是微信
            return createWXPayOrder(payInfo);
        }
        return null;
    }

    public static ResponseResult createWXPayOrder(PayInfo payInfo) {
        ResponseResult responseResult = new ResponseResult();
        SortedMap<String, Object> submitMap = new TreeMap<String, Object>();
        WeiXin wx = new WeiXin();
        Map xml = null;
        try {
            xml = wx.doInBackground(payInfo);
            submitMap.put("appid", WXpayConfig.APP_ID);
            submitMap.put("partnerid", WXpayConfig.MCH_ID);
            submitMap.put("prepayid", xml.get("prepay_id"));
            submitMap.put("noncestr", xml.get("nonce_str"));
            Long time = (System.currentTimeMillis() / 1000);
            submitMap.put("timestamp", time.toString());
            submitMap.put("package", "Sign=WXPay");
            //第二次生成签名
            String sign = createSign("UTF-8", submitMap);
            submitMap.put("sign", sign);
            responseResult.success(submitMap);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            responseResult.fail("操作失败");
        }
        return responseResult;
    }

    //随机字符串生成
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    //生成签名
    public static String createSign(String characterEncoding,SortedMap<String,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        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 + "&");
            }
        }
        sb.append("key=" + WXpayConfig.KEY_API);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
    /**
     * 生成支付宝订单
     * @param payInfo
     */
    private static ResponseResult createAliPayOrder(PayInfo payInfo) {
        ResponseResult responseResult = new ResponseResult();
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.SERVER_URL, AlipayConfig.APP_ID, AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(payInfo.getBody());
        model.setSubject(payInfo.getSubject());
        model.setOutTradeNo(payInfo.getOutTradeNo());
        model.setTimeoutExpress(payInfo.getTimeoutExpress());
        model.setTotalAmount(payInfo.getTotalAmount()+"");
        model.setProductCode(payInfo.getProductCode());
        request.setBizModel(model);
        request.setNotifyUrl(payInfo.getNotifyUrl());
        try {
            //这里和普通的接口调用不同,使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求,无需再做处理。
            responseResult.success(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            responseResult.fail("操作失败");
        }
        return responseResult;
    }

    public static enum  PayType{
        AliPay("支付宝"),WXPay("微信支付");
        private final String name;
        PayType(String name) {
            this.name = name;
        }
        public String getName() {
            return name;
        }

        public static PayType getPayType(String type){
            if (AliPay.toString().equalsIgnoreCase(type)){
                return AliPay;
            }else if (WXPay.toString().equalsIgnoreCase(type)){
                return WXPay;
            }
            return null;
        }
    }

    public static boolean verify(Map<String,String> params) throws AlipayApiException {
         return  AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.input_charset);
    }

    public static Map<String,String> getParams(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        return params;
    }

    public static class PayInfo{
        PayType paytype;
        String body; //内容
        String subject;  //主题
        String outTradeNo; //订单号
        String timeoutExpress = "30m";//超时
        Double totalAmount; //金额
        String productCode = "QUICK_MSECURITY_PAY"; //快速支付
        String notifyUrl;  //商户外网可以访问的异步地址

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }

        public String getSubject() {
            return subject;
        }

        public void setSubject(String subject) {
            this.subject = subject;
        }

        public String getOutTradeNo() {
            return outTradeNo;
        }

        public void setOutTradeNo(String outTradeNo) {
            this.outTradeNo = outTradeNo;
        }

        public String getTimeoutExpress() {
            return timeoutExpress;
        }

        public void setTimeoutExpress(String timeoutExpress) {
            this.timeoutExpress = timeoutExpress;
        }

        public Double getTotalAmount() {
            return totalAmount;
        }

        public void setTotalAmount(Double totalAmount) {
            this.totalAmount = totalAmount;
        }

        public String getProductCode() {
            return productCode;
        }

        public void setProductCode(String productCode) {
            this.productCode = productCode;
        }

        public String getNotifyUrl() {
            return notifyUrl;
        }

        public void setNotifyUrl(String notifyUrl) {
            this.notifyUrl = notifyUrl;
        }

        public PayType getPaytype() {
            return paytype;
        }

        public void setPaytype(PayType paytype) {
            this.paytype = paytype;
        }
    }
}



public class WeiXin {

    /**
     * APP_ID 应用从官方网站申请到的合法appId
     */
    public static final String WX_APP_ID = WXpayConfig.APP_ID;
    /**
     * 商户号
     */
    public static final String WX_PARTNER_ID = WXpayConfig.MCH_ID;
    /**
     * 接口链接
     */
    public static final String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    /**
     * 商户平台和开发平台约定的API密钥,在商户平台设置
     */
    public static final String key = WXpayConfig.KEY_API;

    public StringBuffer wechatPaySb = new StringBuffer();

    //封装产品信息
    public String getproduct(PayUtils.PayInfo payInfo) throws UnsupportedEncodingException {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attrs.getRequest();
        StringBuffer xml = new StringBuffer();
        String nonceStr = genNonceStr();
        xml.append("</xml>");
        List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
        packageParams.add(new BasicNameValuePair("appid", WX_APP_ID));
        //packageParams.add(new BasicNameValuePair("attach",inputMoney));
        //body为汉字是要转成UTF-8
        packageParams.add(new BasicNameValuePair("body",payInfo.getBody()));
        packageParams.add(new BasicNameValuePair("mch_id", WX_PARTNER_ID));
        packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
        packageParams.add(new BasicNameValuePair("notify_url", payInfo.getNotifyUrl()));
        packageParams.add(new BasicNameValuePair("out_trade_no", genTimeStamp()));
        packageParams.add(new BasicNameValuePair("spbill_create_ip", request.getRemoteAddr()));
        packageParams.add(new BasicNameValuePair("total_fee", payInfo.getTotalAmount().intValue()* 100+""));
        packageParams.add(new BasicNameValuePair("trade_type", "APP"));

        String sign = genPackageSign(packageParams);
        packageParams.add(new BasicNameValuePair("sign", sign));
        String xmlstring = toXml(packageParams);
        return xmlstring;
    }

    //获取随机验证参数
    private String genNonceStr() {
        Random random = new Random();
        return MD5Util.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    //获取包签名
    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(key);
        String packageSign = MD5Util.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return packageSign;
    }

    /**
     * 获得app前面
     *
     * @param params 参数
     * @return 签名以后的字符串
     */
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(key);
        this.wechatPaySb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5Util.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    /**
     * 将请求参数转换为xml格式
     *
     * @param params 参数list
     * @return xml字符串
     */
    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");
            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");
        return sb.toString();
    }


    public Map doInBackground(PayUtils.PayInfo payInfo) throws UnsupportedEncodingException {
        String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
        String entity = getproduct(payInfo);
//		System.out.println("entity:" + entity);
        String content = HttpUtil.sendPostUrl(url, entity,"UTF-8");
        Map<String, String> xml = null;
        try {
            xml = XMLUtil.doXMLParse(content);
        } catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return xml;
    }


    public String genTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    public static void main(String[] args) {
//        WeiXin wx = new WeiXin();
//        Map xml = wx.doInBackground(payInfo);
//        System.out.println(xml.get("prepay_id"));
    }


}

/**
 * xml工具类
 * @author miklchen
 *
 */
public class XMLUtil {

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws IOException, JDOMException {
		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 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(XMLUtil.getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		
		return sb.toString();
	}
	
	
}

public class HttpUtil {  
  
    /** 
     * 使用Get方式获取数据 
     *  
     * @param url 
     *            URL包括参数,http://HOST/XX?XX=XX&XXX=XXX 
     * @param charset 
     * @return 
     */  
    public static String sendGet(String url, String charset) {  
        String result = "";  
        BufferedReader in = null;  
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection connection = realUrl.openConnection();  
            // 设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 建立实际的连接  
            connection.connect();  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream(), charset));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送GET请求出现异常!" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        return result;  
    }  
  
    /**  
     * POST请求,字符串形式数据  
     * @param url 请求地址  
     * @param param 请求数据  
     * @param charset 编码方式  
     */  
    public static String sendPostUrl(String url, String param,String charset) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL newUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != param) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(param.getBytes("UTF-8"));
                outputStream.close();
            }

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(),charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String post(String url, String param) {
        String result = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列

        //得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(param, "UTF-8");
        httppost.addHeader("Content-Type", "text/xml");
        httppost.setEntity(postEntity);

        //根据默认超时限制初始化requestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
        httppost.setConfig(requestConfig);
        try {
            System.out.println("executing request " + httppost.getURI());

            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**  
     * POST请求,Map形式数据  
     * @param url 请求地址  
     * @param param 请求数据  
     * @param charset 编码方式  
     */  
    public static String sendPost(String url, Map<String, String> param,  
            String charset) {  
  
        StringBuffer buffer = new StringBuffer();  
        if (param != null && !param.isEmpty()) {  
            for (Map.Entry<String, String> entry : param.entrySet()) {  
                buffer.append(entry.getKey()).append("=")  
                        .append(URLEncoder.encode(entry.getValue()))  
                        .append("&");  
  
            }  
        }  
        buffer.deleteCharAt(buffer.length() - 1);  
  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());  
            // 发送请求参数  
            out.print(buffer);  
            // flush输出流的缓冲  
            out.flush();  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(  
                    conn.getInputStream(), charset));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送 POST 请求出现异常!" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输出流、输入流  
        finally {  
            try {  
                if (out != null) {  
                    out.close();  
                }  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }  
    
    
    
   
  
    public static void main(String[] args) {  
    }  
}  

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

    public final static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

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

}


maven导入这两个包。

<!-- https://mvnrepository.com/artifact/jdom/jdom -->
		<dependency>
			<groupId>jdom</groupId>
			<artifactId>jdom</artifactId>
			<version>1.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>

因为我是用idea开发的,比eclipse更多坑,就是编码问题,具体解决可以查看另外一个帖子。http://blog.youkuaiyun.com/liqingzhou1993/article/details/71107213
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值