一:集成步驟
1.引入依賴:
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.7.110.ALL</version>
</dependency>
2.支付寶app支付參數(shù)配置:
#服務器域名地址
server.service-domain = http://127.0.0.1:8080
##支付寶支付
pay.alipay.gatewayUrl="支付寶gatewayUrl"
pay.alipay.appid="商戶應用id"
pay.alipay.app-private-key="應用RSA私鑰弊添,用于對商戶請求報文加簽"
pay.alipay.alipay-public-key="支付寶RSA公鑰鬼悠,用于驗簽支付寶應答"
#支付成功的異步通知回調接口
pay.alipay.notify-url=${server.service-domain}/api/alipay/notify
3.定義配置類:
package com.annaru.upms.payment.config;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* 支付寶支付的參數(shù)配置
*
* @author mengday zhang
*/
@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "pay.alipay")
public class AlipayConfig {
/**
* 支付寶gatewayUrl
*/
private String gatewayUrl;
/**
* 商戶應用id
*/
private String appid;
/**
* RSA私鑰删性,用于對商戶請求報文加簽
*/
private String appPrivateKey;
/**
* 支付寶RSA公鑰,用于驗簽支付寶應答
*/
private String alipayPublicKey;
/**
* 簽名類型
*/
private String signType = "RSA2";
/**
* 格式
*/
private String formate = "json";
/**
* 編碼
*/
private String charset = "UTF-8";
/**
* 同步地址
*/
private String returnUrl;
/**
* 異步地址
*/
private String notifyUrl;
/**
* 最大查詢次數(shù)
*/
private static int maxQueryRetry = 5;
/**
* 查詢間隔(毫秒)
*/
private static long queryDuration = 5000;
/**
* 最大撤銷次數(shù)
*/
private static int maxCancelRetry = 3;
/**
* 撤銷間隔(毫秒)
*/
private static long cancelDuration = 3000;
@Bean
public AlipayClient alipayClient(){
return new DefaultAlipayClient(this.getGatewayUrl(),
this.getAppid(),
this.getAppPrivateKey(),
this.getFormate(),
this.getCharset(),
this.getAlipayPublicKey(),
this.getSignType());
}
}
4. 定義controller:
在調用微信服務接口進行統(tǒng)一下單之前焕窝,
1蹬挺、為保證安全性,建議驗證數(shù)據(jù)庫是否存在訂單號對應的訂單它掂。
package com.annaru.upms.payment.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.annaru.common.base.BaseController;
import com.annaru.common.result.ResultMap;
import com.annaru.common.util.Constant;
import com.annaru.upms.entity.OrderMain;
import com.annaru.upms.entity.OrderPayment;
import com.annaru.upms.payment.service.AlipayService;
import com.annaru.upms.service.IOrderMainService;
import com.annaru.upms.service.IOrderPaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Api(tags = "支付寶支付接口管理")
@RestController
@RequestMapping("/alipay")
public class AlipayController extends BaseController {
@Reference
private IOrderPaymentService orderPaymentService;
@Reference
private IOrderMainService orderMainService;
@Autowired
private AlipayService alipayService;
/**
* 創(chuàng)建訂單
*/
@ApiOperation(value = "創(chuàng)建訂單", notes = "支付寶支付創(chuàng)建訂單")
@GetMapping("/createOrder")
public ResultMap createOrder(@ApiParam(value = "訂單號") @RequestParam String orderNo,
@ApiParam(value = "訂單金額") @RequestParam double amount,
@ApiParam(value = "商品名稱") @RequestParam String body) {
try {
// 1巴帮、驗證訂單是否存在
// 2、創(chuàng)建支付寶訂單
String orderStr = alipayService.createOrder(orderNo, amount, body);
return ResultMap.ok().put("data", orderStr);
} catch (Exception e) {
logger.error(e.getMessage());
return ResultMap.error("訂單生成失敗");
}
}
/**
* 支付異步通知
* 接收到異步通知并驗簽通過后虐秋,一定要檢查通知內容榕茧,
* 包括通知中的app_id、out_trade_no客给、total_amount是否與請求中的一致用押,并根據(jù)trade_status進行后續(xù)業(yè)務處理。
* https://docs.open.alipay.com/194/103296
*/
@RequestMapping("/notify")
public String notify(HttpServletRequest request) {
// 驗證簽名
boolean flag = alipayService.rsaCheckV1(request);
if (flag) {
String tradeStatus = request.getParameter("trade_status"); // 交易狀態(tài)
String outTradeNo = request.getParameter("out_trade_no"); // 商戶訂單號
String tradeNo = request.getParameter("trade_no"); // 支付寶訂單號
/**
* 還可以從request中獲取更多有用的參數(shù)靶剑,自己嘗試
*/
boolean notify = alipayService.notify(tradeStatus, outTradeNo, tradeNo);
if(notify){
return "success";
}
}
return "fail";
}
@ApiOperation(value = "退款", notes = "退款")
@PostMapping("/refund")
public ResultMap refund(@ApiParam(value = "訂單號") @RequestParam String orderNo,
@ApiParam(value = "退款金額") @RequestParam double amount,
@ApiParam(value = "退款原因") @RequestParam(required = false) String refundReason) {
return alipayService.refund(orderNo, amount, refundReason);
}
}
5蜻拨、定義service接口:
package com.annaru.upms.payment.service;
import com.alipay.api.AlipayApiException;
import javax.servlet.http.HttpServletRequest;
/**
* 支付寶服務接口
*
* Author:
* Date:2019/8/1
* Description:
*/
public interface AlipayService {
/**
* @Description: 創(chuàng)建支付寶訂單
* @param orderNo: 訂單編號
* @param amount: 實際支付金額
* @param body: 訂單描述
* @Author:
* @Date: 2019/8/1
* @return
*/
String createOrder(String orderNo, double amount, String body) throws AlipayApiException;
/**
* @Description:
* @param tradeStatus: 支付寶交易狀態(tài)
* @param orderNo: 訂單編號
* @param tradeNo: 支付寶訂單號
* @Author:
* @Date: 2019/8/1
* @return
*/
boolean notify(String tradeStatus, String orderNo, String tradeNo);
/**
* @Description: 校驗簽名
* @param request
* @Author:
* @Date: 2019/8/1
* @return
*/
boolean rsaCheckV1(HttpServletRequest request);
/**
* @Description: 退款
* @param orderNo: 訂單編號
* @param amount: 實際支付金額
* @param refundReason: 退款原因
* @Author: XCK
* @Date: 2019/8/6
* @return
*/
ResultMap refund(String orderNo, double amount, String refundReason);
}
6、service實現(xiàn)類
package com.annaru.upms.payment.service.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.annaru.upms.payment.config.AlipayConfig;
import com.annaru.upms.payment.service.AlipayService;
import com.annaru.upms.service.IOrderPaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Author:XCK
* Date:2019/8/1
* Description:
*/
@Service
public class AlipayServiceImpl implements AlipayService {
private final Logger logger = LoggerFactory.getLogger(AlipayServiceImpl.class);
@Autowired
private AlipayConfig alipayConfig;
@Autowired
private AlipayClient alipayClient;
@Override
public String createOrder(String orderNo, double amount, String body) throws AlipayApiException {
//SDK已經封裝掉了公共參數(shù)抬虽,這里只需要傳入業(yè)務參數(shù)官觅。以下方法為sdk的model入?yún)⒎绞?model和biz_content同時存在的情況下取biz_content)。
AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
model.setSubject(body);
model.setOutTradeNo(orderNo);
model.setTotalAmount(String.valueOf(amount));
model.setProductCode("QUICK_MSECURITY_PAY");
model.setPassbackParams("公用回傳參數(shù)阐污,如果請求時傳遞了該參數(shù)休涤,則返回給商戶時會回傳該參數(shù)");
//實例化具體API對應的request類,類名稱和接口名稱對應,當前調用接口名稱:alipay.trade.app.pay
AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();
ali_request.setBizModel(model);
ali_request.setNotifyUrl(alipayConfig.getNotifyUrl());// 回調地址
AlipayTradeAppPayResponse ali_response = alipayClient.sdkExecute(ali_request);
//就是orderString 可以直接給客戶端請求,無需再做處理笛辟。
return ali_response.getBody();
}
@Override
public boolean notify(String tradeStatus, String orderNo, String tradeNo) {
if ("TRADE_FINISHED".equals(tradeStatus)
|| "TRADE_SUCCESS".equals(tradeStatus)) {
// 支付成功功氨,根據(jù)業(yè)務邏輯修改相應數(shù)據(jù)的狀態(tài)
// boolean state = orderPaymentService.updatePaymentState(orderNo, tradeNo);
if (state) {
return true;
}
}
return false;
}
@Override
public boolean rsaCheckV1(HttpServletRequest request){
try {
Map<String, String> params = new HashMap<>();
Map<String, String[]> requestParams = request.getParameterMap();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = 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);
}
boolean verifyResult = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
return verifyResult;
} catch (AlipayApiException e) {
logger.debug("verify sigin error, exception is:{}", e);
return false;
}
}
@Override
public ResultMap refund(String orderNo, double amount, String refundReason) {
if(StringUtils.isBlank(orderNo)){
return ResultMap.error("訂單編號不能為空");
}
if(amount <= 0){
return ResultMap.error("退款金額必須大于0");
}
AlipayTradeRefundModel model=new AlipayTradeRefundModel();
// 商戶訂單號
model.setOutTradeNo(orderNo);
// 退款金額
model.setRefundAmount(String.valueOf(amount));
// 退款原因
model.setRefundReason(refundReason);
// 退款訂單號(同一個訂單可以分多次部分退款,當分多次時必傳)
// model.setOutRequestNo(UUID.randomUUID().toString());
AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
alipayRequest.setBizModel(model);
AlipayTradeRefundResponse alipayResponse = null;
try {
alipayResponse = alipayClient.execute(alipayRequest);
} catch (AlipayApiException e) {
logger.error("訂單退款失敗手幢,異常原因:{}", e);
}
if(alipayResponse != null){
String code = alipayResponse.getCode();
String subCode = alipayResponse.getSubCode();
String subMsg = alipayResponse.getSubMsg();
if("10000".equals(code)
&& StringUtils.isBlank(subCode)
&& StringUtils.isBlank(subMsg)){
// 表示退款申請接受成功捷凄,結果通過退款查詢接口查詢
// 修改用戶訂單狀態(tài)為退款
return ResultMap.ok("訂單退款成功");
}
return ResultMap.error(subCode + ":" + subMsg);
}
return ResultMap.error("訂單退款失敗");
}
}
7、定義通用返回結果集 ResultMap
package com.annaru.common.result;
import org.apache.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
/**
* @Description 通用返回結果集
* @Author
* @Date 2018/6/12 15:13
*/
public class ResultMap extends HashMap<String, Object> {
public ResultMap() {
put("state", true);
put("code", 0);
put("msg", "success");
}
public static ResultMap error(int code, String msg) {
ResultMap r = new ResultMap();
r.put("state", false);
r.put("code", code);
r.put("msg", msg);
return r;
}
public static ResultMap error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static ResultMap error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知異常围来,請聯(lián)系管理員");
}
public static ResultMap ok(String msg) {
ResultMap r = new ResultMap();
r.put("msg", msg);
return r;
}
public static ResultMap ok(Map<String, Object> par) {
ResultMap r = new ResultMap();
r.putAll(par);
return r;
}
public static ResultMap ok() {
return new ResultMap();
}
public ResultMap put(String key, Object value) {
super.put(key, value);
return this;
}
}