MiniAppsPayController 类
package com.junfunsoft.cloud.chudun.base.controller.miniApps;
import com.junfunsoft.cloud.chudun.base.model.T_JC_CHUSHI;
import com.junfunsoft.cloud.chudun.base.model.T_JC_DINGDAN;
import com.junfunsoft.cloud.chudun.base.model.T_JC_TUIKUAN;
import com.junfunsoft.cloud.chudun.base.model.T_JC_ZHIFU;
import com.junfunsoft.cloud.chudun.base.service.*;
import com.junfunsoft.cloud.chudun.base.utils.MiniAppsPayUtils;
import com.junfunsoft.devfx.baseapi.base.controller.BaseController;
import com.junfunsoft.devfx.common.result.ResultInfo;
import com.junfunsoft.devfx.common.utils.MapUtils;
import com.junfunsoft.devfx.common.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.text.DecimalFormat;
import java.util.*;
/**
* 类描述: 9.98 基础_微信小程序支付
*/
@Api(tags = {"9.98 基础_微信小程序支付"}, value="MiniAppsPayController")
@RestController
@RequestMapping(value="api/v1/mini_apps_pay")
public class MiniAppsPayController extends BaseController{
public static final String TIMEMILLIS = String.valueOf(System.currentTimeMillis() / 1000);
public static final String RANDOMSTRING = MiniAppsPayUtils.getRandomString(32);
public static final String WXNOTIFYJDHY = "api/v1/mini_apps_pay/success_jdhy";
public static final String WXNOTIFYSPDD = "api/v1/mini_apps_pay/success_spdd";
public static final String SSLPATHURL = "D:/junfunsoft_chudun_cert.p12";
@Autowired
private T_JC_ZHIFU_Service service_T_JC_ZHIFU;
@Autowired
private T_JC_DINGDAN_Service service_T_JC_DINGDAN;
@Autowired
private T_JC_TUIKUAN_Service service_T_JC_TUIKUAN;
@Autowired
private T_JC_LAOBAN_Service service_T_JC_LAOBAN;
@Autowired
private T_JC_CHUSHI_Service service_T_JC_CHUSHI;
@ApiOperation(value = "微信小程序支付接口(金盾会员)")
@RequestMapping(value = "/to_pay_jdhy", method = RequestMethod.POST)
public ResultInfo ToPayJdhy(HttpServletRequest request) {
Map<String, Object> map = this.getParamsToMap();
if (MapUtils.isNull(map, "openid")){
return new ResultInfo(ResultInfo.Code.失败, "openid不能为空");
}
BigDecimal totalAmount = new BigDecimal("0.01");//订单总金额
String description = "金盾会员开通费用";//订单描述
String sym = request.getRequestURL().toString().split("api")[0];
String trade_no = StrUtils.newGuid().toLowerCase();
Map<String, String> resultMap = MiniAppsPayUtils.uniformOrderGeneration(trade_no, totalAmount, description,
MapUtils.getString(map, "openid"), sym + WXNOTIFYJDHY, RANDOMSTRING, request);
SortedMap<String, Object> finalPackage = new TreeMap<>();
finalPackage.put("appId", MiniAppsPayUtils.APPID);
finalPackage.put("timeStamp", TIMEMILLIS);
finalPackage.put("nonceStr", RANDOMSTRING);
finalPackage.put("package", "prepay_id=" + resultMap.get("prepay_id"));
finalPackage.put("signType", "MD5");
String sign = MiniAppsPayUtils.createSign("UTF-8", finalPackage);
finalPackage.put("paySign", sign);
return new ResultInfo(finalPackage);
}
@ApiOperation(value = "微信小程序支付回调接口(金盾会员)")
@RequestMapping(value = "/success_jdhy", method = {RequestMethod.GET,RequestMethod.POST})
public String successJdhy(HttpServletRequest request) throws Exception {
System.out.println("微信支付回调");
InputStream inStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
String resultXml = new String(outSteam.toByteArray(), "utf-8");
Map<String, String> params = MiniAppsPayUtils.doXMLParse(resultXml);
outSteam.close();
inStream.close();
System.out.println(params);
if (!MiniAppsPayUtils.isTenpaySign(params)) {
// 支付失败
return "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";
} else {
System.out.println("===============付款成功==============");
// ------------------------------
// 处理业务开始
// ------------------------------
String returnCode = params.get("return_code");
String returnMsg = params.get("return_msg");
if ("SUCCESS".equals(returnCode)){
String appid = params.get("appid");
String mchId = params.get("mch_id");
String nonceStr = params.get("nonce_str");
String sign = params.get("sign");
String resultCode = params.get("result_code");
String openId = params.get("openid");
String isSubscribe = params.get("is_subscribe");
String tradeType = params.get("trade_type");
String bankType = params.get("bank_type");
String totalFee = params.get("total_fee");
int tf = Integer.parseInt(totalFee);
String feeType = params.get("fee_type");
String cashFee = params.get("cash_fee");
int cf = Integer.parseInt(cashFee);
String transactionId = params.get("transaction_id");
String outTradeNo = params.get("out_trade_no");
String attach = params.get("attach");
String timeEnd = params.get("time_end");
//保存支付订单信息
Map<String, Object> mmp = new HashMap<>();
mmp.put("YW_RECID", openId);
List<T_JC_ZHIFU> tJcZhifuList = service_T_JC_ZHIFU.queryList(mmp);
if (tJcZhifuList.size() == 0){
T_JC_ZHIFU tJcZhifu = new T_JC_ZHIFU();
tJcZhifu.setZF_RECID(StrUtils.newGuid());
tJcZhifu.setYW_RECID(openId);
tJcZhifu.setYWLX("金盾会员");
tJcZhifu.setOPENID(openId);
tJcZhifu.setAPPID(appid);
tJcZhifu.setATTACH(attach);
tJcZhifu.setBANK_TYPE(bankType);
tJcZhifu.setFEE_TYPE(feeType);
tJcZhifu.setIS_SUBSCRIBE(isSubscribe);
tJcZhifu.setMCH_ID(mchId);
tJcZhifu.setNONCE_STR(nonceStr);
tJcZhifu.setOUT_TRADE_NO(outTradeNo);
tJcZhifu.setRESULT_CODE(resultCode);
tJcZhifu.setRETURN_CODE(returnCode);
tJcZhifu.setSIGN(sign);
tJcZhifu.setTIME_END(timeEnd);
tJcZhifu.setTOTAL_FEE(tf);
tJcZhifu.setTRADE_TYPE(tradeType);
tJcZhifu.setTRANSACTION_ID(transactionId);
service_T_JC_ZHIFU.save(tJcZhifu);
}
//修改会员状态
Map<String, Object> lbMap = new HashMap<>();
lbMap.put("CS_RECID", openId);
List<T_JC_CHUSHI> tJcChushiList = service_T_JC_CHUSHI.queryList(lbMap);
if (tJcChushiList.size() == 0){
lbMap.put("HYJB", "金盾会员");
service_T_JC_CHUSHI.updateOne(lbMap);
}else {
lbMap.clear();
lbMap.put("LB_RECID", openId);
lbMap.put("HYJB", "金盾会员");
service_T_JC_LAOBAN.updateOne(lbMap);
}
return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
}else {
return "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";
}
// ------------------------------
// 处理业务完毕
// ------------------------------
}
}
@ApiOperation(value = "微信小程序申请退款接口(金盾会员)")
@RequestMapping(value = "/to_refund_jdhy", method = RequestMethod.POST)
public ResultInfo toRefundJdhy() {
Map<String, Object> hashMap = this.getParamsToMap();
if(MapUtils.isNull(hashMap, "YW_RECID")){
return new ResultInfo(ResultInfo.Code.失败, "YW_RECID不能为空");
}
//查询订单支付信息
List<T_JC_ZHIFU> tJcZhifuList = service_T_JC_ZHIFU.queryList(hashMap);
BigDecimal totalAmount = new BigDecimal(tJcZhifuList.get(0).getTOTAL_FEE());//订单总金额
String openId = tJcZhifuList.get(0).getOPENID();
String out_trade_no = tJcZhifuList.get(0).getOUT_TRADE_NO();
String out_refund_no = out_trade_no + "@7758";
String randomString = MiniAppsPayUtils.getRandomString(32);
SortedMap<String, Object> parameterMap = new TreeMap<>();
parameterMap.put("appid", MiniAppsPayUtils.APPID);
parameterMap.put("mch_id", MiniAppsPayUtils.MCH_ID);
parameterMap.put("nonce_str", randomString);
parameterMap.put("out_trade_no", out_trade_no);
parameterMap.put("out_refund_no", out_refund_no);
parameterMap.put("refund_fee_type", "CNY");
DecimalFormat df = new DecimalFormat("0");
parameterMap.put("total_fee", df.format(totalAmount));
parameterMap.put("refund_fee", df.format(totalAmount));
String sign = MiniAppsPayUtils.createSign("UTF-8", parameterMap);
parameterMap.put("sign", sign);
String requestXML = MiniAppsPayUtils.getRequestXml(parameterMap);
System.out.println(requestXML);
String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
Map<Object, Object> map = new HashMap<>();
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(SSLPATHURL));//加载本地的证书进行https加密传输
try {
keyStore.load(instream, MiniAppsPayUtils.MCH_ID.toCharArray());//设置证书密码
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MiniAppsPayUtils.MCH_ID.toCharArray())// 这里也是写密码的
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
StringEntity se = new StringEntity(requestXML);
httpPost.setEntity(se);
CloseableHttpResponse response2 = client.execute(httpPost);
HttpEntity entity2 = response2.getEntity();
String s2 = EntityUtils.toString(entity2, "UTF-8");
System.out.println(s2);
Map<String, Object> params = MiniAppsPayUtils.doXMLParse(s2);
//保存退款订单信息
T_JC_TUIKUAN tJcTuikuan = new T_JC_TUIKUAN();
tJcTuikuan.setTK_RECID(StrUtils.newGuid());
tJcTuikuan.setRETURN_CODE(MapUtils.getString(params, "return_code"));
tJcTuikuan.setRESULT_CODE(MapUtils.getString(params, "result_code"));
tJcTuikuan.setAPPID(MapUtils.getString(params, "appid"));
tJcTuikuan.setMCH_ID(MapUtils.getString(params, "mch_id"));
tJcTuikuan.setNONCE_STR(MapUtils.getString(params, "nonce_str"));
tJcTuikuan.setSIGN(MapUtils.getString(params, "sign"));
tJcTuikuan.setTRANSACTION_ID(MapUtils.getString(params, "transaction_id"));
tJcTuikuan.setOUT_TRADE_NO(MapUtils.getString(params, "out_trade_no"));
tJcTuikuan.setOUT_REFUND_NO(MapUtils.getString(params, "out_refund_no"));
tJcTuikuan.setREFUND_ID(MapUtils.getString(params, "refund_id"));
tJcTuikuan.setREFUND_FEE(Integer.parseInt(MapUtils.getString(params, "refund_fee")));
tJcTuikuan.setTOTAL_FEE(Integer.parseInt(MapUtils.getString(params, "total_fee")));
tJcTuikuan.setCASH_FEE(Integer.parseInt(MapUtils.getString(params, "cash_fee")));
service_T_JC_TUIKUAN.save(tJcTuikuan);
//修改会员级别
if ("SUCCESS".equals(MapUtils.getString(params, "result_code"))){
Map<String, Object> lbMap = new HashMap<>();
lbMap.put("CS_RECID", openId);
List<T_JC_CHUSHI> tJcChushiList = service_T_JC_CHUSHI.queryList(lbMap);
if (tJcChushiList.size() == 0){
lbMap.put("HYJB", "普通会员");
service_T_JC_CHUSHI.updateOne(lbMap);
}else {
lbMap.clear();
lbMap.put("LB_RECID", openId);
lbMap.put("HYJB", "普通会员");
service_T_JC_LAOBAN.updateOne(lbMap);
}
}
map.put("returnCode", MapUtils.getString(params, "return_code"));
map.put("resultCode", MapUtils.getString(params, "result_code"));
} catch (Exception e) {
e.printStackTrace();
}
return new ResultInfo(map);
}
}
MiniAppsPayUtils 工具类
package com.junfunsoft.cloud.chudun.base.utils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.*;
/**
* Created by lenovo on 2017/9/5.
*/
public class MiniAppsPayUtils {
public static final String API_KEY = "";//商户平台秘钥
public static final String APPID = "";//小程序appId
public static final String MCH_ID = "";//商户号
/**
* 微信小程序支付统一生成订单
* @param trade_no:订单号
* @param totalAmount:订单总金额
* @param description:订单描述
* @param openid:客户标识
* @param notifyUrl:通知地址
* @param request
* @return
*/
public static Map<String, String> uniformOrderGeneration(String trade_no, BigDecimal totalAmount, String description, String openid, String notifyUrl, String randomString, HttpServletRequest request) {
SortedMap<String, Object> parameterMap = new TreeMap<>();
parameterMap.put("appid", APPID);
parameterMap.put("mch_id", MCH_ID);
parameterMap.put("nonce_str", randomString);
parameterMap.put("body", description);
parameterMap.put("out_trade_no", trade_no);
parameterMap.put("fee_type", "CNY");
BigDecimal total = totalAmount.multiply(new BigDecimal(100));
DecimalFormat df = new DecimalFormat("0");
parameterMap.put("total_fee", df.format(total));
parameterMap.put("spbill_create_ip", request.getRemoteAddr());
parameterMap.put("notify_url", notifyUrl);
parameterMap.put("trade_type", "JSAPI");
//trade_type为JSAPI是 openid为必填项
parameterMap.put("openid", openid);
String sign = createSign("UTF-8", parameterMap);
parameterMap.put("sign", sign);
String requestXML = getRequestXml(parameterMap);
System.out.println(requestXML);
String result = httpsRequest(
"https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",
requestXML);
System.out.println(result);
Map<String, String> map = null;
try {
map = doXMLParse(result);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
/**
* 随机字符串生成
* @param length
* @return
*/
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();
}
/**
* 生成签名
* @param characterEncoding
* @param parameters
* @return
*/
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=" + API_KEY);
System.out.println(sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* 请求xml组装
* @param parameters
* @return
*/
public static String getRequestXml(SortedMap<String,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 key = (String)entry.getKey();
String value = (String)entry.getValue();
if ("attach".equalsIgnoreCase(key)||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) {
sb.append("<"+key+">"+"<![CDATA["+value+"]]></"+key+">");
}else {
sb.append("<"+key+">"+value+"</"+key+">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* xml解析
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
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 = getChildrenText(children);
}
m.put(k, v);
}
//关闭流
in.close();
return m;
}
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();
}
/**
* 请求方法
* @param requestUrl
* @param requestMethod
* @param outputStr
* @return
*/
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
System.out.println("连接超时:{}"+ ce);
} catch (Exception e) {
System.out.println("https请求异常:{}"+ e);
}
return null;
}
/**
* 验证回调签名
* @return
*/
public static boolean isTenpaySign(Map<String, String> map) {
String charset = "utf-8";
String signFromAPIResponse = map.get("sign");
if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
System.out.println("API返回的数据签名数据不存在,有可能被第三方篡改!!!");
return false;
}
System.out.println("服务器回包里面的签名是:" + signFromAPIResponse);
//过滤空 设置 TreeMap
SortedMap<String,String> packageParams = new TreeMap();
for (String parameter : map.keySet()) {
String parameterValue = map.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
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);
//将API返回的数据根据用签名算法进行计算新的签名,用来跟API返回的签名进行比较
//算出签名
String resultSign = "";
String tobesign = sb.toString();
if (null == charset || "".equals(charset)) {
resultSign = MD5Util.MD5Encode(tobesign, "utf-8").toUpperCase();
} else {
resultSign = MD5Util.MD5Encode(tobesign, charset).toUpperCase();
}
String tenpaySign = (packageParams.get("sign")).toUpperCase();
return tenpaySign.equals(resultSign);
}
}