本实现基于 Spring-Boot 与 Maven,所以你需要先 创建一个基于 Maven 的 Spring-Boot 项目 。
本文的 Alipay 实现使用了支付宝沙箱环境,因此您不能直接把本项目直接使用到您的实际项目中。
1. 开启支付宝支付沙箱
- 打开支付宝开放平台并登录,然后点击进入控制台
- 在控制台中页面到找到沙箱并进入
- 在沙箱中找到沙箱应用的 APPID、应用私钥、支付宝公钥(红色箭头指向的地方),后面代码的配置文件需要用到这些值。授权回调地址则用于填写支付成功后支付宝跳转过去的您的落地页。
2. 项目实现支付宝支付
-
参考前面所述,在 application.properties 配置文件中添加以下配置项
# 沙箱应用 APPID alipay.appId=your_sandbox_appid # 应用私钥 alipay.privateKey=your_application_private_key # 支付宝公钥 alipay.publicKey=your_alipay_public_key -
在 pom.xml 中,添加支付宝SDK依赖
<dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>4.35.79.ALL</version> </dependency> -
在主包下(例如 net.chenzhongyi) 新增一个 controller 包(例如 net.chenzhongyi.controller)
-
在 controller 包新增一个 AliController.java,添加代码如下(自行解决包声明和导包)
@Controller @RequestMapping("/ali") public class AliController { @Value("${alipay.appId}") private String appId; @Value("${alipay.privateKey}") private String privateKey; @Value("${alipay.publicKey}") private String publicKey; @RequestMapping(value = "/pay", method = RequestMethod.POST) @ResponseBody public String alipay( @RequestParam("outTradeNo") String outTradeNo, @RequestParam("totalAmount") String totalAmount, @RequestParam("subject") String subject ) throws AlipayApiException { AlipayClient alipayClient = new DefaultAlipayClient("https://openapi-sandbox.dl.alipaydev.com/gateway.do", appId, privateKey, "json", "utf-8", publicKey, "RSA2"); AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); alipayRequest.setReturnUrl("http://localhost:8080/callback"); alipayRequest.setNotifyUrl("http://localhost:8080/notify"); alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"," + "\"total_amount\":\"" + totalAmount + "\"," + "\"subject\":\"" + subject + "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); return alipayClient.pageExecute(alipayRequest).getBody(); } } -
启动 Spring-Boot 项目,然后在浏览器中打开服务地址(例如 http://localhost:8080/)
-
在浏览器当前页面中打开控制台,在控制台中输入并执行以下代码(注意请求端口与服务端口保持一致)
fetch('http://localhost:8080/ali/pay?outTradeNo=123&totalAmount=50.99&subject=知识付费', { method: 'post' }) .then(function (res) { var stream = res.body; return new Response(stream, { headers: { "Content-Type": "text/html" } }).text(); }) .then(function (result) { var win = window.open("", "_blank"); win.document.write(result); }); -
接下来就是体验用户支付的流程:
- 使用沙箱用户账号和支付密码登录(如果您打算使用支付宝APP扫码支付,同样需要使用沙箱用户账号登录支付宝APP)
- 继续使用支付密码确认付款
- 确认支付成功
- 页面自动跳转到回调页面(忽略错误,因为没有实现)
- 再回去查看沙箱账号,便能看到商家的账户余额与买家的账户余额的变化