1. Transfer payment process:
Step 1: create an app and get APPID
Open platform to ant golden clothing( open.alipay.com )To create an application in the developer center, an app unique ID (APPID) will be generated and the payment function will be applied for..
Step 2: configure the key
- The Alipay public key: Alipay's RSA public key. The merchant uses the public key to verify whether the result is returned by Alipay.
- 2. Download the RSA key tool of Alibaba cloud to generate the key and public key (download address: https://docs.open.alipay.com/291/106097/)
- 3. Upload the public key generated by the tool to Alibaba cloud, put the private key to the server, and use it when calling the interface
Step 3: integration and development
1: import jar package
<!-- Ali cloud Alipay paid jar --> <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>3.3.87.ALL</version> </dependency>
2: specific demo
a: Alibaba cloud basic parameter class:
public interface AliPayConfig {
/** Alipay paid appid */
String APP_ID = "";
/** Application of private key */
String PRIVATE_KEY = "";
//Application of public key
String APP_PUBLIC_KEY = "";
//Alipay public key
String ALI_PUBLIC_KEY ="";
//character set
String CHARSET = "utf-8";
//data format
String FORMAT = "json";
//Encryption mode
String SIGN_TYPE = "RSA2";
/** The following parameters are call addresses */
//Receive Alipay callback address notify_url
//It can be mapped to the local address for testing, not necessarily deployed online
String NOTIFY_URL = "";
String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
}
b: unified single interface
@ResponseBody
@RequestMapping("/aliPayOrder")
public JSONObject aliPayOrder(String outtradeno) {
JSONObject returnValue = null;
//Instantiate client
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL, AliPayConfig.APP_ID, AliPayConfig.PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALI_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
//Instantiate concrete API Corresponding request class,Class name and interface name correspond,The name of the interface is currently called: alipay.trade.app.pay
AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK The public parameters have been encapsulated. Only the business parameters need to be passed in. The following methods are sdk Of model Entry mode(model and biz_content In case of simultaneous existence biz_content).
outtradeno = WeixinPayUtil.getOrderIdByTime();
AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
model.setBody("test");
model.setSubject("App Payment test");
model.setOutTradeNo(outtradeno);
model.setTimeoutExpress("30m");
model.setTotalAmount("0.01");
model.setProductCode("QUICK_MSECURITY_PAY");
request.setBizModel(model);
request.setNotifyUrl(AliPayConfig.NOTIFY_URL);
try {
//This is different from the ordinary interface call, which uses sdkExecute
AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
//Namely orderString It can directly request to the client without further processing.
returnValue = new JSONObject();
returnValue.put("errCode", ErrorCode.SUCCESS_RETRUN);
returnValue.put("errMsg", "ok");
returnValue.put("data", response.getBody());
logger.info("[Alipay unified order --- Success],Order number is:{}",outtradeno);
return returnValue;
} catch (AlipayApiException e) {
logger.info("[Alipay unified order --- Failure],Order number is:{},The reasons are:{}",outtradeno,e.getErrMsg().toString());
returnValue = ErrorCodeUtil.ERROR_FAILED("Order failure");
return returnValue;
}
}
c: payment callback interface
@RequestMapping("aliPay_notify")
public void aliPay_notify(HttpServletRequest request, HttpServletResponse response) {
//Get Alipay POST Come and give feedback
Map<String, String> params = new HashMap<>();
Map requestParams = request.getParameterMap();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
}
params.put(name, valueStr);
}
try {
//Verifying signature
boolean flag = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALI_PUBLIC_KEY, AliPayConfig.CHARSET, AliPayConfig.SIGN_TYPE);
if (flag) {
if ("TRADE_SUCCESS".equals(params.get("trade_status"))) { //Business logic processing
//Payment amount
String amount = params.get("buyer_pay_amount");
//Merchant order number
String out_trade_no = params.get("out_trade_no");
//Alipay transaction number
String trade_no = params.get("trade_no");
//Additional data
String passback_params = params.get("passback_params");
response.getWriter().write("success");
}
}else {
logger.info("[Alipay payment--Asynchronous callback] callback failed,Signature verification failed");
}
} catch (AlipayApiException e) {
logger.error("[Alipay payment--Asynchronous callback] callback failed,Alibaba cloud interface call error,The reason is:{}",e.getMessage());
} catch (Exception e) {
logger.error("[Alipay payment--Asynchronous callback] callback failed,The reason is:{}",e.getMessage());
}
}
d: refund interface
@RequestMapping("aliPay_refund")
@ResponseBody
public JSONObject aliPay_refund(final String outTradeNo,final String transactionId){
JSONObject returnValue = null ;
try {
//Instantiate client
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL, AliPayConfig.APP_ID, AliPayConfig.PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALI_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
//Instantiate concrete API Corresponding request class,Class name and interface name correspond,The name of the interface is currently called: alipay.trade.refund
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//SDK The public parameters have been encapsulated. Only the business parameters need to be passed in. The following methods are sdk Of model Entry mode(model and biz_content In case of simultaneous existence biz_content).
AlipayTradeRefundModel model = new AlipayTradeRefundModel();
//Priority use of Alipay orders id
if(transactionId == null || transactionId.length() == 0){
model.setOutTradeNo(outTradeNo);
}else {
model.setTradeNo(transactionId);
}
//Test amount 1 cent
String price = "0.01";
//Test refund reason
model.setRefundReason("Test refund");
//refund amount
model.setRefundAmount(price);
request.setBizModel(model);
AlipayTradeRefundResponse response = alipayClient.execute(request);
if(response.isSuccess()){
returnValue = ErrorCodeUtil.ERROR_FAILED("Refund successful");
return returnValue ;
} else {
returnValue = ErrorCodeUtil.ERROR_FAILED(response.getSubMsg());
return returnValue ;
}
}catch (AlipayApiException e) {
logger.error("[Alipay payment -- Refund failed] because:{}",e.getMessage());
returnValue = ErrorCodeUtil.ERROR_FAILED("Refund failed");
return returnValue ;
}
}
e: close order
@ResponseBody
@RequestMapping("aliPay_close")
public JSONObject aliPay_close(final String outTradeNo,final String transactionId){
JSONObject returnValue = null ;
try {
//Instantiate client
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL, AliPayConfig.APP_ID, AliPayConfig.PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALI_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
//Instantiate concrete API Corresponding request class,Class name and interface name correspond,The name of the interface is currently called: alipay.trade.close
AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
//SDK The public parameters have been encapsulated. Only the business parameters need to be passed in. The following methods are sdk Of model Entry mode(model and biz_content In case of simultaneous existence biz_content).
AlipayTradeCloseModel model = new AlipayTradeCloseModel();
//Priority use of Alipay orders id
if(transactionId == null || transactionId.length() == 0){
model.setOutTradeNo(outTradeNo);
}else {
model.setTradeNo(transactionId);
}
request.setBizModel(model);
AlipayTradeCloseResponse response = alipayClient.execute(request);
if(response.isSuccess()){
returnValue = ErrorCodeUtil.ERROR_FAILED("Order closed successfully");
return returnValue ;
} else {
returnValue = ErrorCodeUtil.ERROR_FAILED(response.getSubMsg());
return returnValue ;
}
}catch (AlipayApiException e) {
logger.error("[Alipay payment -- Close order] failed to close the order,The reason is:{}",e.getMessage());
returnValue = ErrorCodeUtil.ERROR_FAILED("Order closing failed");
return returnValue ;
}
}
f: query order status
@ResponseBody
@RequestMapping("aliPay_query")
public JSONObject aliPay_query(final String outTradeNo,final String transactionId){
JSONObject returnValue = null ;
try {
//Instantiate client
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL, AliPayConfig.APP_ID, AliPayConfig.PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALI_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
//Instantiate concrete API Corresponding request class,Class name and interface name correspond,The name of the interface is currently called: alipay.trade.query
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
//SDK The public parameters have been encapsulated. Only the business parameters need to be passed in. The following methods are sdk Of model Entry mode(model and biz_content In case of simultaneous existence biz_content).
AlipayTradeQueryModel model = new AlipayTradeQueryModel();
//Priority use of Alipay orders id
if(transactionId == null || transactionId.length() == 0){
model.setOutTradeNo(outTradeNo);
}else {
model.setTradeNo(transactionId);
}
request.setBizModel(model);
AlipayTradeQueryResponse response = alipayClient.execute(request);
if(response.isSuccess()){
if("WAIT_BUYER_PAY".equals(response.getTradeStatus())){
returnValue = ErrorCodeUtil.ERROR_FAILED("Transaction creation, waiting for buyer payment");
return returnValue ;
}else if("TRADE_CLOSED".equals(response.getTradeStatus())){
returnValue = ErrorCodeUtil.ERROR_FAILED("Overdue closing of unpaid transactions or full refund upon completion of payment");
return returnValue ;
}else if("TRADE_SUCCESS".equals(response.getTradeStatus())){
returnValue = ErrorCodeUtil.ERROR_FAILED("Transaction payment succeeded");
return returnValue ;
}else if("TRADE_FINISHED".equals(response.getTradeStatus())){
returnValue = ErrorCodeUtil.ERROR_FAILED("Transaction closed, non refundable");
return returnValue ;
}else {
returnValue = ErrorCodeUtil.ERROR_FAILED("Unknown state");
return returnValue ;
}
} else {
returnValue = ErrorCodeUtil.ERROR_FAILED(response.getSubMsg());
return returnValue ;
}
}catch (AlipayApiException e) {
logger.error("[Alipay payment -- Failed to query order,The reason is:{}",e.getMessage());
returnValue = ErrorCodeUtil.ERROR_FAILED("Order query failed");
return returnValue ;
}
}