springboot支付宝沙箱支付详细步骤
支付宝沙箱环境配置
进入支付宝的开放平台——沙箱支付
沙箱环境
进入个人沙箱环境
点击进入沙箱环境并用支付宝登陆
沙箱管理界面如图所示:
appid,支付宝网关,自定义密钥等
沙箱账号界面如图所示:
这里是用来支付的账号和密码
密钥的生成
这时我们拿到两个密钥,将它们保存,这两个密钥很重要
- 应用私钥
- 应用公钥
拿到两个密钥后,进行自定义密钥配置
进入最开始的沙箱管理界面,点击自定义密钥,点击设置并查看,我们选择的是公钥模式
在这里将上一步骤生成的应用公钥填进来
得到支付宝公钥这另一个密钥,记住并保存这个支付宝公钥
至此,我们沙箱环境的配置和基本参数都已经获取到。
spring boot 环境配置
导入支付宝支付的依赖到pom.xml中
<!-- 支付宝依赖沙箱支付 -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-easysdk</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 支付宝相关-->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.34.0.ALL</version>
在 application.yml 里面进行配置
alipay:
appId:
appPrivateKey:
alipayPublicKey:
notifyUrl:
alipay的java配置:AplipayConfig.java
package com.kp.config;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Data
@Component
//读取yml文件中alipay 开头的配置
@ConfigurationProperties(prefix = "alipay")
public class AliPayConfig {
private String appId;
private String appPrivateKey;
private String alipayPublicKey;
private String notifyUrl;
@PostConstruct
public void init() {
// 设置参数(全局只需设置一次)
Config config = new Config();
config.protocol = "https";
config.gatewayHost = "openapi.alipaydev.com";
config.signType = "RSA2";
config.appId = this.appId;
config.merchantPrivateKey = this.appPrivateKey;
config.alipayPublicKey = this.alipayPublicKey;
config.notifyUrl = this.notifyUrl;
Factory.setOptions(config);
System.out.println("=======支付宝SDK初始化成功=======");
}
}
支付接口
新建一个 AliPayController.java
package com.kp.controller;
import com.alipay.easysdk.factory.Factory;
import com.kp.config.AliPayConfig;
import com.kp.entity.AliPay;
import com.kp.entity.Orders;
import com.kp.mapper.OrderMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {
@Resource
AliPayConfig aliPayConfig;
@Resource
private OrderMapper shopOrderMapper;
private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
private static final String FORMAT ="JSON";
private static final String CHARSET ="utf-8";
private static final String SIGN_TYPE ="RSA2";
@GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
request.setNotifyUrl(aliPayConfig.getNotifyUrl());
request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
+ "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
+ "\"subject\":\"" + aliPay.getSubject() + "\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
String form = "";
try {
// 调用SDK生成表单
form = alipayClient.pageExecute(request).getBody();
} catch (AlipayApiException e) {
e.printStackTrace();
}
httpResponse.setContentType("text/html;charset=" + CHARSET);
// 直接将完整的表单html输出到页面
httpResponse.getWriter().write(form);
httpResponse.getWriter().flush();
httpResponse.getWriter().close();
}
@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 tradeNo = params.get("out_trade_no");
String gmtPayment = params.get("gmt_payment");
String alipayTradeNo = params.get("trade_no");
// 支付宝验签
if (Factory.Payment.Common().verifyNotify(params)) {
// 验签通过
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"));
// 更新订单未已支付
Orders order = new Orders();
order.setId(Long.valueOf(tradeNo));
order.setStatus(2);
// order.setCheckoutTime(params.get("gmt_payment"));
shopOrderMapper.updateById(order);
}
}
return "success";
}
}
参数 Alipay.java
package com.kp.entity;
import lombok.Data;
@Data
public class AliPay {
private String traceNo;
private double totalAmount;
private String subject;
private String alipayTraceNo;
}
注意:在拦截器里面加上 忽略alipay接口的配置,这很重要!
重要!前端配置!!
res.data.consignee以及其他两个参数都是下单时候的参数
async goToPaySuccess(){
const params = {
remark:this.note,
payMethod:1,
addressBookId:this.address.id
}
const res = await addOrderApi(params)
console.log('params:', params);
console.log('res:', res);
if(res.code === 1){
window.open(`http://localhost:8090/alipay/pay?subject=${res.data.consignee}&traceNo=${res.data.id}&totalAmount=${res.data.amount}`)
this.$message.success('付款成功')
this.load();
})
}else{
this.$notify({ type:'warning', message:res.msg});
}
},
接口测试
测试的url格式:
http://localhost:9090/alipay/paysubject=xxx&traceNo=xxx&totalAmount=1000
使用沙箱账号登录,支付就可以
回调接口在上面的Controller中配置
内网穿透:https://natapp.cn/
配置免费的隧道,端口:(你的项目端口)
软件下载地址:
内网穿透软件下载
下载好软件后,打开配置下authtoken:
参考这个步骤,把authtoken复制过来
双击启动 natapp.exe即可。
看到这个表示你启动成功了:
idea里面配置notify接口并测试
更改 application.yml 里的配置:
至此,集成完毕!撒花!坑太多了!