app支付接口(支付宝 微信)

时间:2024-02-23 08:13:16

生成订单号

public String getOutTradeNo() {
SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
Locale.getDefault());
Date date = new Date();
String key = format.format(date);

Random r = new Random();
key = key + r.nextInt();
key = key.substring(0, 15);
return key;
}

加签名(支付宝)

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);
}

public String getSignType() {
return "sign_type=\"RSA\"";
}

加签名 微信

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;
}
}

 

 

 

 

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, "创建订单成功");
}

最后验证支付结果

@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;
}