开发准备:服务商账号信息 子商户账号信息 服务商的API证书
PayUtil工具类最下方
Constants为常量类
1 服务商支付java代码
public static Json fwsWxPay(Params params, HttpServletRequest request, String itemNo, String type) {
Json json = new Json();
try {
String openid = params.getOpenId();
//生成的随机字符串
String nonce_str = StringUtils.getRandomStringByLength(32);
//商品名称
String body = type;
//获取本机的ip地址
String spbill_create_ip = IpUtils.getIpAddr(request);
String orderNo = itemNo;
String money = String.valueOf((int) Math.ceil(params.getTotalFee().doubleValue() * 100));
Map<String, String> packageParams = new HashMap<String, String>();
packageParams.put("appid", Constants.fwh_app_id);
packageParams.put("sub_appid", Constants.APP_ID);
packageParams.put("mch_id", Constants.fwh_mch_id);
packageParams.put("sub_mch_id", Constants.MCH_ID);
packageParams.put("nonce_str", nonce_str);
//nonce_str
packageParams.put("body", body);
packageParams.put("out_trade_no", orderNo);//商户订单号
packageParams.put("total_fee", money);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", Constants.NOTIFY_URL);
packageParams.put("trade_type", Constants.TRADETYPE);
packageParams.put("sub_openid", openid);
// 除去数组中的空值和签名参数
packageParams = PayUtil.paraFilter(packageParams);
String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
//MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
String mysign = PayUtil.sign(prestr, Constants.fws_KEY, "utf-8").toUpperCase();
logger.info("=======================第一次签名:" + mysign + "=====================");
//拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
String xml = "<xml>" + "<appid>" + Constants.fwh_app_id + "</appid>"
+ "<sub_appid>"+ Constants.APP_ID+"</sub_appid>"
+ "<sub_mch_id>"+ Constants.MCH_ID+"</sub_mch_id>"
+ "<body><![CDATA[" + body + "]]></body>"
+ "<mch_id>" + Constants.fwh_mch_id + "</mch_id>"
+ "<nonce_str>" + nonce_str + "</nonce_str>"
+ "<notify_url>" + Constants.NOTIFY_URL + "</notify_url>"
+ "<sub_openid>" + openid + "</sub_openid>"
+ "<out_trade_no>" + orderNo + "</out_trade_no>"
+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
+ "<total_fee>" + money + "</total_fee>"
+ "<trade_type>" + Constants.TRADETYPE + "</trade_type>"
+ "<sign>" + mysign + "</sign>"
+ "</xml>";
logger.info("调试模式_统一下单接口 请求XML数据:" + xml);
//调用统一下单接口,并接受返回的结果
String result = PayUtil.httpRequest(Constants.PAY_URL, "POST", xml);
logger.info("调试模式_统一下单接口 返回XML数据:" + result);
//校验下单是否成功
if (StringKit.isEmpty(result)) {
json.setSuccess(false);
json.setMsg("统一下单返回结果有误");
}
// 将解析结果存储在HashMap中
Map map = PayUtil.parseXmlToList2(result);
//校验解析结果是否正确
if (ObjectKit.isNull(map)) {
json.setSuccess(false);
json.setMsg("统一下单解析结果有误");
return json;
}
String return_code = (String) map.get("return_code");//返回状态码
String result_code = (String) map.get("result_code");
logger.info("return_code:" + return_code);
//返回给移动端需要的参数
Map<String, Object> response = new HashMap<String, Object>();
if (return_code.equals("SUCCESS") && "SUCCESS".equals(result_code)) {
// 业务结果
String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
logger.info("prepay_id" + prepay_id);
response.put("nonceStr", nonce_str);
response.put("package", "prepay_id=" + prepay_id);
Long timeStamp = System.currentTimeMillis() / 1000;
response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
String stringSignTemp = "appId=" + Constants.APP_ID + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=" + Constants.SIGNTYPE + "&timeStamp=" + timeStamp;
logger.info("stringSignTemp:" + stringSignTemp);
//再次签名,这个签名用于小程序端调用wx.requesetPayment方法
String paySign = PayUtil.sign(stringSignTemp, Constants.fws_KEY, "utf-8").toUpperCase();
logger.info("=======================第二次签名:" + paySign + "=====================");
response.put("paySign", paySign);
//更新订单信息
//业务逻辑代码
response.put("appid", Constants.APP_ID);
json.setSuccess(true);
json.setData(response);
} else if ("SUCCESS".equals(return_code) && "FAIL".equals(result_code)) {
json.setSuccess(false);
json.setMsg((String) map.get("err_code_des"));
//否则返回下单失败
} else {
json.setSuccess(false);
json.setMsg("统一下单失败");
}
} catch (Exception e) {
e.printStackTrace();
json.setSuccess(false);
json.setMsg("统一下单异常");
}
return json;
}
注意 appid是服务商的appid subappid才是子商户的小程序的appid mchid同理
签名用的秘钥是服务商的API秘钥
fwh_app_id 服务商appid
APP_ID 子服务商appid
fwh_mch_id 服务商号
MCH_ID 子服务商号
fws_KEY 服务商的key
接口调用统一下单接口
PAY_URL = https://api.mch.weixin.qq.com/pay/unifiedorder
小程序方面和普通微信支付相同 不需要改动 返回值一样
2、服务商支付退款代码
public static Map fwsWxRefund (String nonce_str,String out_trade_no,String out_refund_no ,String money,String appMoney){
try {
Map<String, String> packageParams = new HashMap<String, String>();
packageParams.put("appid", Constants.fwh_app_id);
packageParams.put("sub_appid", Constants.APP_ID);
packageParams.put("mch_id", Constants.fwh_mch_id);
packageParams.put("sub_mch_id", Constants.MCH_ID);
packageParams.put("nonce_str", nonce_str);
packageParams.put("out_trade_no", out_trade_no);//商户订单号
packageParams.put("out_refund_no", out_refund_no);//商户退款订单号
packageParams.put("total_fee", money);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
packageParams.put("refund_fee", appMoney);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
// 除去数组中的空值和签名参数
packageParams = PayUtil.paraFilter(packageParams);
String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
//MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
String mysign = PayUtil.sign(prestr, Constants.fws_KEY, "utf-8").toUpperCase();
logger.info("=======================第一次签名:" + mysign + "=====================");
//拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
String xml = "<xml>" + "<appid>" + Constants.fwh_app_id + "</appid>"
+ "<sub_appid>"+ Constants.APP_ID+"</sub_appid>"
+ "<sub_mch_id>"+ Constants.MCH_ID+"</sub_mch_id>"
+ "<mch_id>" + Constants.fwh_mch_id + "</mch_id>"
+ "<nonce_str>" + nonce_str + "</nonce_str>"
+ "<out_trade_no>" + out_trade_no + "</out_trade_no>"
+ "<out_refund_no>" + out_refund_no + "</out_refund_no>"
+ "<total_fee>" + money + "</total_fee>"
+ "<refund_fee>" + appMoney + "</refund_fee>"
+ "<sign>" + mysign + "</sign>"
+ "</xml>";
logger.info("退款接口 请求XML数据:" + xml);
//调用统一下单接口,并接受返回的结果
String result = PayUtil.refundHttpRequest(Constants.REFUND_URL, xml);
logger.info("退款接口 返回XML数据:" + result);
// 将解析结果存储在HashMap中
return PayUtil.parseXmlToList2(result);
} catch (Exception e){
e.printStackTrace();
return null;
}
}
注意:参数和支付参数类似 秘钥使用服务商秘钥 退款证书也是服务商的证书
工具类
public class PayUtil {
private static final Logger log = LoggerFactory.getLogger(PayUtil.class);
/**
* 签名字符串
*
* @param text 需要签名的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static String sign(String text, String key, String input_charset) {
text = text + "&key=" + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 签名字符串
*
* @param text 需要签名的字符串
* @param sign 签名结果
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if (mysign.equals(sign)) {
return true;
} else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
public static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
/**
* 生成6位或10位随机数 param codeLength(多少位)
*
* @return
*/
public static String createCode(int codeLength) {
String code = "";
for (int i = 0; i < codeLength; i++) {
code += (int) (Math.random() * 9);
}
return code;
}
private static boolean isValidChar(char ch) {
if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
return true;
if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
return true;// 简体中文汉字编码
return false;
}
/**
* 除去数组中的空值和签名参数
*
* @param sArray 签名参数组
* @return 去掉空值与签名参数后的新签名参数组
*/
public static Map<String, String> paraFilter(Map<String, String> sArray) {
Map<String, String> result = new HashMap<String, String>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
|| key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
*
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
* @param requestUrl 请求地址
* @param requestMethod 请求方法
* @param outputStr 参数
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
// 创建SSLContext
StringBuffer buffer = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//往服务器端写内容
if (null != outputStr) {
OutputStream os = conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
// 读取服务器端返回的内容
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* 微信退款请求方法
*/
public static String refundHttpRequest(String url, String data) throws Exception {
/**
* 注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的
*/
KeyStore keyStore = KeyStore.getInstance("PKCS12");
//公司证书
FileInputStream instream = new FileInputStream(new File(Constants.CERT_ADD));//P12文件在服务器磁盘中的目录
try {
/**
* 此处要改成你的MCHID
* */
keyStore.load(instream, Constants.fwh_mch_id.toCharArray());//这里写密码..默认是你的MCHID
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
/**
* 此处要改成你的MCHID
* */
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, Constants.fwh_mch_id.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 httpost = new HttpPost(url); // 设置响应头信息
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
*
* @param strxml
* @return
* @throws
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws Exception {
if (null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = String2Inputstream(strxml);
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 = getChildrenText(children);
}
m.put(k, v);
}
//关闭流
in.close();
return m;
}
@SuppressWarnings({"unused", "rawtypes", "unchecked"})
public static Map parseXmlToList2(String strXML) throws Exception {
Map data = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
String FEATURE = null;
try {
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
documentBuilderFactory.setFeature(FEATURE, true);
FEATURE = "http://xml.org/sax/features/external-general-entities";
documentBuilderFactory.setFeature(FEATURE, false);
FEATURE = "http://xml.org/sax/features/external-parameter-entities";
documentBuilderFactory.setFeature(FEATURE, false);
FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
documentBuilderFactory.setFeature(FEATURE, false);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
} catch (ParserConfigurationException e) {
log.error("ParserConfigurationException was thrown. The feature '" + FEATURE + "' is probably not supported by your XML processor.");
}
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
}
return data;
}
/**
* 获取子结点的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(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
回调函数就不写了 都是些业务逻辑 和正常支付渠道一样