签名和解析xml
package com.sh.appweipay;
import org.apache.http.Consts;
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.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.util.*;
public class PayCommonUtil {
public static String API_KEY = "6MzErPV8E6DTxulQT4hk8REinlGsjQTG";
public static String getRandomString(int 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 getRequestXml(SortedMap<String,Object> parameters){
StringBuffer sb = new StringBuffer();
sb.append("");
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+">"+"+value+"]]>"+key+">");
}else {
sb.append("<"+key+">"+value+""+key+">");
}
}
sb.append("");
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=" + API_KEY);
System.out.println(sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
public static boolean isTenpaySign(Map<String, String> map) {
String characterEncoding="utf-8";
String charset = "utf-8";
String signFromAPIResponse = map.get("sign");
if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
System.out.println("API返回的数据签名数据不存在,有可能被第三方篡改!!!");
return false;
}
System.out.println("服务器回包里面的签名是:" + signFromAPIResponse);
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);
String resultSign = "";
String tobesign = sb.toString();
if (null == charset || "".equals(charset)) {
resultSign = MD5Util.MD5Encode(tobesign, characterEncoding).toUpperCase();
}else{
try{
resultSign = MD5Util.MD5Encode(tobesign, characterEncoding).toUpperCase();
}catch (Exception e) {
resultSign = MD5Util.MD5Encode(tobesign, characterEncoding).toUpperCase();
}
}
String tenpaySign = ((String)packageParams.get("sign")).toUpperCase();
return tenpaySign.equals(resultSign);
}
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);
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
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;
}
public static String httpsRequest2(String requestUrl, String requestMethod, String outputStr) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
StringBuilder res = new StringBuilder("");
FileInputStream instream = new FileInputStream(new File("/home/apiclient_cert.p12"));
try {
keyStore.load(instream, "".toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "1313329201".toCharArray())
.build();
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("https://api.mch.weixin.qq.com/secapi/pay/refund");
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) ");
StringEntity entity2 = new StringEntity(outputStr , Consts.UTF_8);
httpost.setEntity(entity2);
System.out.println("executing request" + httpost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
String text = "";
res.append(text);
while ((text = bufferedReader.readLine()) != null) {
res.append(text);
System.out.println(text);
}
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
return res.toString();
}
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();
}
public static String getRemoteHost(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
}
}
MD5
package com.sh.appweipay;
import java.security.MessageDigest;
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();
}
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" };
}
时间类
package com.sh.appweipay;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;
public class DateUtil {
public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";
public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";
public static final String FORMAT_FOUR = "yyyyMMdd";
public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";
public static final String SHORT_DATE_FORMAT = "MM-dd";
public static final String LONG_TIME_FORMAT = "HH:mm:ss";
public static final String MONTG_DATE_FORMAT = "yyyy-MM";
public static final int SUB_YEAR = Calendar.YEAR;
public static final int SUB_MONTH = Calendar.MONTH;
public static final int SUB_DAY = Calendar.DATE;
public static final int SUB_HOUR = Calendar.HOUR;
public static final int SUB_MINUTE = Calendar.MINUTE;
public static final int SUB_SECOND = Calendar.SECOND;
static final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四",
"星期五", "星期六" };
public DateUtil() {
}
public static Date stringtoDate(String dateStr, String format) {
Date d = null;
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
formater.setLenient(false);
d = formater.parse(dateStr);
} catch (Exception e) {
d = null;
}
return d;
}
public static Date stringtoDate(String dateStr, String format,
ParsePosition pos) {
Date d = null;
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
formater.setLenient(false);
d = formater.parse(dateStr, pos);
} catch (Exception e) {
d = null;
}
return d;
}
public static String dateToString(Date date, String format) {
String result = "";
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
result = formater.format(date);
} catch (Exception e) {
}
return result;
}
public static String getCurrDate(String format) {
return dateToString(new Date(), format);
}
public static String dateSub(int dateKind, String dateStr, int amount) {
Date date = stringtoDate(dateStr, MONTG_DATE_FORMAT);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(dateKind, amount);
return dateToString(calendar.getTime(), FORMAT_ONE);
}
public static String yearthDate(String dateStr){
Date date = stringtoDate(dateStr, LONG_DATE_FORMAT);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.DATE,-1);
return dateToString(calendar.getTime(), LONG_DATE_FORMAT);
}
public static long timeSub(String firstTime, String secTime) {
long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
long second = stringtoDate(secTime, FORMAT_ONE).getTime();
return (second - first) / 1000;
}
public static boolean timeSub(Date firstTime, Date secTime,long secs) {
long first = firstTime.getTime();
long second = secTime.getTime();
return (second - first - secs) > 0 ? false:true;
}
public static boolean timeSub(Date firstTime, Date secTime) {
long first = firstTime.getTime();
long second = secTime.getTime();
return (second - first)>0?false:true;
}
public static int getDaysOfMonth(String year, String month) {
int days = 0;
if (month.equals("1") || month.equals("3") || month.equals("5")
|| month.equals("7") || month.equals("8") || month.equals("10")
|| month.equals("12")) {
days = 31;
} else if (month.equals("4") || month.equals("6") || month.equals("9")
|| month.equals("11")) {
days = 30;
} else {
if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
|| Integer.parseInt(year) % 400 == 0) {
days = 29;
} else {
days = 28;
}
}
return days;
}
public static int getDaysOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
public static int getToday() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DATE);
}
public static int getToMonth() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
}
public static int getToYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
}
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
public static long dayDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 86400000;
}
public static int yearDiff(String before, String after) {
Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(afterDay) - getYear(beforeDay);
}
public static int yearDiffCurr(String after) {
Date beforeDay = new Date();
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(beforeDay) - getYear(afterDay);
}
public static int getFirstWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY);
c.set(year, month - 1, 1);
return c.get(Calendar.DAY_OF_WEEK);
}
public static int getLastWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY);
c.set(year, month - 1, getDaysOfMonth(year, month));
return c.get(Calendar.DAY_OF_WEEK);
}
public static String getNow() {
Calendar today = Calendar.getInstance();
return dateToString(today.getTime(), FORMAT_ONE);
}
public static boolean isDate(String date) {
StringBuffer reg = new StringBuffer(
"^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
Pattern p = Pattern.compile(reg.toString());
return p.matcher(date).matches();
}
public static Date adjustDateByHour(Date d ,Integer num, int type) {
Calendar Cal= Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Cal.setTime(d);
if(type==0){
Cal.add(Calendar.MINUTE,-num);
}else
{
Cal.add(Calendar.MINUTE,num);
}
return Cal.getTime();
}
public static Date adjustDateByMinutes(Date d ,Integer num, int type) {
Calendar Cal= Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Cal.setTime(d);
if(type==0){
Cal.add(Calendar.MINUTE,-num);
}else
{
Cal.add(Calendar.MINUTE,num);
}
return Cal.getTime();
}
public static void main(String[] args){
String settlementDate = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
long day = DateUtil.dayDiff(DateUtil.stringtoDate("2017-06-22", "yyyy-MM-dd"),DateUtil.stringtoDate(settlementDate, "yyyy-MM-dd"));
if(day >= 0){
System.out.println(day);
}
String goodsArriveTime = "2017-04-02 17:00-18:00";
int space_index = goodsArriveTime.indexOf(" ");
String arrive_date = goodsArriveTime.substring(0, space_index);
String arrive_time = goodsArriveTime.substring(space_index+1, goodsArriveTime.length());
System.out.println(arrive_date);
System.out.println(arrive_time);
String arrive_start_time = arrive_time.substring(0, 2);
String arrive_end_time = arrive_time.substring(6,8);
System.out.println(arrive_start_time);
System.out.println(arrive_end_time);
String Time = DateUtil.getCurrDate("HH");
System.out.println(Time);
String Time2 = DateUtil.getCurrDate("mm");
System.out.println(Time2);
}
}
字符串工具
package com.sh.appweipay;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
public static String supplementZeroGenerateThirteen(int num){
String str = String.format("%013d", num);
return str;
}
public static String supplementZeroGenerateSixteen(int num){
String str = String.format("%016d", num);
return str;
}
public static String supplementZeroGenerateThree(int num){
String str = String.format("%03d", num);
return str;
}
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
public static String trim(String str, boolean nullFlag){
String tempStr = null;
if (str != null)
{
tempStr = str.trim();
}
if (nullFlag)
{
if ("".equals(tempStr) || "null".equals(tempStr))
{
tempStr = null;
}
}
else
{
if (tempStr == null)
{
tempStr = "";
}
}
return tempStr;
}
public static String replace(String strSource, String strFrom, String strTo) {
if(strSource==null){
return null;
}
int i = 0;
if ((i = strSource.indexOf(strFrom, i)) >= 0) {
char[] cSrc = strSource.toCharArray();
char[] cTo = strTo.toCharArray();
int len = strFrom.length();
StringBuffer buf = new StringBuffer(cSrc.length);
buf.append(cSrc, 0, i).append(cTo);
i += len;
int j = i;
while ((i = strSource.indexOf(strFrom, i)) > 0) {
buf.append(cSrc, j, i - j).append(cTo);
i += len;
j = i;
}
buf.append(cSrc, j, cSrc.length - j);
return buf.toString();
}
return strSource;
}
public static String deal(String str) {
str = replace(str, "\\", "\\\\");
str = replace(str, "'", "\\'");
str = replace(str, "\r", "\\r");
str = replace(str, "\n", "\\n");
str = replace(str, "\"", "\\\"");
return str;
}
public static String GetMapToXML(Map<String,String> param){
StringBuffer sb = new StringBuffer();
sb.append("");
for (Map.Entry<String,String> entry : param.entrySet()) {
sb.append("<"+ entry.getKey() +">");
sb.append(entry.getValue());
sb.append(""+ entry.getKey() +">");
}
sb.append("");
return sb.toString();
}
public static void main(String[] args){
double a = 32.;
System.out.println(StringUtil.isNumeric("32."));
System.out.println(a);
}
}
业务层
package com.sh.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.JDOMException;
import org.junit.runner.Result;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sh.appweipay.ConfigManager;
import com.sh.appweipay.DateUtil;
import com.sh.appweipay.PayCommonUtil;
import com.sh.appweipay.StringUtil;
import com.sh.util.CommonUtil;
@Controller
@RequestMapping("/pay")
public class PayController extends CommonAppController{
public static void main(String[] args) {
String randomString = PayCommonUtil.getRandomString(32);
System.out.println(randomString);
}
String randomString = PayCommonUtil.getRandomString(32);
public static String wxnotify = "http://192.168.43.184:8089/o2o/pay/notifyWeiXinPay";
@RequestMapping(value = "/wxpay", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> wxpay(HttpServletRequest request) {
Map<String, Object> maps = new HashMap<>();
Long userId = new Long(1);
BigDecimal totalAmount = new BigDecimal(request.getParameter("totalPrice"));
String trade_no = "";
String description="";
try {
trade_no = new String(request.getParameter("orderNum").getBytes("ISO-8859-1"),"UTF-8");
description = request.getParameter("description");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<String, String> map = weixinPrePay(trade_no,totalAmount,description,request);
SortedMap<String, Object> finalpackage = new TreeMap<String, Object>();
finalpackage.put("appid", "wxd2573b9d483286a5");
finalpackage.put("partnerid", "1567460921");
finalpackage.put("prepayid", map.get("prepay_id"));
finalpackage.put("package", "Sign=WXPay");
finalpackage.put("noncestr", PayCommonUtil.getRandomString(32));
Long time = (System.currentTimeMillis() / 1000);
finalpackage.put("timestamp", time.toString());
String signAgain = PayCommonUtil.createSign("UTF-8", finalpackage);
finalpackage.put("sign", signAgain);
return finalpackage;
}
@SuppressWarnings("unchecked")
public Map<String, String> weixinPrePay(String trade_no,BigDecimal totalAmount,
String description, HttpServletRequest request) {
SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
parameterMap.put("appid", "wxd123456286a5");
parameterMap.put("body", description);
parameterMap.put("fee_type", "CNY");
parameterMap.put("mch_id","123456");
parameterMap.put("notify_url", wxnotify);
parameterMap.put("nonce_str", PayCommonUtil.getRandomString(32));
parameterMap.put("out_trade_no", trade_no);
parameterMap.put("spbill_create_ip", PayCommonUtil.getRemoteHost(request));
parameterMap.put("trade_type", "APP");
System.out.println("jiner");
BigDecimal total = totalAmount.multiply(new BigDecimal(10));
java.text.DecimalFormat df=new java.text.DecimalFormat("0");
parameterMap.put("total_fee", df.format(total));
System.out.println("jiner2");
System.out.println("");
String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
System.out.println("jiner2");
parameterMap.put("sign", sign);
String requestXML = PayCommonUtil.getRequestXml(parameterMap);
System.out.println(requestXML);
String result = PayCommonUtil.httpsRequest(
"https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",
requestXML);
System.out.println(result);
Map<String, String> map = null;
try {
map = PayCommonUtil.doXMLParse(result);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
@RequestMapping(value = "notifyWeiXinPay", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
System.out.println("微信支付回调");
InputStream inStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
String resultxml = new String(outSteam.toByteArray(), "utf-8");
Map<String, String> params = PayCommonUtil.doXMLParse(resultxml);
outSteam.close();
inStream.close();
Map<String,String> return_data = new HashMap<String,String>();
if (!PayCommonUtil.isTenpaySign(params)) {
return_data.put("return_code", "FAIL");
return_data.put("return_msg", "return_code不正确");
return StringUtil.GetMapToXML(return_data);
} else {
System.out.println("===============付款成功==============");
String total_fee = params.get("total_fee");
double v = Double.valueOf(total_fee) / 100;
String out_trade_no = String.valueOf(Long.parseLong(params.get("out_trade_no").split("O")[0]));
Date accountTime = DateUtil.stringtoDate(params.get("time_end"), "yyyyMMddHHmmss");
String ordertime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
String totalAmount = String.valueOf(v);
String appId = params.get("appid");
String tradeNo = params.get("transaction_id");
return_data.put("return_code", "SUCCESS");
return_data.put("return_msg", "OK");
return StringUtil.GetMapToXML(return_data);
}
}
}
微信支付所需 pom
<!--如果各位pom不齐全可去下面pom寻找-->
<!--微信 -->
<dependency>
<groupId>com.github.liyiorg</groupId>
<artifactId>weixin-popular</artifactId>
<version>2.8.5</version>
</dependency>
<!--httpclient-->
<!-- <dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency> -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
我全部pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qg360</groupId>
<artifactId>o2o</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- spring版本号 -->
<spring.version>4.3.11.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.4.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.21</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<!--微信 -->
<dependency>
<groupId>com.github.liyiorg</groupId>
<artifactId>weixin-popular</artifactId>
<version>2.8.5</version>
</dependency>
<!--httpclient-->
<!-- <dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency> -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
<!-- <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId>
<version>4.0.2</version> </dependency> -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!-- 根据ip获取位置 -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.1</version>
</dependency>
<!--距离 筛选-->
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.5</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!--maven jar -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
</dependency>
<!--视频点播jar包 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.6</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
<version>2.7.0</version>
</dependency>
<!-- SDK 上传 -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[6.1.7, 6.999]</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<!-- <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId>
<version>4.11</version> 表示开发的时候引入,发布的时候不会加载此包 <scope>test</scope> </dependency> -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper
分页 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<!-- 通用 Mapper -->
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- java servlet的规范包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 映入JSON -->
<!-- <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version> </dependency> -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.4</version>
<exclusions>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
<exclusion>
<artifactId>jackson-core</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.4</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.55</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
<testResources>
<testResource>
<directory>src/main/webapp</directory>
</testResource>
</testResources>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.2</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
注意: 一定要再按签名规范重新生成签名后,将数据传输给APP。参与签名的字段名为appid,partnerid,prepayid,noncestr,timestamp,package。注意:package的值格式为Sign=WXPay