import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WechatPay {
/**
*
* @param params:请求参数
* @return 这里调起支付宝支付,生成支付链接
* @throws RunTimeException
*/
public Object createAlipayUrl(Map<String, String> params) throws RunTimeException {
/* 把请求参数打包成map集合 */
Map<String, String> param = buildRequestPara(params);
/* 生成签名结果 */
String mysign = sign(param);
/* 签名结果与签名方式加入请求提交参数组中 */
param.put("sign", mysign);
param.put("sign_type", "MD5");
StringBuffer sb = new StringBuffer("请求url");
List<String> keys = new ArrayList<String>(param.keySet());
for (int i = 0, size = keys.size(); i < size; i++) {
String key = keys.get(i);
String value = param.get(key);
sb.append("&").append(key).append("=").append(value);
}
return sb.toString();
}
//通过排序,然后再MD5加密
private String sign(Map<String, String> param) {
/** 把所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 */
String prestr = createLinkString(param);
return DigestUtils.md5Hex(getContentBytes(prestr + propertiesConfig.getProperty("alipay_key"),"utf-8"));
}
/**
* <p>
* Description:[去掉空值和参数签名]
* </p>
*
* @param paramsMap
* @return
*/
public static Map<String, String> parameterFilter(Map<String, String> paramsMap) {
Map<String, String> result = new HashMap<String, String>();
if (paramsMap == null || paramsMap.isEmpty()) {
return result;
}
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
String key = param.getKey();
String value = param.getValue();
if (StringUtils.isBlank(value) || StringUtils.equalsIgnoreCase(key, "sign")
|| StringUtils.equalsIgnoreCase(key, "sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
private Map<String, String> buildRequestPara() {
Map<String, String> param = new HashMap<String, String>();
param.put("service", "create_direct_pay_by_user");
param.put("partner", "");//
param.put("_input_charset", "utf-8");//编码
param.put("payment_type", "1");
param.put("notify_url", "支付成功异常回调通知地址");
param.put("return_url", "支付成功跳转地址");
param.put("seller_email", "");//支付宝账号
param.put("out_trade_no", "订单号");
param.put("total_fee", "总价钱");
param.put("body", "");//好像是购买详情,具体看支付文档,记不太清楚
param.put("subject","具体描述");
param.put("anti_phishing_key", "");// 防钓鱼时间戳
param.put("exter_invoke_ip", "");// 客户端的IP地址
return parameterFilter(param);
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
public static byte[] getContentBytes(String content, String charset) {
if (StringUtils.isBlank(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
}
catch (UnsupportedEncodingException e) {
throw new RunTimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
}