生成訂單號json
public String getOutTradeNo() {
SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
Locale.getDefault());
Date date = new Date();
String key = format.format(date);api
Random r = new Random();
key = key + r.nextInt();
key = key.substring(0, 15);
return key;
}微信
加簽名(支付寶)app
public boolean getSign(Result ret, OrderVo ord){
out_trade_no = getOutTradeNo();
//僅設置result的msg
String orderInfo = getOrderInfo("xxxx", "xxxxx", out_trade_no, "0.01");
String tmpsign = sign(orderInfo);
try {
// 僅需對sign 作URL編碼
tmpsign = URLEncoder.encode(tmpsign, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
ret.resp(404, "獲取訂單錯誤");
return false;
}
sign = orderInfo + "&sign=\"" + tmpsign + "\"&" + getSignType();
return true;
}
public String sign(String content) {
return SignUtils.sign(content, Config.RSA_PRIVATE);
}dom
public String getSignType() {
return "sign_type=\"RSA\"";
}post
加簽名 微信測試
public boolean getSign(Result ret, OrderVo ord, String ip){
//僅設置result的msg
Map<String, String> restmap = null;
boolean flag = true; // 是否訂單建立成功
try {
String total_fee = BigDecimal.valueOf(0.01).multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
Map<String, String> parm = new HashMap<String, String>();
parm.put("appid", Config.APP_ID);
parm.put("mch_id", Config.MCH_ID);
parm.put("device_info", "WEB"); //設備信息
out_trade_no = WxPayUtil.getTradeNo();
parm.put("nonce_str", WxPayUtil.getNonceStr());
parm.put("body", "測試付費");
parm.put("attach", "今日秀場"); //附加數據,如深圳分店
parm.put("out_trade_no", out_trade_no);
parm.put("total_fee", total_fee);
parm.put("spbill_create_ip", ip);
parm.put("notify_url", Config.FDBACK);
parm.put("trade_type", "APP");
parm.put("sign", WxPayUtil.getSign(parm, Config.API_SECRET));
String restxml = HttpUtils.posts(Config.ORDER_PAY, XmlUtil.xmlFormat(parm, false));
System.out.println("--"+restxml);
restmap = XmlUtil.xmlParse(restxml);
} catch (Exception e) {
e.printStackTrace();
ret.resp(404, "獲取訂單錯誤");
return false;
}
prepayid = restmap.get("prepay_id");
noncestr = WxPayUtil.getNonceStr();
timestamp = WxPayUtil.payTimestamp();
Map<String, String> payMap = new HashMap<String, String>();
if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
payMap.put("appid", Config.APP_ID);
payMap.put("partnerid", Config.MCH_ID);
payMap.put("prepayid", prepayid);
payMap.put("package", "Sign=WXPay");
payMap.put("noncestr", noncestr);
payMap.put("timestamp", timestamp);
try {
payMap.put("sign", WxPayUtil.getSign(payMap, Config.API_SECRET));
sign = payMap.get("sign");
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
}
if (flag) {
return true;
} else {
return false;
}
}ui
app端接口生成訂單編碼
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "提交訂單")
@ApiResponses(value = { @ApiResponse(code = 700, message = "保存成功,但建立支付信息失敗,須要從新調用支付接口") })
public OrderAddResult addOrder(OrderVo order) {
OrderAddResult ret = new OrderAddResult();
User user = validateUser(ret, 0, 0);
if (user == null) {
return ret;
}
if(!order.add(ret, user)){
return ret;
}
ret.resp(700, "保存訂單成功");
try{
if(order.getPayType() == 1){
if(order.getAlipay().getSign(ret, order)){
order.setPaystate(0);
Orders o=order.toModel();
o.save();
//order.updateAlipay();
}else{
return ret;
}
}else{
//order.wxpay = new WxPay();
if(order.getWxpay().getSign(ret, order, WxPayUtil.getRemoteAddrIp(getReq()))){
//order.updateWxpay();
order.setPaystate(0);
Orders o=order.toModel();
o.save();
}else{
return ret;
}
}
}finally {
ret.data = order;
}
return ret.resp(0, "建立訂單成功");
}url
最後驗證支付結果
@GET
@Path("/result/validate/{id}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "驗證支付結果")
public Result validate(@ApiParam(value = "訂單id", required = true) @PathParam("id") long mid) {
Result ret = new Result();
User user = validateUser(ret, 0, 0);
if (user == null) {
return ret;
}
Orders order1 = Orders.getOrder(user.getId(), mid);//根據用戶獲取訂單信息
OrderVo order=order1.toVo();
if(order == null){
return ret.resp(103, "訂單不存在");
}
if(order.getPayType() == 1){
if(order.getAlipay() != null){
int c = order.getAlipay().checkState(ret, order);
if(c == 0){
order.updateState(1);
int co=user.updateCoins(order.getCoins());
if(co==0){
ret.resp(0,"充值成功");
}
}
}else{
ret.resp(107, "未找到支付信息");
}
}else{
if(order.getWxpay() != null){
int c = order.getWxpay().checkState(ret, order);
if(c == 0){
order.updateState(1);
int co=user.updateCoins(order.getCoins());
if(co==0){
ret.resp(0,"充值成功");
}
}
}else{
ret.resp(107, "未找到支付信息");
}
}
return ret;
}
微信驗證支付狀態
public int checkState(Result ret, OrderVo order){
Map<String, String> restmap = null;
try {
Map<String, String> parm = new HashMap<String, String>();
parm.put("appid", Config.APP_ID);
parm.put("mch_id", Config.MCH_ID);
//parm.put("transaction_id", tradeid);
parm.put("out_trade_no", out_trade_no);
parm.put("nonce_str", WxPayUtil.getNonceStr());
parm.put("sign", WxPayUtil.getSign(parm, Config.API_SECRET));
String restxml = HttpUtils.post(Config.ORDER_PAY_QUERY, XmlUtil.xmlFormat(parm, false));
/*
SUCCESS—支付成功
REFUND—轉入退款
NOTPAY—未支付
CLOSED—已關閉
REVOKED—已撤銷(刷卡支付)
USERPAYING--用戶支付中
PAYERROR--支付失敗(其餘緣由,如銀行返回失敗)
*/
restmap = XmlUtil.xmlParse(restxml);
} catch (Exception e) {
e.printStackTrace();
ret.resp(500, "查詢出錯,請稍後再試");
return 500;
}
if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
// 訂單查詢成功 處理業務邏輯
String state = restmap.get("trade_state");
if("NOTPAY".equals(state)){
ret.resp(100, "未支付");
}else if("SUCCESS".equals(state)){
ret.resp(0, "訂單支付成功");
}else if("REVOKED".equals(state)){
ret.resp(107, "已撤消(刷卡支付)");
}else if("USERPAYING".equals(state)){
ret.resp(100, "用戶支付中");
}else if("REFUND".equals(state)){
ret.resp(100, "轉入退款");
}else if("CLOSED".equals(state)){
ret.resp(107, "訂單已關閉");
}else{
ret.resp(108, "未知錯誤");
}
//System.out.println("訂單查詢:訂單" + restmap.get("out_trade_no") + "支付成功");
} else {
if (CollectionUtil.isNotEmpty(restmap)) {
ret.resp(100, "訂單支付失敗:"+restmap.get("err_code")+"" + restmap.get("err_code_des"));
}else{
ret.resp(100, "訂單支付失敗");
}
}
return ret.code;
}
支付寶驗證支付狀態方法
public int checkState(Result ret,OrderVo order){ AlipayClient client = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", Config.APPID, Config.RSA_PRIVATE,"json","UTF-8",Config.ALIPAY_PUBKEY); AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); Map<String, Object> maps = new HashMap<String, Object>(); maps.put("out_trade_no", out_trade_no); request.setBizContent(Json.getGson().toJson(maps).replaceAll(" | |\n", "")); try { AlipayTradeQueryResponse response = client.execute(request); System.out.println(Json.getGson().toJson(response)); if("10000".equals(response.getCode())){ String tradeState = response.getTradeStatus(); if("WAIT_BUYER_PAY".equals(tradeState)){ //等待付款 ret.resp(100, "用戶支付中"); }else if("TRADE_CLOSED".equals(tradeState)){ //未付款交易超時關閉,或支付完成後全額退款 }else if("TRADE_SUCCESS".equals(tradeState)){ //交易支付成功 ret.resp(0, "訂單支付成功"); }else if("TRADE_FINISHED".equals(tradeState)){ //交易結束,不可退款 ret.resp(107, "交易結束,不可退款"); }else{ ret.resp(108, "未知狀態錯誤"); } }else{ System.out.println(Json.getGson().toJson(response)); ret.resp(500, "查詢支付狀態出錯,請稍後再試"); return 500; } } catch (AlipayApiException e) { e.printStackTrace(); ret.resp(500, "查詢出錯,請稍後再試"); return 500; } return ret.code; }