PC端扫码支付,支付宝、微信支付对接

PC端扫码支付,支付宝、微信支付对接工具类以及Service调用。

依赖Jar:alipay-sdk-java20171201160035.jar (可上传值私服,使用pom配置)

pom.xml:    

************************************************pom. begin*******************************************************

                <dependency>

<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.51</version> 
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.1.0</version> 
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version> 
</dependency>


<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.8</version> 
</dependency>

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.5</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version> 
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.37</version> 

</dependency>

******************************************************pom  end******************************************************


工具类:

Assert.java

PayUtils.java

RSAUtils.java

SignUtil.java

WebUtils.java

XmlUtil.java

******************************************************utils begin******************************************************

Assert.java

package com.lzkj.csp.web.www.payutils;

import org.apache.commons.lang3.StringUtils;


public class Assert {
        public Assert() {
        }


        public static void isTrue(boolean expression, String message) {
            if(!expression) {
                throw new IllegalArgumentException(message);
            }
        }


        public static void isTrue(boolean expression) {
            isTrue(expression, "[Assertion failed] - this expression must be true");
        }


        public static void isNull(Object object, String message) {
            if(object != null) {
                throw new IllegalArgumentException(message);
            }
        }


        public static void isNull(Object object) {
            isNull(object, "[Assertion failed] - the object argument must be null");
        }


        public static void notNull(Object object, String message) {
            if(object == null) {
                throw new IllegalArgumentException(message);
            }
        }


        public static void notNull(Object object) {
            notNull(object, "[Assertion failed] - this argument is required; it must not be null");
        }



        public static void isNotEmpty(String text) {
            isNotEmpty(text, "[Assertion failed] - this String argument must have length; it must not be null or empty");
        }


        public static void isNotEmpty(String text, String message) {
            if(!StringUtils.isNotEmpty(text)) {
                throw new IllegalArgumentException(message);
            }
        }


        public static void doesNotContain(String textToSearch, String substring, String message) {
            if(StringUtils.isNotEmpty(textToSearch) && StringUtils.isNotEmpty(substring) && textToSearch.contains(substring)) {
                throw new IllegalArgumentException(message);
            }
        }


        public static void doesNotContain(String textToSearch, String substring) {
            doesNotContain(textToSearch, substring, "[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
        }


        public static void noNullElements(Object[] array, String message) {
            if(array != null) {
                Object[] var2 = array;
                int var3 = array.length;


                for(int var4 = 0; var4 < var3; ++var4) {
                    Object element = var2[var4];
                    if(element == null) {
                        throw new IllegalArgumentException(message);
                    }
                }
            }


        }


        public static void noNullElements(Object[] array) {
            noNullElements(array, "[Assertion failed] - this array must not contain any null elements");
        }


        public static void isInstanceOf(Class<?> clazz, Object obj) {
            isInstanceOf(clazz, obj, "");
        }


        public static void isInstanceOf(Class<?> type, Object obj, String message) {
            notNull(type, "Type to check against must not be null");
            if(!type.isInstance(obj)) {
                throw new IllegalArgumentException((StringUtils.isNotEmpty(message)?message + " ":"") + "Object of class [" + (obj != null?obj.getClass().getName():"null") + "] must be an instance of " + type);
            }
        }


        public static void isAssignable(Class<?> superType, Class<?> subType) {
            isAssignable(superType, subType, "");
        }


        public static void isAssignable(Class<?> superType, Class<?> subType, String message) {
            notNull(superType, "Type to check against must not be null");
            if(subType == null || !superType.isAssignableFrom(subType)) {
                throw new IllegalArgumentException(message + subType + " is not assignable to " + superType);
            }
        }


        public static void state(boolean expression, String message) {
            if(!expression) {
                throw new IllegalStateException(message);
            }
        }


        public static void state(boolean expression) {
            state(expression, "[Assertion failed] - this state invariant must be true");
        }
}




PayUtils.java

package com.lzkj.csp.web.www.payutils;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.lzkj.csp.web.www.paymodel.WechatClient;
import com.lzkj.csp.web.www.paymodel.WechatUnifiedOrder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;




public class PayUtils {


/**
     * 不可实例化
     */
    private PayUtils(){};

    /**
     * 支付宝请求客户端入口
     */
    private volatile static AlipayClient alipayClient = null;
    
    /**
     * 微信请求客户端入口
     */
    private volatile static WechatClient wechatClient = null;
    
    
    
    
    /**
     * 生成支付宝支付form
     * @return
     * @throws AlipayApiException 
     */
    public static String alipayOrder(Map<String, String> params,Map<String, String> clientMap) throws AlipayApiException{
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(params.get("return_url"));
        alipayRequest.setNotifyUrl(params.get("pay_notify"));
        // 待请求参数数组
        alipayRequest.setBizContent(JSON.toJSONString(params));
        
        if (alipayClient == null){
            synchronized (PayUtils.class){
                if (alipayClient == null){
                alipayClient = new DefaultAlipayClient(clientMap.get("gateway"),clientMap.get("app_id"),clientMap.get("app_private_key"),clientMap.get("param_type"),clientMap.get("charset"),clientMap.get("alipay_public_key"));
                }
            }
        }
       
        String form = alipayClient.pageExecute(alipayRequest).getBody();
        
        return form;
    }


    /**
     * 生成微信统一订单并获取code_url
     * @return
     */
    public static String  wxUnifiedOrder(WechatUnifiedOrder unifiedOrder,Map<String, String> clientMap){
    if (wechatClient == null){
             synchronized (PayUtils.class){
                 if (wechatClient == null){
                wechatClient = new WechatClient(clientMap.get("app_id"),clientMap.get("mch_id"),clientMap.get("app_secret"),clientMap.get("trade_type"));
                 }
             }
         }
        WechatUnifiedOrder.Response response =  wechatClient.unifiedOrder(unifiedOrder,clientMap.get("reqUrl"));
        if(null!=response && "SUCCESS".equals(response.getReturn_code()) && "SUCCESS".equals(response.getResult_code())){
            return response.getCode_url();
        }else{
            return null;
        }
    }


    /**
     * 生成二维码
     * @param code_url
     * @return
     */
public static void generateQRCode(String code_url,OutputStream out) throws WriterException, IOException {
        int width = 200;
        int height = 200;
        String format = "png";
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, format, out);
        out.flush();
        out.close();
    }
}



RSAUtils.java

/*
 * Copyright 2005-2015 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 */
package com.lzkj.csp.web.www.payutils;


import com.sun.istack.internal.NotNull;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * Utils - RSA加密/解密
 */
public final class RSAUtils {


/** 密钥算法 */
private static final String KEY_ALGORITHM = "RSA";


/** 加密/解密算法 */
private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";


/** 安全服务提供者 */
private static final Provider PROVIDER = new BouncyCastleProvider();


/**
* 不可实例化
*/
private RSAUtils() {
}


/**
* 生成密钥对

* @param keySize
*            密钥大小
* @return 密钥对
*/
public static KeyPair generateKeyPair(int keySize) {
Assert.state(keySize > 0);


try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM, PROVIDER);
keyPairGenerator.initialize(keySize);
return keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 生成私钥

* @param encodedKey
*            密钥编码
* @return 私钥
*/
public static PrivateKey generatePrivateKey(byte[] encodedKey) {

try {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM, PROVIDER);
return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 生成私钥

* @param keyString
*            密钥字符串(BASE64编码)
* @return 私钥
*/
public static PrivateKey generatePrivateKey(String keyString) {
Assert.isNotEmpty(keyString);


return generatePrivateKey(Base64.decodeBase64(keyString));
}


/**
* 生成公钥

* @param encodedKey
*            密钥编码
* @return 公钥
*/
public static PublicKey generatePublicKey(byte[] encodedKey) {
Assert.notNull(encodedKey);


try {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM, PROVIDER);
return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 生成公钥

* @param keyString
*            密钥字符串(BASE64编码)
* @return 公钥
*/
public static PublicKey generatePublicKey(@NotNull String keyString) {


return generatePublicKey(Base64.decodeBase64(keyString));
}


/**
* 获取密钥字符串

* @param key
*            密钥
* @return 密钥字符串(BASE64编码)
*/
public static String getKeyString(Key key) {
Assert.notNull(key);


return Base64.encodeBase64String(key.getEncoded());
}


/**
* 获取密钥

* @param type
*            类型
* @param inputStream
*            输入流
* @param password
*            密码
* @return 密钥
*/
public static Key getKey(String type, InputStream inputStream, String password) {
Assert.isNotEmpty(type);
Assert.notNull(inputStream);


try {
KeyStore keyStore = KeyStore.getInstance(type, PROVIDER);
keyStore.load(inputStream, password != null ? password.toCharArray() : null);
String alias = keyStore.aliases().hasMoreElements() ? keyStore.aliases().nextElement() : null;
return keyStore.getKey(alias, password != null ? password.toCharArray() : null);
} catch (KeyStoreException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (CertificateException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (UnrecoverableKeyException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 获取证书

* @param type
*            类型
* @param inputStream
*            输入流
* @return 证书
*/
public static Certificate getCertificate(String type, InputStream inputStream) {
Assert.isNotEmpty(type);
Assert.notNull(inputStream);


try {
CertificateFactory certificateFactory = CertificateFactory.getInstance(type, PROVIDER);
return certificateFactory.generateCertificate(inputStream);
} catch (CertificateException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 生成签名

* @param algorithm
*            签名算法
* @param privateKey
*            私钥
* @param data
*            数据
* @return 签名
*/
public static byte[] sign(String algorithm, PrivateKey privateKey, byte[] data) {
Assert.isNotEmpty(algorithm);
Assert.notNull(privateKey);
Assert.notNull(data);


try {
Signature signature = Signature.getInstance(algorithm, PROVIDER);
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (SignatureException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 验证签名

* @param algorithm
*            签名算法
* @param publicKey
*            公钥
* @param sign
*            签名
* @param data
*            数据
* @return 是否验证通过
*/
public static boolean verify(String algorithm, PublicKey publicKey, byte[] sign, byte[] data) {
Assert.isNotEmpty(algorithm);
Assert.notNull(publicKey);
Assert.notNull(sign);
Assert.notNull(data);


try {
Signature signature = Signature.getInstance(algorithm, PROVIDER);
signature.initVerify(publicKey);
signature.update(data);
return signature.verify(sign);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (SignatureException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 验证签名

* @param algorithm
*            签名算法
* @param certificate
*            证书
* @param sign
*            签名
* @param data
*            数据
* @return 是否验证通过
*/
public static boolean verify(String algorithm, Certificate certificate, byte[] sign, byte[] data) {
Assert.isNotEmpty(algorithm);
Assert.notNull(certificate);
Assert.notNull(sign);
Assert.notNull(data);


try {
Signature signature = Signature.getInstance(algorithm, PROVIDER);
signature.initVerify(certificate);
signature.update(data);
return signature.verify(sign);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (SignatureException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 加密

* @param publicKey
*            公钥
* @param data
*            数据
* @return 密文
*/
public static byte[] encrypt(PublicKey publicKey, byte[] data) {
Assert.notNull(publicKey);
Assert.notNull(data);


try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (BadPaddingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


/**
* 解密

* @param privateKey
*            私钥
* @param data
*            数据
* @return 明文
*/
public static byte[] decrypt(PrivateKey privateKey, byte[] data) {
Assert.notNull(privateKey);
Assert.notNull(data);


try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (BadPaddingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}


}



SignUtil.java

package com.lzkj.csp.web.www.payutils;


import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;


public class SignUtil {


    /**
     * 连接Map键值对
     *
     * @param map
     *            Map
     * @param prefix
     *            前缀
     * @param suffix
     *            后缀
     * @param separator
     *            连接符
     * @param ignoreEmptyValue
     *            忽略空值
     * @param ignoreKeys
     *            忽略Key
     * @return 字符串
     */
    public static String joinKeyValue(Map<String, Object> map, String prefix, String suffix, String separator,
                                  boolean ignoreEmptyValue, String... ignoreKeys) {
        List<String> list = new ArrayList<String>();
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = String.valueOf(entry.getValue());
                if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key)
                        && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) {
                    list.add(key + "=" + (value != null ? value : ""));
                }
            }
        }
        return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : "");
    }


    /**
     * 把request请求参数转换为Map<String,String>
     * @param request 该请求
     * @return Map<String,String>格式的参数
     */
    public static Map<String,String> request2Map(HttpServletRequest request){
        Enumeration<String> names = request.getParameterNames();
        Map<String, String> resData = new HashMap<String, String>();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            resData.put(name, request.getParameter(name));
        }
        return resData;
    }


    /**
     * Bean转map
     * @param bean 要转的bean
     * @return 返回一个TreeMap
     */
    public static TreeMap<String, String> bean2TreeMap(Object bean) {
        TreeMap<String, String> requestMap = new TreeMap<String, String>();
        Class<?> cls = bean.getClass();
        Field[] fields = cls.getDeclaredFields();
        try {
            for (int i = 0; i < fields.length; i++) {
                String key = fields[i].getName();
                    fields[i].setAccessible(true);
                    Object value = fields[i].get(bean);
                    if ("sign".equals(key) || value == null || StringUtils.isEmpty(value.toString())) {
                        continue;
                    }
                    requestMap.put(key, value.toString());
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return requestMap;
    }


}





WebUtils.java


/*
 * Copyright 2005-2015 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 */
package com.lzkj.csp.web.www.payutils;




import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




public final class WebUtils {


/** PoolingHttpClientConnectionManager */
private static final PoolingHttpClientConnectionManager HTTP_CLIENT_CONNECTION_MANAGER;


/** CloseableHttpClient */
private static final CloseableHttpClient HTTP_CLIENT;


static {
HTTP_CLIENT_CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build());
HTTP_CLIENT_CONNECTION_MANAGER.setDefaultMaxPerRoute(100);
HTTP_CLIENT_CONNECTION_MANAGER.setMaxTotal(200);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();
HTTP_CLIENT = HttpClientBuilder.create().setConnectionManager(HTTP_CLIENT_CONNECTION_MANAGER).setDefaultRequestConfig(requestConfig).build();
}


/**
* 不可实例化
*/
private WebUtils() {
}




/**
* 参数解析
*
* @param query
*            查询字符串
* @param encoding
*            编码格式
* @return 参数
*/
public static Map<String, String> parse(String query, String encoding) {


Charset charset;
if (StringUtils.isNotEmpty(encoding)) {
charset = Charset.forName(encoding);
} else {
charset = Charset.forName("UTF-8");
}
List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(query, charset);
Map<String, String> parameterMap = new HashMap<String, String>();
for (NameValuePair nameValuePair : nameValuePairs) {
parameterMap.put(nameValuePair.getName(), nameValuePair.getValue());
}
return parameterMap;
}


/**
* 解析参数

* @param query
*            查询字符串
* @return 参数
*/
public static Map<String, String> parse(String query) {


return parse(query, null);
}


/**
* POST请求

* @param url
*            URL
* @param parameterMap
*            请求参数
* @return 返回结果
*/
public static String post(String url, Map<String, Object> parameterMap) {


String result = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = String.valueOf(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
result = consumeResponse(httpResponse);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (ClientProtocolException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result;
}
/**
* POST请求
*
* @param url
*            URL
* @param inputStreamEntity
*            请求体
* @return 返回结果
*/
public static String post(String url, InputStreamEntity inputStreamEntity) {


String result = null;
try {
HttpPost httpPost = new HttpPost(url);
inputStreamEntity.setContentEncoding("UTF-8");
httpPost.setEntity(inputStreamEntity);
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
result = consumeResponse(httpResponse);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (ClientProtocolException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result;
}


/**
* GET请求

* @param url
*            URL
* @param parameterMap
*            请求参数
* @return 返回结果
*/
public static String get(String url, Map<String, Object> parameterMap) {


String result = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = String.valueOf(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
result = consumeResponse(httpResponse);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (ClientProtocolException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return result;
}


/**
* 利用证书请求微信
* @param certPath 证书路径
* @param passwd  证书密码
* @param uri 请求地址
* @param entity 请求体xml内容
* @return 得到的结果
*/
public static String post(String certPath,String passwd, String uri, InputStreamEntity entity) throws Exception{
String result = null;
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(certPath));
try {
keyStore.load(instream, passwd.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);


CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpPost = new HttpPost(uri);
entity.setContentEncoding("UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
result = consumeResponse(httpResponse);
} finally {
httpclient.close();
}
return result;
}


/**
* 处理返回的请求,拿到返回内容
* @param httpResponse 要处理的返回
* @return 返回的内容
*/
private static String consumeResponse(CloseableHttpResponse httpResponse){
String result = null;
try {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
result = EntityUtils.toString(httpEntity,"UTF-8");
EntityUtils.consume(httpEntity);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpResponse.close();
} catch (IOException ignored) {
}
}
return result;
}
}

XmlUtil.java


package com.lzkj.csp.web.www.payutils;




import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;


public class XmlUtil {




/**
* XML转对象

* @param xmlStr
* @param t
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T xmlToBean(String xmlStr, Class<T> t) {
try {
JAXBContext context = JAXBContext.newInstance(t);
Unmarshaller unmarshaller = context.createUnmarshaller();
T ts = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
return ts;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}


/**
* XML转对象

* @param t
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T xmlToBean(InputStream input, Class<T> t) {
try {
JAXBContext context = JAXBContext.newInstance(t);
Unmarshaller unmarshaller = context.createUnmarshaller();
T ts = (T) unmarshaller.unmarshal(new InputStreamReader(input,
"UTF-8"));
return ts;
} catch (JAXBException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}


/**
* 对象转XML

* @param out
* @param to
*/
public static String beanToXml(ByteArrayOutputStream out, Object to) {
try {
JAXBContext context = JAXBContext.newInstance(to.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(to, out);
return new String(out.toByteArray(), "UTF-8");
} catch (JAXBException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}


}

******************************************************utils end*********************************************************

工具类测试:

*************************************************utils test begin*********************************************************

package com.lzkj.csp.web.www.payutils;


import java.util.HashMap;
import java.util.Map;


import org.junit.Test;


import com.alipay.api.AlipayApiException;
import com.lzkj.csp.web.www.paymodel.WechatUnifiedOrder;


public class PayTest {
@Test
    public void testAlipay(){
        Map<String,String> paraMap = new HashMap<String,String>();
        paraMap.put("out_trade_no",System.currentTimeMillis()+"");//咱们的订单号
        paraMap.put("total_amount","0.01");//金额
        paraMap.put("subject","测试下单");//主题
        paraMap.put("product_code","QUICK_WAP_PAY");//与支付宝签约的类型
        paraMap.put("return_url","http://api.test.alipay.net/atinterface/receive_notify.htm");//前台通知地址
        paraMap.put("pay_notify","https://m.alipay.com/Gk8NF23");//成功付款回调
        paraMap.put("seller_id","mmgjnx2748@sandbox.com");//收款方账号
        
        Map<String,String> clientMap = new HashMap<String,String>();
        clientMap.put("gateway", "https://openapi.alipaydev.com/gateway.do");//支付宝网关地址
        clientMap.put("app_id", "2016082700322128");//应用号
        //商户的私钥
        clientMap.put("app_private_key", "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKpchr/m/YcfE+5XicteoOXOl/YtMYWoduLI9n1cHmSl131ZneU9mG4F+xt7YVqcni3JoIHX17GBnL8gjIaajINb/Pl7Q5MGLfOPzM7rJsRuNFFo/1+X7syr4TZoH06FCUIfsXAD3GvV21VO3m/a8J4kIE8k2PeEasT/S0hM5sppAgMBAAECgYAYXroL86Aq1yBDxRP6GqRLm30Tgy2FYC75jCPulOHoJe0oikxTAbevbX2ZVdH8Y1EhXalvSZAaXV8t3BseGjelSqOddvZGcFINdN+e4DjaZW8f/YDQW8dSDUtgOZFr2BsHYgEb24VK4War/M4AlDumZtM2lrkjl1Mw4Vs5WeuKAQJBAO1RltDAiD02xOZRZGCu/6In5XyCvm2GMnWsLHBnsoVfQ9KnNF6WDLyJRoy6uv/mw8SUpkPT+AH0SIkfJY+Vu8ECQQC3xZ/RNmifLEXD96sZIBH1NnZWeCewfjvgssWe3vltfrLvAntOvGhBSExuXOdI3BHY7ydkezM3PSn0BqbRY9ipAkEAsRAbxzqvK4Tuma0GiIBo6JJ9zU07STpD8bn5GhC0iIAQeV4ZW6z2acC+a4dyuDVzwPrrplXDh6m8aNpdSuj7wQJAJdPGC9h5PJpuWeI3E9roF2N4hGADO28ggCYMS6F2EjXMOyp1m0Vo6FcrdGQnL3YtLkw7/ZDmf+5VHmfoGp3E0QJAOMg3Gu+1aM3T812qYTinbCdJRFFgfQDR2WvkL0v88KPa8kqUBWmaQxjPlbOs7j2hv+hptypwx2yT5gxvUvGbTQ==");
        clientMap.put("param_type", "json");//参数类型
        clientMap.put("charset", "UTF-8");//编码
        //支付宝公钥
        clientMap.put("alipay_public_key", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB");
         
try {
String form = PayUtils.alipayOrder(paraMap,clientMap);
System.out.println("+++++++++++++++++++++++++++++++支付宝begin++++++++++++++++++++++++++++");
System.out.println(form);
System.out.println("+++++++++++++++++++++++++++++++支付宝end++++++++++++++++++++++++++++");
} catch (AlipayApiException e) {
e.printStackTrace();
System.out.println(e.getErrMsg());
System.out.println("+++++++++++++++++++++++++++++++支付宝end++++++++++++++++++++++++++++-");
}
        
       
    }

    @Test
    public void testWxPay(){
       WechatUnifiedOrder request = new WechatUnifiedOrder();
        request.setBody("测试商品");//商品描述
        request.setDetail("一个好商品");//商品详情 
        request.setGoods_tag("测试");//商品标记 
        request.setOut_trade_no(System.currentTimeMillis()+"");//商户订单号 
        request.setFee_type("CNY");//货币类型  默认人民币:CNY
        request.setTotal_fee(1000);//总金额 单位分
        request.setSpbill_create_ip("127.0.0.1");//终端IP
        request.setTime_start(System.currentTimeMillis()+"");//交易起始时间
        //request.setLimit_pay("");//指定支付方式
        request.setNotify_url("http://www.weixin.qq.com/wxpay/pay.php");//支付成功回调
        
        Map<String, String> clientMap = new HashMap<String,String>();
        clientMap.put("app_id", "wxc43157e3f98c1cae");//应用ID
        clientMap.put("mch_id", "18514008880");//商户id
        clientMap.put("app_secret", "1dbc76a147087e1c82580a8ac2c34740");//身份密钥
        clientMap.put("trade_type", "NATIVE");//支付类型
        clientMap.put("reqUrl", "https://api.mch.weixin.qq.com/pay/unifiedorder");//统一下单地址
        
        System.out.println("+++++++++++++++++++++++++++++++微信begin++++++++++++++++++++++++++++");
        String s = PayUtils.wxUnifiedOrder(request,clientMap);
        System.out.println(s);
        System.out.println("+++++++++++++++++++++++++++++++微信end++++++++++++++++++++++++++++");
    }
}


*************************************************utils test end*******************************************************


实际开发过程中往往封装成Service:

PaymentParam.java

PaymentView.java

AlipayService.java

AlipayServiceImpl.java

WxpayService.java

WxpayServiceImpl.java


*************************************************service begin*******************************************************

PaymentParam.java

package com.lzkj.csp.web.www.oracle.alpha.model;


public class PaymentParam {

/**
*商品订单号 
**/
private String orderNum;
/**
*订单金额 
**/
private String orderAmount;
/**
*商品名称 
**/
private String goodsName;
/**
*商品描述 
**/
private String goodsDetails;

/**
*终端IP 
**/
private String spbillCreateIp;



public String getSpbillCreateIp() {
return spbillCreateIp;
}
public void setSpbillCreateIp(String spbillCreateIp) {
this.spbillCreateIp = spbillCreateIp;
}
public String getOrderNum() {
return orderNum;
}
public void setOrderNum(String orderNum) {
this.orderNum = orderNum;
}
public String getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(String orderAmount) {
this.orderAmount = orderAmount;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsDetails() {
return goodsDetails;
}
public void setGoodsDetails(String goodsDetails) {
this.goodsDetails = goodsDetails;
}


}



PaymentView.java

package com.lzkj.csp.web.www.oracle.alpha.model;


public class PaymentView {


/**
*调用支付返回信息 
**/
private String resultInfo;




public String getResultInfo() {
return resultInfo;
}


public void setResultInfo(String resultInfo) {
this.resultInfo = resultInfo;
}



}


AlipayService.java

package com.lzkj.csp.web.www.oracle.alpha.service;


import com.lzkj.csp.web.www.oracle.alpha.model.PaymentParam;
import com.lzkj.csp.web.www.oracle.alpha.model.PaymentView;


/**
 *支付宝支付 
 **/
public interface AlipayService {
public PaymentView pay(PaymentParam paymentParam);

}



AlipayServiceImpl.java

package com.lzkj.csp.web.www.oracle.alpha.service.impl;


import java.util.HashMap;
import java.util.Map;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import com.alipay.api.AlipayApiException;
import com.lzkj.csp.web.www.oracle.alpha.model.PaymentParam;
import com.lzkj.csp.web.www.oracle.alpha.model.PaymentView;
import com.lzkj.csp.web.www.oracle.alpha.service.AlipayService;
import com.lzkj.csp.web.www.payutils.PayUtils;
/**
 *支付宝支付 
 **/
@Service
public class AlipayServiceImpl implements AlipayService {


@Value("#{configProperties['product_code']}")
private String product_code;//与支付宝签约的类型

@Value("#{configProperties['return_url']}")
private String return_url;//前台通知地址

@Value("#{configProperties['param_type']}")
private String param_type;//参数类型

@Value("#{configProperties['charset']}")
private String charset;//编码

@Value("#{configProperties['seller_id']}")
private String seller_id;//收款方账号

@Value("#{configProperties['gateway']}")
private String gateway;//支付宝网关地址

@Value("#{configProperties['pay_notify']}")
private String pay_notify;//成功付款回调

@Value("#{configProperties['app_id']}")
private String app_id;//应用号

@Value("#{configProperties['app_private_key']}")
private String app_private_key;//商户的私钥

@Value("#{configProperties['alipay_public_key']}")
private String alipay_public_key;//支付宝公钥

@Override
public PaymentView pay(PaymentParam paymentParam) {

PaymentView paymentView = new PaymentView();

Map<String,String> paraMap = new HashMap<String,String>();
        paraMap.put("out_trade_no",paymentParam.getOrderNum());//咱们的订单号
        paraMap.put("total_amount",paymentParam.getOrderAmount());//金额
        paraMap.put("subject",paymentParam.getGoodsName());//主题
        paraMap.put("product_code",product_code);//与支付宝签约的类型
        paraMap.put("return_url",return_url);//前台通知地址
        paraMap.put("pay_notify",pay_notify);//成功付款回调
        paraMap.put("seller_id",seller_id);//收款方账号
        
        Map<String,String> clientMap = new HashMap<String,String>();
        clientMap.put("gateway",gateway);//支付宝网关地址
        clientMap.put("app_id",app_id);//应用号
        //商户的私钥
        clientMap.put("app_private_key",app_private_key);
        clientMap.put("param_type",param_type);//参数类型
        clientMap.put("charset",charset);//编码
        //支付宝公钥
        clientMap.put("alipay_public_key",alipay_public_key);
         
try {
paymentView.setResultInfo(PayUtils.alipayOrder(paraMap,clientMap));
} catch (AlipayApiException e) {

return paymentView;
}

return paymentView;
}


}


WxpayService.java

package com.lzkj.csp.web.www.oracle.alpha.service;


import com.lzkj.csp.web.www.oracle.alpha.model.PaymentParam;
import com.lzkj.csp.web.www.oracle.alpha.model.PaymentView;


/**
 *微信支付 
 **/
public interface WxpayService {
public PaymentView pay(PaymentParam paymentParam);
}

WxpayServiceImpl.java

package com.lzkj.csp.web.www.oracle.alpha.service.impl;


import java.util.HashMap;
import java.util.Map;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import com.lzkj.csp.web.www.oracle.alpha.model.PaymentParam;
import com.lzkj.csp.web.www.oracle.alpha.model.PaymentView;
import com.lzkj.csp.web.www.oracle.alpha.service.WxpayService;
import com.lzkj.csp.web.www.paymodel.WechatUnifiedOrder;
import com.lzkj.csp.web.www.payutils.PayUtils;


/**
 *微信支付 
 **/
@Service
public class WxpayServiceImpl implements WxpayService {



@Value("#{configProperties['fee_type']}")
private String fee_type;//货币类型

@Value("#{configProperties['notify_url']}")
private String notify_url;//支付成功回调

@Value("#{configProperties['app_id']}")
private String app_id;//应用ID

@Value("#{configProperties['mch_id']}")
private String mch_id;//商户id

@Value("#{configProperties['app_secret']}")
private String app_secret;//身份密钥

@Value("#{configProperties['trade_type']}")
private String trade_type;//支付类型

@Value("#{configProperties['reqUrl']}")
private String reqUrl;//统一下单地址(请求地址)


@Override
public PaymentView pay(PaymentParam paymentParam) {
PaymentView paymentView = new PaymentView();

WechatUnifiedOrder request = new WechatUnifiedOrder();
        request.setBody(paymentParam.getGoodsName());//商品描述
        request.setDetail(paymentParam.getGoodsDetails());//商品详情 
        request.setGoods_tag(paymentParam.getGoodsName());//商品标记 
        request.setOut_trade_no(paymentParam.getOrderNum());//商户订单号 
        request.setFee_type(fee_type);//货币类型  默认人民币:CNY
        request.setTotal_fee(Integer.valueOf(paymentParam.getOrderAmount())*100);//总金额 单位分
        request.setSpbill_create_ip(paymentParam.getSpbillCreateIp());//终端IP
        request.setTime_start(System.currentTimeMillis()+"");//交易起始时间
        request.setNotify_url(notify_url);//支付成功回调
        
        Map<String, String> clientMap = new HashMap<String,String>();
        clientMap.put("app_id",app_id);//应用ID
        clientMap.put("mch_id",mch_id);//商户id
        clientMap.put("app_secret",app_secret);//身份密钥
        clientMap.put("trade_type",trade_type);//支付类型
        clientMap.put("reqUrl",reqUrl);//统一下单地址
        
        paymentView.setResultInfo(PayUtils.wxUnifiedOrder(request,clientMap));
        
return paymentView;
}


}


*************************************************service end*******************************************************

Service层 properties 配置:

alipay.properties

#与支付宝签约的类型
product_code=QUICK_WAP_PAY
#前台通知地址
return_url=http://api.test.alipay.net/atinterface/receive_notify.htm
#参数类型
param_type=json
#编码
charset=UTF-8
#收款方账号
seller_id=mmgjnx2748@sandbox.com
#支付宝网关地址
gateway=https://openapi.alipaydev.com/gateway.do
#成功付款回调
pay_notify=https://m.alipay.com/Gk8NF23
#应用号
app_id=2016082700322128
#商户的私钥
app_private_key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKpchr/m/YcfE+5XicteoOXOl/YtMYWoduLI9n1cHmSl131ZneU9mG4F+xt7YVqcni3JoIHX17GBnL8gjIaajINb/Pl7Q5MGLfOPzM7rJsRuNFFo/1+X7syr4TZoH06FCUIfsXAD3GvV21VO3m/a8J4kIE8k2PeEasT/S0hM5sppAgMBAAECgYAYXroL86Aq1yBDxRP6GqRLm30Tgy2FYC75jCPulOHoJe0oikxTAbevbX2ZVdH8Y1EhXalvSZAaXV8t3BseGjelSqOddvZGcFINdN+e4DjaZW8f/YDQW8dSDUtgOZFr2BsHYgEb24VK4War/M4AlDumZtM2lrkjl1Mw4Vs5WeuKAQJBAO1RltDAiD02xOZRZGCu/6In5XyCvm2GMnWsLHBnsoVfQ9KnNF6WDLyJRoy6uv/mw8SUpkPT+AH0SIkfJY+Vu8ECQQC3xZ/RNmifLEXD96sZIBH1NnZWeCewfjvgssWe3vltfrLvAntOvGhBSExuXOdI3BHY7ydkezM3PSn0BqbRY9ipAkEAsRAbxzqvK4Tuma0GiIBo6JJ9zU07STpD8bn5GhC0iIAQeV4ZW6z2acC+a4dyuDVzwPrrplXDh6m8aNpdSuj7wQJAJdPGC9h5PJpuWeI3E9roF2N4hGADO28ggCYMS6F2EjXMOyp1m0Vo6FcrdGQnL3YtLkw7/ZDmf+5VHmfoGp3E0QJAOMg3Gu+1aM3T812qYTinbCdJRFFgfQDR2WvkL0v88KPa8kqUBWmaQxjPlbOs7j2hv+hptypwx2yT5gxvUvGbTQ==
#支付宝公钥
alipay_public_key=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIgHnOn7LLILlKETd6BFRJ0GqgS2Y3mn1wMQmyh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB

wxpay.properties


#货币类型
fee_type=CNY
#支付成功回调
notify_url=http://www.weixin.qq.com/wxpay/pay.php
#应用ID
app_id=wxc43157e3f98c1cae
#商户id
mch_id=18514008880
#身份密钥
app_secret=1dbc76a147087e1c82580a8ac2c34740
#支付类型
trade_type=NATIVE
#统一下单地址(请求地址)
reqUrl=https://api.mch.weixin.qq.com/pay/unifiedorder


























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值