@kangwg
2017-04-09T14:37:05.000000Z
字数 7921
阅读 1397
layout: post
title: "支付宝支付"
subtitle: "app支付,网页支付,扫码支付"
date: 2017-04-09 12:00:00
author: "kangwg"
header-img: "img/post-bg-2015.jpg"
catalog: true
先导入第三方jar包
建立基类,所有支付类型都继承它
import java.util.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alipay.api.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import cn.swao.baselib.util.*;
@Service
public class AliParamService {
private static Logger log = LoggerFactory.getLogger(AliParamService.class);
@Value("${partner:}")
protected String partner;
@Value("${private_key:}")
protected String private_key;
@Value("${public_key:}")
protected String public_key;
@Value("${alipay_public_key:}")
protected String alipay_public_key;
@Value("${notify_url:}")
protected String notify_url;
@Value("${app_id:}")
protected String app_id;
@Value("${timeout_express:}")
protected String timeout_express;
protected String sign_type = "RSA";
protected String input_charset = "utf-8";
protected String format = "json";
protected String version = "1.0";
protected AlipayClient alipayClient = null;
public void getClient(String requestUrl) {
alipayClient = new DefaultAlipayClient(requestUrl, app_id, private_key, format, input_charset, alipay_public_key);
}
// 异步 synNotify
public boolean asynNotify(Map<String, String> map) {
boolean flag = false;
try {
log.info(LogUtils.gen("map", map));
if (partner.equals(map.get("seller_id")) && app_id.equals(map.get("app_id"))) {
log.info("partner:" + partner + "seller_id" + map.get("seller_id"));
flag = AlipaySignature.rsaCheckV1(map, alipay_public_key, input_charset);
}
} catch (AlipayApiException e) {
log.info("异步通知校验失败", e);
flag = false;
}
return flag;
}
// 同步
public boolean synNotify(Map<String, String> alipay, String sign) {
boolean flag = false;
log.info("同步验证参数,alipay={},sign={}", alipay, sign);
try {
if (partner.equals(alipay.get("seller_id")) && app_id.equals(alipay.get("app_id"))) {
log.info("开始同步签名验证");
flag = AlipaySignature.rsaCheckContent(JSONUtils.toJson(alipay).toString(), sign, alipay_public_key, input_charset);
}
} catch (AlipayApiException e) {
log.info("同步通知校验失败", e);
flag = false;
}
return flag;
}
/**
* out_trade_no 支付时传入的商户订单号,与trade_no必填一个 trade_no 支付时返回的支付宝交易号,与out_trade_no必填一个
*/
public String queryOrder(Map<String, String> map) {
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();// 创建API对应的request类
AlipayTradeQueryResponse response = null;
String result = null;
try {
request.setBizContent(JSONUtils.toJson(AlipayCore.emptyFilter(map)).toString());// 设置业务参数
response = alipayClient.execute(request);
result = response.getBody();
} catch (AlipayApiException e) {
log.info("查询订单失败{}", map);
}
return result;
}
// 退款
public Map<String, Object> refund(Map<String, String> map) {
log.info("ali开始退款");
log.info(LogUtils.gen("map", map));
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
request.setBizContent(JSONUtils.toJson(AlipayCore.emptyFilter(map)).toString());
AlipayTradeRefundResponse response = null;
boolean flag = false;
String msg = null;
String subCode = null;
String out_trade_no = null;
Map<String, Object> data = new HashMap<String, Object>();
try {
response = alipayClient.execute(request);
out_trade_no = response.getOutTradeNo();
// Map body = WebUtils.getJsonParams(response.getBody());
} catch (Exception e) {
msg = "退款失败:" + e;
log.info(msg);
data.put("flag", flag);
data.put("msg", "退款失败");
return data;
}
if (response != null && response.isSuccess()) {
String fundChange = response.getFundChange();
if ("Y".equals(fundChange)) {
flag = true;
msg = "退款成功";
data.put("out_trade_no", out_trade_no);
data.put("refund_fee", response.getRefundFee());
data.put("gmtRefundPay", response.getGmtRefundPay());
data.put("buyer_logon_id", response.getBuyerLogonId());
} else if ("N".equals(fundChange)) {
msg = "已完成退款,不可重复退款";
flag = false;
}
} else {
msg = response.getSubMsg();
subCode = response.getSubCode();
flag = false;
}
data.put("msg", msg);
data.put("flag", flag);
data.put("subCode", subCode);
log.info(LogUtils.gen("refund return", "out_trade_no", out_trade_no, "msg", msg, "subCode", subCode));
return data;
}
}
基类提供了获取支付对象、查询、退款的方法
1.app支付
import java.util.*;
import javax.annotation.PostConstruct;
import org.slf4j.*;
import org.springframework.stereotype.Service;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import cn.swao.baselib.util.*;
@Service
public class AlipayService extends AliParamService {
private static Logger log = LoggerFactory.getLogger(AlipayService.class);
private String method = "alipay.trade.app.pay";
private String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
@PostConstruct
public void init() {
super.getClient(ALIPAY_GATEWAY_NEW);
}
// 获取签名
public String buildRequestPara(Map<String, String> sParaTemp) throws Exception {
log.info("ali开始获取签名");
log.info(LogUtils.gen("sParaTemp", sParaTemp));
Map<String, String> map = new HashMap<String, String>();
map.put("app_id", app_id);
map.put("method", method);
map.put("format", format);
map.put("charset", input_charset);
map.put("sign_type", sign_type);
map.put("notify_url", notify_url);
map.put("timestamp", DateUtils.toDateTimeString(new Date()));
map.put("version", version);
sParaTemp.put("seller_id", partner);
sParaTemp.put("timeout_express", timeout_express);
map.put("biz_content", JSONUtils.toJson(sParaTemp).toString());
String sign = AlipaySignature.rsaSign(map, private_key, input_charset);
map.put("sign", sign);
String linkString = AlipayCore.encodeMap2String(map);
log.info("签名alipay:" + linkString);
return linkString;
}
}
其他app支付的验签查询的方法都来自父类
2.网页支付和扫码支付
import cn.swao.baselib.util.JSONUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import org.assertj.core.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
@Service
public class AliMpService extends AliParamService {
private static Logger log = LoggerFactory.getLogger(AliMpService.class);
private String method = "alipay.trade.wap.pay";
private String ALIPAY_OPEN_NEW = "https://openapi.alipay.com/gateway.do";
private String apiVersion = "3";
private String product_code = "QUICK_WAP_PAY";
@Value("${returnUrl:}")
private String return_url;
@Value("${qrCodeUrl:}")
public String LIANTU_URL;//生成二维码
@PostConstruct
public void init() {
super.getClient(ALIPAY_OPEN_NEW);
}
// 手机网站支付下单
public String buildRequestPara(Map<String, String> sParaTemp) throws Exception {
AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();// 创建API对应的request
alipayRequest.setNotifyUrl(notify_url);
alipayRequest.setApiVersion(apiVersion);
if (!Strings.isNullOrEmpty(sParaTemp.get("selfparam"))) {
String returnUrl = new StringBuffer(return_url).append("?selfparam=").append(sParaTemp.get("selfparam")).toString();
alipayRequest.setReturnUrl(returnUrl);
sParaTemp.remove("selfparam");
} else {
alipayRequest.setReturnUrl(return_url);
}
sParaTemp.put("product_code", product_code);
String biz_content = JSONUtils.toJson(AlipayCore.emptyFilter(sParaTemp)).toString();
alipayRequest.setBizContent(biz_content);
log.info("支付宝手机网站支付业务参数:{}", alipayRequest);
String form = super.alipayClient.pageExecute(alipayRequest).getBody();
log.info("支付宝手机网站支付下单后参数:{}", form);
return form;
}
/**
* 扫码支付生成二维码 map中必要参数 out_trade_no,total_amount,subject,store_id(门店编号)
*/
public String buildRequestQrCode(Map<String, String> sParaTemp) {
AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
request.setNotifyUrl(notify_url);
sParaTemp.put("timeout_express", timeout_express);
String bizContent = JSONUtils.toJson(sParaTemp);
request.setBizContent(bizContent);
log.info("扫码预下单:sParaTemp:{}", sParaTemp);
try {
AlipayTradePrecreateResponse execute = super.alipayClient.execute(request);
String qrCode = execute.getQrCode();
String qrCodeUrl = LIANTU_URL + URLEncoder.encode(qrCode, "UTF-8");
String body = execute.getBody();
log.info("qrCode:{},qrCodeUrl:{},AlipayTradePrecreateResponse.Body:{}", qrCode, qrCodeUrl, body);
return qrCodeUrl;
} catch (AlipayApiException | UnsupportedEncodingException e) {
log.error("扫码预下单失败", e);
return null;
}
}
}