首页 > 基础资料 博客日记
2023最新之 教你如何使用Springboot集成支付宝沙箱支付(支持回调- 亲测有效)
2024-05-31 08:00:05基础资料围观294次
文章2023最新之 教你如何使用Springboot集成支付宝沙箱支付(支持回调- 亲测有效)分享给大家,欢迎收藏Java资料网,专注分享技术知识
1、进入支付宝开放平台
https://openhome.alipay.comhttps://openhome.alipay.com
2、进入沙箱
2.1 点击启用公钥
点击查看:
3、Java集成沙箱支付
3.1 在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.22.113.ALL</version>
</dependency>
3.2 在 application.yml 文件中配置
alipay:
appId:
appPrivateKey:
alipayPublicKey:
notifyUrl:
3.3 alipay的java配置:AplipayConfig.java
package com.shijiu.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;
/**
* @Author
* @Date Created in 2023/5/5 15:06
* @DESCRIPTION:
* @Version V1.0
*/
@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初始化成功=======");
}
}
3.4 **注意:在拦截器里面加上 忽略alipay接口的配置,这很重要!**
3.5 新建一个AliPayController.java
package com.shijiu.controller;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.shijiu.common.Result;
import com.shijiu.config.AliPayConfig;
import com.shijiu.dao.mapper.ShopOrderMapper;
import com.shijiu.pojo.AliPay;
import com.shijiu.pojo.ShopOrder;
import org.joda.time.DateTime;
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 java.net.URLEncoder;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Author
* @Date Created in 2023/5/5 15:23
* @DESCRIPTION:
* @Version V1.0
*/
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {
@Resource
AliPayConfig aliPayConfig;
@Resource
private ShopOrderMapper shopOrderMapper;
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";
@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"));
// 更新订单未已支付
ShopOrder order = new ShopOrder();
order.setId(tradeNo);
order.setStatus("1");
Date payTime = DateUtil.parse(gmtPayment, "yyyy-MM-dd HH:mm:ss");
order.setZhhifuTime(payTime);
shopOrderMapper.updateById(order);
}
}
return "success";
}
}
3.6 新建 AliPay.java 参数
package com.shijiu.pojo;
import lombok.Data;
/**
* @Author
* @Date Created in 2023/5/5 15:26
* @DESCRIPTION:
* @Version V1.0
*/
@Data
public class AliPay {
private String traceNo;
private double totalAmount;
private String subject;
private String alipayTraceNo;
}
前端vue 代码:(重点)
handleEdit(row) {
this.$confirm('确认支付?, 是否继续?', '删除打卡信息?', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
window.open(`http://localhost:8888/alipay/pay?subject=${row.orderName}&traceNo=${row.id}&totalAmount=${row.prince}`)
this.$message.success('付款成功')
this.load()
}).catch(() => {
this.$message({
type: 'info',
message: '已取消付款'
})
this.load()
})
},
3.7 接口测试
然后我们访问URL进行测试,测试的url格式:
http://localhost:8888/alipay/pay?subject=测试商品&traceNo= 666&totalAmount=1000
3.8 内网穿透:https://natapp.cn/
配置免费的隧道,端口:8888:(你项目中的地址端口号)
3.9 新建文本文档 (启动内网穿透工具):
内容为下列内容。修改格式为 .bat
每次启动回调地址都不同!!!
3.10 回调地址:(如果一次不行,就多重新启动start.bat ,并更新yml文件中的回调地址)
触发回调函数:
看下方的:
3.11 支付结果:(示例:227)
已支付
学习来源:
文章来源:https://blog.csdn.net/XikYu/article/details/130273107
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: