服务端代码:
package com.wlsq.kso.web;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wlsq.kso.annotation.MethodAction;
import com.wlsq.kso.entity.ResultObject;
import com.wlsq.kso.service.AccountWalletService;
import com.wlsq.kso.util.HttpUtil;
import com.wlsq.kso.util.MyMd5Util;
import com.wlsq.kso.util.XmltoJsonUtil;
/**
* 微信支付接口Controller
*
* @author zzg
* @date 2017-02-18
*/
@Controller
@RequestMapping(value = "/WeiXinPay")
public class AccountWeiXinController {
private static final Logger LOG = LoggerFactory
.getLogger(AccountWeiXinController.class);
@Autowired
private AccountWalletService accountWalletService;
// 微信统一下单接口路径
private static final String UNIFORMORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
// 微信商户号:*****
private static final String MCHID = "********";
// 微信回调地址
private static final String NOTIFYURL = "*********";
// 微信交易类型
private static final String TRADETYPE = "APP";
//微信APIKEY
private static final String APIKEY ="************";
/**
* 微信统一下单
*
* @return
* @throws UnsupportedEncodingException
*/
@MethodAction(optionDescription = "微信统一下单", methodName = "/WeiXinPay/uniformorder")
@RequestMapping(value = "/uniformorder", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
@ResponseBody
public String uniformorder(HttpServletRequest request) throws UnsupportedEncodingException {
ResultObject result = new ResultObject();// 返回数据结果集合
request.setCharacterEncoding("UTF-8");
try {
//APP ID
String appid = request.getParameter("appid") == null ? null
: request.getParameter("appid").trim().toUpperCase();
// 用户访问令牌
String accessToken = request.getParameter("accessToken") == null ? null
: request.getParameter("accessToken").trim();
// 订单编号
String orderNum = request.getParameter("orderNum") == null ? null
: request.getParameter("orderNum").trim();// 订单编号
// 消费金额
String money = request.getParameter("money") == null ? null
: request.getParameter("money").trim();// 消费金额
// 消费主题
String subject = request.getParameter("subject") == null ? null
: request.getParameter("subject").trim();// 消费主体
if(StringUtils.isEmpty(appid)){
result.setMsg("参数:appid 为空");
result.setResultCode("-1");
return JSON.toJSONString(result);
}
if(StringUtils.isEmpty(accessToken)){
result.setMsg("参数:accessToken 为空");
result.setResultCode("-1");
return JSON.toJSONString(result);
}
if(StringUtils.isEmpty(orderNum)){
result.setMsg("参数:orderNum 为空");
result.setResultCode("-1");
return JSON.toJSONString(result);
}
if(StringUtils.isEmpty(money)){
result.setMsg("参数:money 为空");
result.setResultCode("-1");
return JSON.toJSONString(result);
}
if(StringUtils.isEmpty(subject)){
result.setMsg("参数:subject 为空");
result.setResultCode("-1");
return JSON.toJSONString(result);
}
SortedMap
HttpUtil 类
package com.wlsq.kso.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
public class HttpUtil
{
public static final String POST = "POST";
public static final String GET = "GET";
public static String post(String uriString, Map params)
throws Exception
{
URL url = new URL(uriString);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod(RequstMethod.POST.value());
con.setRequestProperty(" Content-Type ",
" application/x-www-form-urlencoded ");
con.setUseCaches(false);
con.setInstanceFollowRedirects(true);
if (params != null) {
StringBuffer sb = new StringBuffer();
String data = null;
byte[] b = null;
for (String key : params.keySet()) {
sb.append(key).append('=').append((String)params.get(key)).append('&');
}
data = sb.substring(0, sb.length() - 1);
b = data.getBytes("UTF-8");
OutputStream out = con.getOutputStream();
out.write(b);
out.flush();
out.close();
}
InputStream in = con.getInputStream();
String responseBody = FileUtil.readAll(in);
return responseBody;
}
public static String post(String uriString, Map params, String authorization)
throws Exception
{
URL url = new URL(uriString);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod(RequstMethod.POST.value());
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", authorization);
con.setUseCaches(false);
con.setInstanceFollowRedirects(true);
if (params != null) {
StringBuffer sb = new StringBuffer();
String data = null;
byte[] b = null;
for (String key : params.keySet()) {
sb.append(key).append('=').append((String)params.get(key)).append('&');
}
data = sb.substring(0, sb.length() - 1);
b = data.getBytes("UTF-8");
OutputStream out = con.getOutputStream();
out.write(b);
out.flush();
out.close();
}
InputStream in = con.getInputStream();
String responseBody = FileUtil.readAll(in);
return responseBody;
}
public static String jpost(String uriString, Map params)
throws Exception
{
URL url = new URL(uriString);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod(RequstMethod.POST.value());
con.setRequestProperty("Content-Type", "application/json");
con.setUseCaches(false);
con.setInstanceFollowRedirects(true);
if (params != null) {
StringBuffer sb = new StringBuffer();
String data = null;
byte[] b = null;
for (String key : params.keySet()) {
sb.append(key).append('=').append((String)params.get(key)).append('&');
}
data = sb.substring(0, sb.length() - 1);
b = data.getBytes("UTF-8");
OutputStream out = con.getOutputStream();
out.write(b);
out.flush();
out.close();
}
InputStream in = con.getInputStream();
String responseBody = FileUtil.readAll(in);
return responseBody;
}
public static String sendGet(String url, String param)
{
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
Map map = connection.getHeaderFields();
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null)
{
//String line;
result = result + line;
}
} catch (Exception e) {
System.out.println("����GET��������쳣��" + e);
e.printStackTrace();
try
{
if (in != null)
in.close();
}
catch (Exception e2) {
e2.printStackTrace();
}
}
finally
{
try
{
if (in != null)
in.close();
}
catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/xml");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
//String line;
result = result + line;
}
} catch (Exception e) {
System.out.println("���� POST ��������쳣��" + e);
e.printStackTrace();
try
{
if (out != null) {
out.close();
}
if (in != null)
in.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
finally
{
try
{
if (out != null) {
out.close();
}
if (in != null)
in.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
public static enum RequstMethod
{
GET("GET"), POST("POST");
private String value;
private RequstMethod(String value) {
this.value = value;
}
public String value() {
return this.value;
}
}
}
package com.wlsq.kso.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import com.alibaba.fastjson.JSONObject;
public class XmltoJsonUtil {
public static String xml2JSON(String xml) {
JSONObject obj = new JSONObject();
try {
InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
obj.put(root.getName(), iterateElement(root));
return obj.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static Map iterateElement(Element element) {
List jiedian = element.getChildren();
Element et = null;
Map obj = new HashMap();
List list = null;
for (int i = 0; i < jiedian.size(); i++) {
list = new LinkedList();
et = (Element) jiedian.get(i);
if (et.getTextTrim().equals("")) {
if (et.getChildren().size() == 0)
continue;
if (obj.containsKey(et.getName())) {
list = (List) obj.get(et.getName());
}
list.add(iterateElement(et));
obj.put(et.getName(), list);
} else {
if (obj.containsKey(et.getName())) {
list = (List) obj.get(et.getName());
}
list.add(et.getTextTrim());
obj.put(et.getName(), list);
}
}
return obj;
}
}
package com.wlsq.kso.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author fengcai ouyang
* @version V1.0
* @Description:
* @date 2016/7/23 18:48
* @Update by: ${todo}
*/
public class MyMd5Util {
private static MessageDigest sMd5MessageDigest;
private static StringBuilder sStringBuilder;
private MyMd5Util() {
}
public static String md5(String s) {
sMd5MessageDigest.reset();
sMd5MessageDigest.update(s.getBytes());
byte[] digest = sMd5MessageDigest.digest();
sStringBuilder.setLength(0);
for (int i = 0; i < digest.length; ++i) {
int b = digest[i] & 255;
if (b < 16) {
sStringBuilder.append('0');
}
sStringBuilder.append(Integer.toHexString(b));
}
return sStringBuilder.toString().toUpperCase();
}
static {
try {
sMd5MessageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException var1) {
}
sStringBuilder = new StringBuilder();
}
}