一、流程
二、沙箱操作
1.用支付宝账号登录【开放控制平台】创建应用获取 appid
2.选择沙箱模拟环境
3.沙箱应用-》获取appid(一个appid绑定一个收款支付宝账户)
4.利用开发助手工具生成RSA2密钥
公钥:传给支付宝平台
私钥:配置代码中,签名用
5.生成密钥后,进行配置
返回平台 --> 开发信息 --> 自定义密钥 --> 设置并启用(加签)--> 应用公钥
保存后生成支付宝公钥(需要配置到项目中)
6.支付宝网关(配置代码中)
https://openapi.alipaydev.com/gateway.do
2.1、用 nat app 内网穿透工具进行异步/同步回调
NATAPP-内网穿透 基于ngrok的国内高速内网映射工具
2.2、依赖与配置
2.2.1、引入依赖
<dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-sdk-java</artifactId>
</dependency>
2.2.2、配置文件
spring:application:name: alipay-demoserver:port: 9999alipay:appId: 收款账号对应的应用idprivateKey: 应用私钥publicKey: 支付宝公钥returnUrl: 127.0.0.1:9999/order/returnnotifyUrl: 127.0.0.1:9999/order/notify-url(异步回调地址,http/https开头必须外网能访问)refundNotifyUrl: https://blog.csdn.net/qq_37630282(同步回调地址,需要外网能够访问)gatewayUrl: https://openapi.alipaydev.com/gateway.do(沙箱官网与正式网关不同,此处为沙箱网关)charset: utf-8signType: RSA2
2.2.3、支付相关的实体类
支付的配置类
@Data
@Component
@ConfigurationProperties(prefix = "alipay")
public class AlipayConfig {private String appId;private String privateKey;private String publicKey;private String returnUrl;private String notifyUrl;private String refundNotifyUrl;private String gatewayUrl;private String charset;private String signType;
}支付的实体类
@Data
public class AliPay {private String traceNo; // 订单编号private double totalAmount; // 总金额private String subject; // 商品名称private String alipayTraceNo;
}
2.3、支付、回调、退款接口
支付流程
1.在Controller中配置gateway_url(调用支付宝url的一个网关地址)、format(JSON形式)、charset(UTF-8)、sign_type(签名方式-rsa2)
2.编写Get请求,(参数是AliPay的配置类里生成的订单号、总金额、支付的名称、支付宝交易凭证号、HttpServletResponse)
3.创建Client(由通用SDK提供的Client,负责调支付宝的API,设置参数包含网关地址、appid、密钥、公钥、format、charset、签名方式)
4.创建 AlipayTradePagePayRequest,配置notifyUrl并设置Request参数(参数包含订单号、总金额、支付的名称)(格式:JSON格式)
5.通过AlipayClient执行request调用SDK生成表单,用HttpServletResponse(浏览器响应的一个流)写表单的内容,创建一个html的网页)
6.回调接口(Post)先验证交易状态是否成功,获取request里面的信息。支付宝验签(使用的是AlipaySignature(通用SDK提供的类)获取一个String字符串将其与sign签名验证),用 OrderMapper 更新到数据库)退款流程
1.创建Client(由通用SDK提供的Client,负责调用支付宝的API)(参数包含网关地址、appid、密钥、公钥、format、charset、签名方式)
2.创建 AlipayTradePagePayRequest,设置Request参数(参数包含支付宝回调的订单流水号、总金额、我的订单编号)(格式:JSON格式)
3.通过 AlipayClient 执行 request 获取 response,通过isSuccess判断是否成功,成功后更新数据库状态。
@RestController
@RequestMapping("/alipay")
public class AliPayController {private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";private static final String FORMAT = "JSON";private static final String CHARSET = "UTF-8";//签名方式private static final String SIGN_TYPE = "RSA2";@Resourceprivate AlipayConfig aliPayConfig;/*** 支付接口*/@GetMapping("/pay")public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {// 1. 创建Client,通用SDK提供的Client,负责调用支付宝的APIAlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),aliPayConfig.getPrivateKey(), FORMAT, CHARSET, aliPayConfig.getPublicKey(), SIGN_TYPE);// 2. 创建 Request并设置Request参数AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的 Request类request.setNotifyUrl(aliPayConfig.getNotifyUrl());JSONObject bizContent = new JSONObject();bizContent.set("out_trade_no", aliPay.getTraceNo()); // 我们自己生成的订单编号bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额bizContent.set("subject", aliPay.getSubject()); // 支付的名称bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置request.setBizContent(bizContent.toString());// 执行请求,拿到响应的结果,返回给浏览器AlipayTradePagePayResponse response = alipayClient.pageExecute(request);if(response.isSuccess()){//System.out.println("调用成功");log.info("调用成功");String form = response.getBody();httpResponse.setContentType("text/html;charset=" + CHARSET);httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面httpResponse.getWriter().flush();httpResponse.getWriter().close();return form;} else {//System.out.println("调用失败");log.info("调用失败,返回码=====" + response.getCode() + "返回描述=====" + response.getMsg());throw new RuntimeException("调用失败");}}/*** 回调接口*/@PostMapping("/notify") // 必须是POST接口public String payNotify(HttpServletRequest request) throws Exception {if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {System.out.println("=========支付宝异步回调========");Map<String, String> params = new HashMap<>();Map<String, String[]> requestParams = request.getParameterMap();for (String name : requestParams.keySet()) {params.put(name, request.getParameter(name));// System.out.println(name + " = " + request.getParameter(name));}String outTradeNo = params.get("out_trade_no");String gmtPayment = params.get("gmt_payment");String alipayTradeNo = params.get("trade_no");String sign = params.get("sign");String content = AlipaySignature.getSignCheckContentV1(params);boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getPublicKey(), "UTF-8"); // 验证签名 // 支付宝验签 if (checkSignature) {// 验签通过 System.out.println("交易名称: " + params.get("subject"));System.out.println("交易状态: " + params.get("trade_status"));System.out.println("支付宝交易凭证号: " + params.get("trade_no"));System.out.println("商户订单号: " + params.get("out_trade_no"));System.out.println("交易金额: " + params.get("total_amount"));System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));System.out.println("买家付款时间: " + params.get("gmt_payment"));System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));}}return "success";}/*** 退款接口*/@GetMapping("/return")public Result returnPay(AliPay aliPay) throws AlipayApiException {// 7天无理由退款String now = DateUtil.now();Orders orders = ordersMapper.getByNo(aliPay.getTraceNo());if (orders != null) {// hutool工具类,判断时间间隔long between = DateUtil.between(DateUtil.parseDateTime(orders.getPaymentTime()), DateUtil.parseDateTime(now), DateUnit.DAY);if (between > 7) {return Result.error("-1", "该订单已超过7天,不支持退款");}}// 1. 创建Client,通用SDK提供的Client,负责调用支付宝的APIAlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET,aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);// 2. 创建 Request,设置参数AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();JSONObject bizContent = new JSONObject();bizContent.set("trade_no", aliPay.getAlipayTraceNo()); // 支付宝回调的订单流水号bizContent.set("refund_amount", aliPay.getTotalAmount()); // 订单的总金额bizContent.set("out_request_no", aliPay.getTraceNo()); // 我的订单编号// 返回参数选项,按需传入//JSONArray queryOptions = new JSONArray();//queryOptions.add("refund_detail_item_list");//bizContent.put("query_options", queryOptions);request.setBizContent(bizContent.toString());// 3. 执行请求AlipayTradeRefundResponse response = alipayClient.execute(request);if (response.isSuccess()) { // 退款成功,isSuccess 为trueSystem.out.println("调用成功");// 4. 更新数据库状态ordersMapper.updatePayState(aliPay.getTraceNo(), "已退款", now);return Result.success();} else { // 退款失败,isSuccess 为falseSystem.out.println(response.getBody());return Result.error(response.getCode(), response.getBody());}}
}