Spring Boot 接入支付宝,实战来了!
在Spring Boot项目中接入支付宝,通常需要以下几个步骤:
- 创建支付宝商家账号,并获取相关密钥和应用公钥私钥。
- 配置支付宝SDK和相关依赖。
- 编写接口用于发起支付请求。
- 处理支付结果回调。
以下是一个简化的例子,展示如何在Spring Boot项目中发起支付宝当面付:
1. 添加依赖(pom.xml)
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.10.192.ALL</version>
</dependency>
2. 配置支付宝参数(application.properties)
alipay.appId=你的APPID
alipay.privateKey=你的应用私钥
alipay.publicKey=支付宝公钥
alipay.domain=https://openapi.alipay.com
3. 配置AlipayTemplate(AlipayConfig)
@Configuration
public class AlipayConfig {
@Value("${alipay.appId}")
private String appId;
@Value("${alipay.privateKey}")
private String privateKey;
@Value("${alipay.publicKey}")
private String publicKey;
@Value("${alipay.domain}")
private String domain;
@Bean
public AlipayClient alipayClient() throws AlipayApiException {
return new DefaultAlipayClient(domain, appId, privateKey, "json", "utf-8", publicKey, "RSA2");
}
}
4. 发起支付请求的Controller
@RestController
@RequestMapping("/alipay")
public class AlipayController {
@Autowired
private AlipayClient alipayClient;
@PostMapping("/createOrder")
public String createOrder(@RequestParam("orderPrice") double orderPrice) throws AlipayApiException {
// 创建API对应的request
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
// 设置bizModel
AlipayTradePagePayModel model = new AlipayTradePagePayModel();
model.setOutTradeNo(UUID.randomUUID().toString()); // 商户订单号
model.setProductCode("FAST_INSTANT_TRADE_PAY"); // 产品编码
model.setTotalAmount(String.valueOf(orderPrice)); // 订单金额
model.setSubject("你的商品名称"); // 订单标题
model.setBody("你的商品描述"); // 订单描述
alipayRequest.setBizModel(model);
// 发起支付请求
String result = alipayClient.pageExecute(alipayRequest).getBody();
return result; // 返回页面跳转form表单
}
}
5. 支付结果回调的Controller
@RestController
public class AlipayCallbackController {
@Autowired
private AlipayClient alipayClient;
@PostMapping("/alipayCallback")
public String alipayCallback(HttpServletRequest request) throws AlipayApiException {
Map<String, String> params = new HashMap<String, String>();
Map<String, String
评论已关闭