JDK 1.8
或以上版本AppId
、应用私钥、应用公钥证书、支付宝公钥证书、支付宝根证书等信息<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.38.10.ALL</version>
</dependency>
位置:
ruoyi-api/src/main/resources/alipay.yml
通过沙箱环境
找到以下所需参数
aliyun:
#AppID
app-id:
notify-url: http://ip:端口/api/order/student/ali/callback #支付回调地址
#应用私钥
private-key:
#应用公钥
app-public-key:
#应用公钥路径
app-public-key-path: /home/config/alipay/app_public_key.crt
#支付宝公钥
ali-public-key:
#支付宝公钥路径
ali-public-key-path: /home/config/alipay/ali_public_key.crt
#支付宝根证书路径
ali-root-key-path: /home/config/alipay/ali_root_key.crt
package com.ruoyi.common.ali;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 获取支付宝支付所需yml配置
**/
@Data
@ConfigurationProperties(prefix = "aliyun")
@Component
@Slf4j
public class AliyunProperties {
//支付回调
private String notifyUrl;
//应用id
private String appId;
//应用私钥
private String privateKey;
//应用公钥
private String appPublicKey;
//应用公钥地址
private String appPublicKeyPath;
//支付宝公钥
private String aliPublicKey;
//支付宝公钥地址
private String aliPublicKeyPath;
//支付宝根证书地址
private String aliRootKeyPath;
}
package com.ruoyi.common.ali;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Log4j2
public class AliPayService {
@Autowired
private AliyunProperties aliyunProperties;
/**
* 支付宝通过证书的方式进行下单
* @param dto 支付宝统一下单请求参数
* @param productCode 手机网站跳转支付宝支付传值QUICK_WAP_WAY,电脑网站扫码支付传FAST_INSTANT_TRADE_PAY
* @return
*/
public String certificatePayment(AliPayDTO dto,String productCode) {
try {
//构造client
CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
//设置网关地址 沙箱环境请修改网关
certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
//设置应用Id
certAlipayRequest.setAppId(aliyunProperties.getAppId());
//设置应用私钥
certAlipayRequest.setPrivateKey(aliyunProperties.getPrivateKey());
//设置请求格式,固定值json
certAlipayRequest.setFormat("json");
//设置字符集
certAlipayRequest.setCharset("UTF-8");
//设置签名类型
certAlipayRequest.setSignType("RSA2");
/******服务器配置******/
//设置应用公钥证书路径
// certAlipayRequest.setCertPath(aliyunProperties.getAppPublicKeyPath());
// //设置支付宝公钥证书路径
// certAlipayRequest.setAlipayPublicCertPath(aliyunProperties.getAliPublicKeyPath());
// //设置支付宝根证书路径
// certAlipayRequest.setRootCertPath(aliyunProperties.getAliRootKeyPath());
/******本地配置******/
//设置应用公钥证书路径
certAlipayRequest.setCertPath("C:\\Users\\__yge__\\Desktop\\config\\app_public_key.crt");
//设置支付宝公钥证书路径
certAlipayRequest.setAlipayPublicCertPath("C:\\Users\\__yge__\\Desktop\\config\\ali_public_key.crt");
//设置支付宝根证书路径
certAlipayRequest.setRootCertPath("C:\\Users\\__yge__\\Desktop\\config\\ali_root_key.crt");
AlipayClient alipayClient = null;
alipayClient = new DefaultAlipayClient(certAlipayRequest);
AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
//异步接收地址,仅支持http/https,公网可访问
request.setNotifyUrl(aliyunProperties.getNotifyUrl());
//同步跳转地址,仅支持http/https
// request.setReturnUrl(aliyunProperties.getNotifyUrl());
/******必传参数******/
JSONObject bizContent = new JSONObject();
//商户订单号,商家自定义,保持唯一性
bizContent.put("out_trade_no", dto.getOutTradeNo());
//支付金额,最小值0.01元
bizContent.put("total_amount", dto.getTotalAmount());
//订单标题,不可使用特殊符号
bizContent.put("subject", dto.getSubject());
/******可选参数******/
//todo 手机网站跳转支付宝支付传值QUICK_WAP_WAY,电脑网站扫码支付传FAST_INSTANT_TRADE_PAY
bizContent.put("product_code", productCode);
// bizContent.put("time_expire", "2022-08-01 22:00:00");
//商品明细信息,按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);
// 扩展信息,按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);
request.setBizContent(bizContent.toString());
// AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
// 如果需要返回GET请求,请使用
AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
String pageRedirectionData = response.getBody();
if (response.isSuccess()) {
return pageRedirectionData;
}
} catch (AlipayApiException e) {
e.printStackTrace();
}
return null;
}
/**
* 支付宝通过秘钥的方式进行下单
* @param dto 支付宝统一下单请求参数
* @param productCode 手机网站跳转支付宝支付传值QUICK_WAP_WAY,电脑网站扫码支付传FAST_INSTANT_TRADE_PAY
* @return
*/
public String keyPayment(AliPayDTO dto,String productCode) {
try {
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
aliyunProperties.getAppId(),
aliyunProperties.getPrivateKey(),
"json",
"utf-8",
aliyunProperties.getAppPublicKey(),
"RSA2");
AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
//异步接收地址,仅支持http/https,公网可访问
request.setNotifyUrl(aliyunProperties.getNotifyUrl());
//同步跳转地址,仅支持http/https
// request.setReturnUrl(aliyunProperties.getNotifyUrl());
/******必传参数******/
JSONObject bizContent = new JSONObject();
//商户订单号,商家自定义,保持唯一性
bizContent.put("out_trade_no", dto.getOutTradeNo());
//支付金额,最小值0.01元
bizContent.put("total_amount", dto.getTotalAmount());
//订单标题,不可使用特殊符号
bizContent.put("subject", dto.getSubject());
/******可选参数******/
//todo 手机网站跳转支付宝支付传值QUICK_WAP_WAY,电脑网站扫码支付传FAST_INSTANT_TRADE_PAY
bizContent.put("product_code", productCode);
// bizContent.put("time_expire", "2022-08-01 22:00:00");
// 商品明细信息,按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);
// 扩展信息,按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);
request.setBizContent(bizContent.toString());
// AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
// 如果需要返回GET请求,请使用
AlipayTradeWapPayResponse response = null;
response = alipayClient.pageExecute(request,"GET");
String pageRedirectionData = response.getBody();
if (response.isSuccess()) {
return pageRedirectionData;
}
} catch (AlipayApiException e) {
e.printStackTrace();
}
return null;
}
}
package com.ruoyi.web.controller.system;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.common.ali.AliPayDTO;
import com.ruoyi.common.ali.AliPayService;
import com.ruoyi.common.ali.AliyunProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
@Api(tags = "支付宝支付相关接口")
@RestController
@Slf4j
@Validated
@RequiredArgsConstructor
@RequestMapping("/ali")
public class AliPayController {
@Resource
private AliPayService aliPayService;
@Resource
private AliyunProperties aliyunProperties;
@ApiOperation(value = "手机网站支付,返回跳转链接")
@GetMapping("/mobilePay")
public Object aliPay(@RequestParam("orderNumber") String orderNumber) {
//todo 按照业务查询订单信息
AliPayDTO dto = new AliPayDTO();
//订单编号
dto.setOutTradeNo(orderNumber);
//支付金额,单位为元
dto.setTotalAmount("0.01");
//订单标题,不可使用特殊符号
dto.setSubject("订单标题");
// 请求阿里云支付
String pay = aliPayService.certificatePayment(dto,"QUICK_WAP_WAY");
return pay;
}
@ApiOperation(value = "电脑网站支付,返回支付二维码")
@GetMapping("/webPay")
public Object scanCodePay(@RequestParam("orderNumber") String orderNumber) {
//todo 按照业务查询订单信息
AliPayDTO dto = new AliPayDTO();
//订单编号
dto.setOutTradeNo(orderNumber);
//支付金额,单位为元
dto.setTotalAmount("0.01");
//订单标题,不可使用特殊符号
dto.setSubject("订单标题");
// 请求阿里云支付
String pay = aliPayService.certificatePayment(dto,"FAST_INSTANT_TRADE_PAY");
return pay;
}
@ApiOperation(value = "支付宝支付回调")
@PostMapping("/callback")
public Object aliCallback(HttpServletRequest request) {
String paramsJson = null;
try {
//获取支付回调信息
Map<String,String> params = new HashMap<String,String>();
Map requestParams = request.getParameterMap();
log.info("异步通知信息为:"+ JSON.toJSONString(requestParams));
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] + ",";
}
//乱码解决,这段代码在出现乱码时使用。
// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
paramsJson = JSON.toJSONString(params);
log.info("支付宝回调信息为: ", params);
//todo 调用SDK验证签名,是支付宝公钥不是应用公钥
boolean signVerified = AlipaySignature.rsaCertCheckV1(params, aliyunProperties.getAliPublicKeyPath(),"utf-8", "RSA2");
if (signVerified) {
//todo 做业务操作,如改订单状态,保存回调信息等
// 如果签名验证正确,返回success
return "success";
} else {
log.info("支付宝回调签名认证失败,signVerified=false, paramsJson:{}", paramsJson);
return "failure";
}
} catch (AlipayApiException e) {
log.error("支付宝回调签名认证失败,paramsJson:{},errorMsg:{}", paramsJson, e.getMessage());
return "failure";
}
}
}
package com.ruoyi.common.ali;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* 支付宝统一下单请求参数
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class AliPayDTO {
/**
* 字段名:商户订单号,商家自定义,保持唯一性
* 变量名:out_trade_no
*/
private String outTradeNo;
/**
* 字段名:支付金额,最小值0.01元
* 变量名:total_amount
*/
private String totalAmount;
/**
* 字段名:订单标题,不可使用特殊符号
* 变量名:subject
*/
private String subject;
}
powered by kaifamiao