WeixinOrderController
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.controller.Helper.HttpClientHelper;
import com.data.WebConfig;
import com.message.Response;
import com.message.WeixinOrderRequest;
import com.pojo.Order;
import com.pojo.OrderNATIVE;
import com.redis.utils.RedisUtil;
import com.utils.GetRequest;
import com.utils.HttpClientUtils;
import com.utils.HttpUtil;
import com.utils.PayCommonUtil;
import com.utils.WeixinConfigUtil;
import com.utils.XMLUtil;
import com.google.common.collect.ImmutableMap;
import Message.Inner.RechargeSyncRequest;
import Message.Inner.RechargeSyncResponse;
@Controller
@RequestMapping(value = "/weixin")
public class WeixinOrderController {
//公众号支付 trade_type:JSAPI
@ResponseBody
@RequestMapping(value = "/pay", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
public String JSpay(WeixinOrderRequest request, HttpServletRequest httpRequest) {
if (request.getUid() != 0 && request.getItemId() != null) {
try {
int diamond = 0;// 钻石
int money = 0 ;//充值金额(注:充值表中金额单位为元,double类型。请求微信金额的单位为分)
String querywolfurl = WeixinConfigUtil.diamond_url;//公众号充值钻石表
String string = HttpClientUtils.executePost(querywolfurl, null, "utf-8");//公众号充值钻石表
JSONArray jsona = JSONArray.parseArray(string);
if (jsona.size() > 0) {
for (int i = 0; i < jsona.size(); i++) {
JSONObject job = jsona.getJSONObject(i);
if ((job.getString("recharge_price_id")).equals(request.getItemId())) {
diamond = Integer.parseInt(job.getString("jewel_amount"));// 钻石
money = Integer.parseInt(job.getString("amount").substring(0, job.getString("amount").indexOf("."))+"00");
break;
}
}
}
if(money == 0){
//支付的商品id不存在,返回异常信息
return JSON.toJSONString("error");
}
String openid = "";
if (request.getCode() != null) {
//此处的GetRequest.sendGet()为自定义的get请求
String wechatResponse2 = GetRequest.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token",
"appid=" + WeixinConfigUtil.APPID + "&secret=" + WeixinConfigUtil.SECRET + "&code="
+ request.getCode() + "&grant_type=authorization_code");
JSONObject responseObject2 = JSONObject.parseObject(wechatResponse2);
openid = responseObject2.getString("openid");
}
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
String orderId = request.getUid() + "_" + timestamp;
String nonce_str = PayCommonUtil.CreateNoncestr();
String ip = httpRequest.getRemoteAddr();
Map<String, Object> oparams = null;
if (openid != "") {
oparams = ImmutableMap.<String, Object> builder().put("appid", WeixinConfigUtil.APPID)// 应用号
.put("body", diamond + "颗钻石")// 商品描述
.put("mch_id", WeixinConfigUtil.MCH_ID)// 商户号
.put("nonce_str", nonce_str)// 16随机字符串(大小写字母加数字)
.put("out_trade_no", orderId)// 商户订单号
.put("total_fee", money)// 总金额
.put("spbill_create_ip", ip)// 用户端实际IP地址
.put("notify_url", WeixinConfigUtil.NOTIFY_URL) // 微信回调地址
.put("trade_type", "JSAPI")// 支付类型
.put("openid", openid).build();
}
// key ASCII 排序
SortedMap<String, Object> sortMap = PayCommonUtil.sortMap(oparams);
// MD5签名
String createSign = PayCommonUtil.createSign("UTF-8", sortMap);
// sign签名
sortMap.put("sign", createSign);
String requestXML = PayCommonUtil.getRequestXml(sortMap);
String responseStr = HttpUtil.sendGet(WeixinConfigUtil.PLACE_ORDER_URL, "POST", requestXML);
SortedMap<String, Object> responseMap = XMLUtil.doXMLParse(responseStr);
String resultCode = (String) responseMap.get("result_code");
if (null == resultCode || !resultCode.equals("SUCCESS")) {
//支付的商品id不存在,返回异常信息
return JSON.toJSONString("error");
} else {//二次签名
String noncestr2 = PayCommonUtil.CreateNoncestr();
Map<String, Object> oparams2 = ImmutableMap.<String, Object> builder().put("appId", WeixinConfigUtil.APPID)// 应用号
.put("nonceStr", noncestr2)// 16随机字符串(大小写字母加数字)
.put("package", "prepay_id=" + (String) responseMap.get("prepay_id"))
.put("signType", "MD5")
.put("timeStamp", timestamp).build();// 时间戳 十位
// MD5签名
createSign = PayCommonUtil.createSign("UTF-8", oparams2);
Map<String, String> map = new HashMap<String, String>();
map.put("appId", WeixinConfigUtil.APPID);
map.put("timeStamp", timestamp);
map.put("nonceStr", noncestr2);
map.put("package", "prepay_id=" + (String) responseMap.get("prepay_id"));
map.put("signType", "MD5");
map.put("paySign", createSign);
RedisUtil.setValueTime(orderId, "1", 2 * 24 * 60 * 60);// 未支付
return JSON.toJSONString(map);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
//APP支付
@ResponseBody
@RequestMapping(value = "/APPpay", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
public String APPpay(WeixinOrderRequest request, HttpServletRequest httpRequest) {
if (request.getUid() != 0 && request.getItemId() != null) {
try {
JSONArray json = JSONArray.parseArray(RedisUtil.getByKey("RechargeMeter"));
int diamond = 0;// 钻石
int money = 0 ;//充值金额
if (json.size() > 0) {
for (int i = 0; i < json.size(); i++) {
JSONObject job = json.getJSONObject(i);
if ((job.getString("itemId")).equals(request.getItemId())){
diamond = Integer.parseInt((String) job.get("ADiamonds"));
money = Integer.parseInt((String) job.get("money")+"00");
break;
}
}
}
if(money == 0){
//支付的商品id不存在,返回异常信息
return JSON.toJSONString("error");
}
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
String orderId = request.getUid() + "_" + timestamp;
String nonce_str = PayCommonUtil.CreateNoncestr();
String ip = httpRequest.getRemoteAddr();
Map<String, Object> oparams = ImmutableMap.<String, Object> builder().put("appid", WeixinConfigUtil.APPAPPID)// 应用号
.put("body", diamond + "颗钻石")// 商品描述
.put("mch_id", WeixinConfigUtil.APPMCH_ID)// 商户号
.put("nonce_str", nonce_str)// 16随机字符串(大小写字母加数字)
.put("out_trade_no", orderId)// 商户订单号
.put("total_fee", money)// 总金额
.put("spbill_create_ip", ip)// 用户端实际IP地址
.put("notify_url", WeixinConfigUtil.APPNOTIFY_URL) // 微信回调地址
.put("trade_type", "APP")// 支付类型
.build();
// key ASCII 排序
SortedMap<String, Object> sortMap = PayCommonUtil.sortMap(oparams);
// MD5签名
String createSign = PayCommonUtil.createAPPSign("UTF-8", sortMap);
// sign签名
sortMap.put("sign", createSign);
String requestXML = PayCommonUtil.getRequestXml(sortMap);
String responseStr = HttpUtil.sendGet(WeixinConfigUtil.PLACE_ORDER_URL, "POST", requestXML);
SortedMap<String, Object> responseMap = XMLUtil.doXMLParse(responseStr);
String resultCode = (String) responseMap.get("result_code");
if (null == resultCode || !resultCode.equals("SUCCESS")) {
//创建订单失败,返回异常信息
return JSON.toJSONString("error");
} else {//二次签名
String noncestr2 = PayCommonUtil.CreateNoncestr();
String timestamp2 = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
Map<String, Object> oparams2 = ImmutableMap.<String, Object> builder().put("appid", WeixinConfigUtil.APPAPPID)// 应用号
.put("noncestr", noncestr2)// 16随机字符串(大小写字母加数字)
.put("package", "Sign=WXPay") // 固定值
.put("partnerid", WeixinConfigUtil.APPMCH_ID)// 商户号
.put("prepayid", (String) responseMap.get("prepay_id"))// 第一次请求微信,成功后,返回的参数
.put("timestamp", timestamp2)// 时间戳 十位
.build();
// MD5签名
createSign = PayCommonUtil.createAPPSign("UTF-8", oparams2);
Order order = new Order();
order.setOrderId(orderId);
order.setAppId(WeixinConfigUtil.APPAPPID);
order.setNonceStr(noncestr2);
order.setPrepayId((String) responseMap.get("prepay_id"));
order.setSign(createSign);
order.setTimeStamp(Long.parseLong(timestamp2));
order.setMchId(WeixinConfigUtil.APPMCH_ID);
RedisUtil.setValueTime(orderId, "1", 2 * 24 * 60 * 60);// 未支付,订单保存2天
return JSON.toJSONString(order);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
// 网站扫码支付
@ResponseBody
@RequestMapping(value = "/pagePay", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
public String pagePay(WeixinOrderRequest request, HttpServletRequest httpRequest) {
if (request.getUid() != 0 && request.getItemId() != null) {
try {
int diamond = 0;// 钻石
int money = 0 ;//充值金额(注:充值表中金额单位为元,double类型。请求微信金额的单位为分)
String querywolfurl = WeixinConfigUtil.diamond_url;//公众号充值钻石表
String string = HttpClientUtils.executePost(querywolfurl, null, "utf-8");//公众号充值钻石表
JSONArray jsona = JSONArray.parseArray(string);
try{
if (jsona.size() > 0) {
for (int i = 0; i < jsona.size(); i++) {
JSONObject job = jsona.getJSONObject(i);
if ((job.getString("recharge_price_id")).equals(request.getItemId())) {
diamond = Integer.parseInt(job.getString("jewel_amount"));// 钻石
money = Integer.parseInt(job.getString("amount").substring(0, job.getString("amount").indexOf("."))+"00");
break;
}
}
}
} catch (Exception e) {
money = 1;//测试
}
if(money == 0){
//支付的商品id不存在,返回异常信息
return JSON.toJSONString("error");
}
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
String orderId = request.getUid() + "_" + timestamp;
String nonce_str = PayCommonUtil.CreateNoncestr();
String ip = httpRequest.getRemoteAddr();
Map<String, Object> oparams = ImmutableMap.<String, Object> builder()
.put("appid", WeixinConfigUtil.APPID)// 应用号
.put("body", diamond + "颗钻石")// 商品描述
.put("mch_id", WeixinConfigUtil.MCH_ID)// 商户号
.put("nonce_str", nonce_str)// 16随机字符串(大小写字母加数字)
.put("out_trade_no", orderId)// 商户订单号
.put("total_fee", money)// 总金额
.put("spbill_create_ip", ip)// 用户端实际IP地址
.put("notify_url", WeixinConfigUtil.OWNOTIFY_URL) // 微信回调地址
.put("trade_type", "NATIVE")// 支付类型
.build();
// key ASCII 排序
SortedMap<String, Object> sortMap = PayCommonUtil.sortMap(oparams);
// MD5签名
String createSign = PayCommonUtil.createSign("UTF-8", sortMap);
// sign签名
sortMap.put("sign", createSign);
String requestXML = PayCommonUtil.getRequestXml(sortMap);
String responseStr = HttpUtil.sendGet(WeixinConfigUtil.PLACE_ORDER_URL, "POST", requestXML);
SortedMap<String, Object> responseMap = XMLUtil.doXMLParse(responseStr);
String resultCode = (String) responseMap.get("result_code");
if (null == resultCode || !resultCode.equals("SUCCESS")) {
//创建订单失败,返回异常信息
return JSON.toJSONString("error");
} else {
OrderNATIVE order = new OrderNATIVE();
order.setCode_url((String) responseMap.get("code_url"));// 二维码链接
order.setOrderId(orderId);
order.setAppId((String) responseMap.get("appid"));
order.setNonceStr((String) responseMap.get("nonce_str"));
order.setPrepayId((String) responseMap.get("prepay_id"));
order.setSign(createSign);
order.setTimeStamp(Long.parseLong(timestamp));
order.setMchId(WeixinConfigUtil.MCH_ID);
RedisUtil.setValueTime(orderId, "1", 2 * 24 * 60 * 60);// 未支付
return JSON.toJSONString(order);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
//公众号支付回调
@RequestMapping(value = "/notify")
public void notify(HttpServletRequest request, HttpServletResponse httpResponse) {
BufferedReader br = null;
String line = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
SortedMap<String, Object> responseMap = XMLUtil.doXMLParse(sb.toString());
System.out.println((String) responseMap.get("result_code"));
if (PayCommonUtil.checkIsSignValidFromResponseString(sb.toString())
&&("SUCCESS").equals((String) responseMap.get("result_code"))) {
String out_trade_no = (String) responseMap.get("out_trade_no");// 商户系统内部订单号
String total_fee = (String) responseMap.get("total_fee");// 订单总金额,单位为分
System.out.println("out_trade_no" + out_trade_no);
System.out.println("total_fee" + total_fee);
boolean contains = RedisUtil.getAllkeys().contains(out_trade_no);
if((contains && !RedisUtil.getByKey(out_trade_no).equals("3")) || !contains){
RedisUtil.setValue(out_trade_no, "2");// 支付成功,未加钻石
//获取订单信息,传到业务层,修改数据库
String uid = out_trade_no.substring(0, out_trade_no.indexOf("_"));
int diamond = 0;// 钻石
String querywolfurl = WeixinConfigUtil.diamond_url;//公众号充值钻石表
String string = HttpClientUtils.executePost(querywolfurl, null, "utf-8");//公众号充值钻石表
JSONArray jsona = JSONArray.parseArray(string);
if (jsona.size() > 0) {
for (int i = 0; i < jsona.size(); i++) {
JSONObject job = jsona.getJSONObject(i);
if ((job.getString("amount").substring(0, job.getString("amount").indexOf(".")) + "00").equals(total_fee)) {
diamond = Integer.parseInt(job.getString("jewel_amount"));// 钻石
break;
}
}
}
System.out.println("diamond : "+ diamond);
//........
if(修改数据库失败){
System.out.println("增加钻石失败--网络异常");
}else{
RedisUtil.setValue(out_trade_no, "3");// 增加钻石成功
System.out.println("增加钻石成功");
httpResponse.getWriter().println("SUCCESS");
}
}
}else{
httpResponse.getWriter().println("FAIL");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//APP支付回调
@RequestMapping(value = "/appNotify")
public void appNotify(HttpServletRequest request, HttpServletResponse httpResponse) {
BufferedReader br = null;
String line = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
SortedMap<String, Object> responseMap = XMLUtil.doXMLParse(sb.toString());
System.out.println((String) responseMap.get("result_code"));
if (PayCommonUtil.checkIsAPPSignValidFromResponseString(sb.toString())
&&("SUCCESS").equals((String) responseMap.get("result_code"))) {
String out_trade_no = (String) responseMap.get("out_trade_no");// 商户系统内部订单号
String total_fee = (String) responseMap.get("total_fee");// 订单总金额,单位为分
System.out.println("out_trade_no" + out_trade_no);
System.out.println("total_fee" + total_fee);
boolean contains = RedisUtil.getAllkeys().contains(out_trade_no);
if((contains && !RedisUtil.getByKey(out_trade_no).equals("3")) || !contains){
RedisUtil.setValue(out_trade_no, "2");// 支付成功,未加钻石
//获取订单信息,传到业务层,修改数据库
String uid = out_trade_no.substring(0, out_trade_no.indexOf("_"));
JSONArray json = JSONArray.parseArray(RedisUtil.getByKey("RechargeMeter"));
int diamond = 0;
if (json.size() > 0) {
for (int i = 0; i < json.size(); i++) {
JSONObject job = json.getJSONObject(i);
if (job.getString("money").equals(((Double.parseDouble(total_fee))/100)+"")){
diamond = Integer.parseInt((String) job.get("ADiamonds"));
break;
}
}
}
System.out.println("diamond : "+ diamond);
//........
if(修改数据库失败){
System.out.println("增加钻石失败--网络异常");
}else{
RedisUtil.setValue(out_trade_no, "3");// 增加钻石成功
System.out.println("增加钻石成功");
httpResponse.getWriter().println("SUCCESS");
}
}
}else{
httpResponse.getWriter().println("FAIL");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//网站扫码支付回调
@RequestMapping(value = "/OWnotify")
public void OWnotify(HttpServletRequest request, HttpServletResponse httpResponse) {
BufferedReader br = null;
String line = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
SortedMap<String, Object> responseMap = XMLUtil.doXMLParse(sb.toString());
System.out.println((String) responseMap.get("result_code"));
if (PayCommonUtil.checkIsSignValidFromResponseString(sb.toString())
&&("SUCCESS").equals((String) responseMap.get("result_code"))) {
String out_trade_no = (String) responseMap.get("out_trade_no");// 商户系统内部订单号
String total_fee = (String) responseMap.get("total_fee");// 订单总金额,单位为分
System.out.println("out_trade_no" + out_trade_no);
System.out.println("total_fee" + total_fee);
boolean contains = RedisUtil.getAllkeys().contains(out_trade_no);
if((contains && !RedisUtil.getByKey(out_trade_no).equals("3")) || !contains){
RedisUtil.setValue(out_trade_no, "2");// 支付成功,未加钻石
//获取订单信息,传到业务层,修改数据库
String uid = out_trade_no.substring(0, out_trade_no.indexOf("_"));
int diamond = 0;// 钻石
String querywolfurl = WeixinConfigUtil.diamond_url;//公众号充值钻石表
String string = HttpClientUtils.executePost(querywolfurl, null, "utf-8");
JSONArray jsona = JSONArray.parseArray(string);
if (jsona.size() > 0) {
for (int i = 0; i < jsona.size(); i++) {
JSONObject job = jsona.getJSONObject(i);
if ((job.getString("amount").substring(0, job.getString("amount").indexOf(".")) + "00").equals(total_fee)) {
diamond = Integer.parseInt(job.getString("jewel_amount"));// 钻石
break;
}
}
}
System.out.println("diamond : "+ diamond);
//........
if(修改数据库失败){
System.out.println("增加钻石失败--网络异常");
}else{
RedisUtil.setValue(out_trade_no, "3");// 增加钻石成功
System.out.println("增加钻石成功");
httpResponse.getWriter().println("SUCCESS");
}
}
}else{
httpResponse.getWriter().println("FAIL");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
WeixinConfigUtil
public class WeixinConfigUtil {
public final static String APPAPPID = "";//开放平台审核通过的应用APPID
public final static String APPID = "";//商户平台审核通过的公众号APPID
public final static String APPMCH_ID = ""; //开放平台支付分配的商户号
public final static String MCH_ID = ""; //商户平台微信支付商户号
public final static String SECRET = "";//商户平台 secret
public final static String APPAPI_KEY = "";// 和商户平台绑定的APP的 API密钥
public final static String API_KEY = "";//商户平台 API密钥
public final static String CHECK_ORDER_URL = "";//订单查询接口
public final static String PLACE_ORDER_URL = "";//统一下单,生成预支付交易单
public final static String NOTIFY_URL = "http://....../weixin/notify";//网站支付
public final static String APPNOTIFY_URL = "http://....../weixin/appNotify";//APP后台服务器异步通知
public final static String OWNOTIFY_URL = "http://....../weixin/OWnotify";//扫码支付后台服务器异步通知
public static final String diamond_url = "http://www.xxx.com/GetRechergePrice";//公众号充值钻石表
}
PayCommonUtil
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
public class PayCommonUtil
{
/**
* 默认16 位随机字符串
* @return
*/
public static String CreateNoncestr()
{
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String res = "";
for (int i = 0; i < 16; i++) {
Random rd = new Random();
res += chars.charAt(rd.nextInt(chars.length() - 1));
}
return res;
}
/**
* 签名工具
* @Description:sign签名
* @param characterEncoding 编码格式 UTF-8
* @param parameters 请求参数
* @return
*/
public static String createSign(String characterEncoding,
Map<String, Object> parameters)
{
StringBuffer sb = new StringBuffer();
Iterator<Entry<String, Object>> it = parameters.entrySet().iterator();
while (it.hasNext())
{
Map.Entry <String,Object>entry = (Map.Entry<String,Object>) it.next();
String key = (String) entry.getKey();
Object value = entry.getValue();//去掉带sign的项
if (null != value && !"".equals(value) && !"sign".equals(key)
&& !"key".equals(key)) {
sb.append(key + "=" + value + "&");
}
}
sb.append("key=" + WeixinConfigUtil.API_KEY);
//注意sign转为大写
return MD5Utils.getMD5(sb.toString()).toUpperCase();
}
public static String createAPPSign(String characterEncoding,
Map<String, Object> parameters)
{
StringBuffer sb = new StringBuffer();
Iterator<Entry<String, Object>> it = parameters.entrySet().iterator();
while (it.hasNext())
{
Map.Entry <String,Object>entry = (Map.Entry<String,Object>) it.next();
String key = (String) entry.getKey();
Object value = entry.getValue();//去掉带sign的项
if (null != value && !"".equals(value) && !"sign".equals(key)
&& !"key".equals(key)) {
sb.append(key + "=" + value + "&");
}
}
sb.append("key=" + WeixinConfigUtil.APPAPI_KEY);
//注意sign转为大写
return MD5Utils.getMD5(sb.toString()).toUpperCase();
}
/**
* @date
* @Description:将请求参数转换为xml格式的string
* @param parameters 请求参数
* @return
*/
public static String getRequestXml(SortedMap<String, Object> parameters)
{
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Iterator<Entry<String, Object>> iterator = parameters.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,Object> entry = (Map.Entry<String,Object>) iterator.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();
}
public static boolean checkIsSignValidFromResponseString(String responseString)
{
try
{
SortedMap<String, Object> map = XMLUtil.doXMLParse(responseString);
String signFromAPIResponse = map.get("sign").toString();
if ("".equals(signFromAPIResponse) || signFromAPIResponse == null)
{
return false;
}
//清掉返回数据对象里面的Sign数据(不能把这个数据也加进去进行签名),然后用签名算法进行签名
map.put("sign", "");
//将API返回的数据根据用签名算法进行计算新的签名,用来跟API返回的签名进行比较
String signForAPIResponse = PayCommonUtil.createSign("UTF-8", map);
if (!signForAPIResponse.equals(signFromAPIResponse))
{
//签名验不过,表示这个API返回的数据有可能已经被篡改了
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean checkIsAPPSignValidFromResponseString(String responseString)
{
try
{
SortedMap<String, Object> map = XMLUtil.doXMLParse(responseString);
String signFromAPIResponse = map.get("sign").toString();
if ("".equals(signFromAPIResponse) || signFromAPIResponse == null)
{
return false;
}
//清掉返回数据对象里面的Sign数据(不能把这个数据也加进去进行签名),然后用签名算法进行签名
map.put("sign", "");
//将API返回的数据根据用签名算法进行计算新的签名,用来跟API返回的签名进行比较
String signForAPIResponse = PayCommonUtil.createAPPSign("UTF-8", map);
if (!signForAPIResponse.equals(signFromAPIResponse))
{
//签名验不过,表示这个API返回的数据有可能已经被篡改了
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**排序
* @param map
* @return
*/
public static SortedMap<String, Object> sortMap(Map<String, Object> map) {
new TreeMap<String, String>(new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 升序排序
return obj1.compareTo(obj2);
}
});
SortedMap<String, Object> sortmap = new TreeMap<String, Object>();
for (String key : map.keySet()) {
sortmap.put(key, map.get(key));
}
return sortmap;
}
}
XMLUtil
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
/**
* @desc:XML 解析工具
*/
@SuppressWarnings("all")
public class XMLUtil {
/**
* 解析xml,返回第一级元素键值对。
* 如果第一级元素有子节点,
* 则此节点的值是子节点的xml数据。
*
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static SortedMap<String, Object> doXMLParse(String strxml)
throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if (null == strxml || "".equals(strxml)) {
return null;
}
SortedMap<String, Object> map = new TreeMap<String, Object>();
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 key = e.getName();
String value = "";
List children = e.getChildren();
if (children.isEmpty()) {
value = e.getTextNormalize();
} else {
value = XMLUtil.getChildrenText(children);
}
map.put(key, value);
}
// 关闭流
in.close();
return map;
}
/**
* 获取子结点的xml
* @param children
* @return
*/
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(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
}
MD5Utils
import java.security.MessageDigest;
public class MD5Utils {
// 十六进制下数字到字符的映射数组
private final static String[] HEXDIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d","e", "f" };
public final static String getMD5(String str){
if (str != null) {
try {
// 创建具有指定算法名称的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results = md.digest(str.getBytes()); // 将得到的字节数组变成字符串返回
StringBuffer resultSb = new StringBuffer();
String a = "";
for (int i = 0; i < results.length; i++) {
int n = results[i];
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
a = HEXDIGITS[d1] + HEXDIGITS[d2];
resultSb.append(a);
}
return resultSb.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
}
WeixinOrderRequest
public class WeixinOrderRequest {
private long uid;
private String itemId;// 充值商品id
private String code;//网站支付需要传此参数,用来获取openid
//并生成get/set方法
Order
public class Order {
private String orderId;// 用户订单账号
private String appId;// 应用APPID
private String nonceStr;// 随机字符串
private String prepayId;// 预支付交易会话标识
private String sign;// 签名
private long timeStamp;// 时间戳
private String mchId;// 商户号
//并生成get/set方法
OrderNATIVE
public class OrderNATIVE extends Order
{
private String code_url;//二维码链接
}