SpringBoot接入支付宝
- (一)、前提工作:
- 1、进入支付宝开发平台—沙箱环境
- 1.1、进入个人沙箱环境
- 1.2、接下来进行几个密钥的生成
- 1.3、拿到两个密钥后,进行自定义密钥配置
- 1.4、至此,我们沙箱环境的配置和基本参数都已经获取到。
- (二)、Java代码-thymeleaf
- 1.导入两个包
- 2.编写两个代码
- 3.控制层代码优化
(一)、前提工作:
1、进入支付宝开发平台—沙箱环境
沙箱环境-支付宝文档中心
1.1、进入个人沙箱环境
参考文档
点击进入沙箱环境并用支付宝登陆
沙箱管理界面如图所示
appid,支付宝网关,自定义密钥等
这里是沙箱支付宝(虚拟)的账号和密码,可以用来支付
1.2、接下来进行几个密钥的生成
点击进入密钥工具
点击生成
这时我们拿到两个密钥,将它们保存,这两个密钥很重要
应用私钥
应用公钥
1.3、拿到两个密钥后,进行自定义密钥配置
进入最开始的沙箱管理界面,点击自定义密钥,点击设置(查看),我们选择的是RSA2密钥
选择“公钥”这一选项
将上一步骤生成的应用公钥填进来,会得到支付宝公钥这另一个密钥,记住并保存这个支付宝公钥
1.4、至此,我们沙箱环境的配置和基本参数都已经获取到。
(二)、Java代码-thymeleaf
1.导入两个包
导入一个包
我用的开发语言是JAVA,工具为IDEA,一个简单的springboot工程
1.构建一个普通的springboot工程,引入支付宝SDK的maven依赖:
<!--支付宝支付接口-->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.0.0</version>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.7.7</version>
</dependency>
2.编写两个代码
新建一个AlipayConfig类,用于配置支付的相关配置:
里面的配置信息,标记是你的就写你的。没标记就照搬
package com.jsxs.config;
import java.io.FileWriter;
import java.io.IOException;
public class AlipayConfig {
// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号,开发时使用沙箱提供的APPID,生产环境改成自己的APPID
public static String APP_ID = "122620920";
// 商户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O0KsNMaL8tv5FuleqDYMpSxfv3pTcEr8Xi74L058WPJe1RY0m9QRNhrMda2LnViZMevgti8k4rbwKBgQCs2EYKni1qt5Qa1b35HD5HPFFkUemYvlaFfJWfgTKxDmmFdJQaeHfu6yN5sO439IisjNMNOA8hUEFjo0LLM2LqDy32PM65O3l7R67roLcjI96Y+mXwU16lPHm5aklaISyfXq6VGlFcnRvnnExm3d562PYy9Z+UQ8HX1mr7bI18+QKBgQDO2bDicEShwtWcnT1Nooa4J0v/LILC1exBSX12OdjVCPkn52x/RmI7nQu/nzfwJB8/Spw5Kh93BGZr4qDMFSfE81L9ApWAtvQpbZ8oz22SRrCxno2rKHO4I2Bh50BtXjtTfO4u9TBIXdV1lr9+ivQCsup6KeslS9+xWsP92n58IQ==\n";
// 支付宝公钥,您的 查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx0R/5SJaYXD9uBTfzbQJvYIh07GHVoeppfndAaoy/HNJrlotxAclJPwLEudVWF3hSXqf1kafXTGfKBCRYTYCoGywm0fQNXH7fZuqYpOu7duKkQJDB+RNxOMWRmU4cemdwIDAQAB\n";
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String notify_url = "https://www.baidu.com";
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问(其实就是支付成功后返回的页面)
public static String return_url = "https://www.baidu.com";
// 签名方式
public static String sign_type = "RSA2";
// 字符编码格式
public static String CHARSET = "utf-8";
// 支付宝网关,这是沙箱的网关(你自己的)
public static String gatewayUrl = "https://openapi.alipaydev.cay.do";
// 支付宝网关
public static String log_path = "C:\\";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
* @param sWord 要写入日志里的文本内容
*/
public static void logResult(String sWord) {
FileWriter writer = null;
try {
writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");
writer.write(sWord);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
新建一个controller包,用于存放Action,新建一个PayController类,编写一个用于支付的接口/pay
package com.jsxs.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jsxs.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class PayController {
@RequestMapping("/pay")
public void payController(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
//设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//付款金额,必填
String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
//订单名称,必填
String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
//商品描述,可空
String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");
alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
+ "\"total_amount\":\"" + total_amount + "\","
+ "\"subject\":\"" + subject + "\","
+ "\"body\":\"" + body + "\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明
//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
// + "\"total_amount\":\""+ total_amount +"\","
// + "\"subject\":\""+ subject +"\","
// + "\"body\":\""+ body +"\","
// + "\"timeout_express\":\"10m\","
// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
//请求
String form = "";
try {
form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
} catch (AlipayApiException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
response.getWriter().write(form);//直接将完整的表单html输出到页面
response.getWriter().flush();
response.getWriter().close();
}
@RequestMapping("/")
public String toTest(){
return "index";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<form action="/pay" method="post">
订单号:<input type="text" name="WIDout_trade_no" required><br/>
订单名称:<input type="text" name="WIDsubject" required><br/>
付款金额:<input type="text" name="WIDtotal_amount" required><br/>
WIDbody:<input type="text" name="WIDbody"><br/>
<input type="submit" value="下单"> <input type="reset" value="重置">
</form>
required保证提交的时候这两项内容非空
5. controller类添加跳转html页面的映射:
@RequestMapping("/")
public String toTest(){
return "index";
}
6.测试运行,启动项目,在浏览器输入:http://localhost:8080/
3.控制层代码优化
package com.jsxs.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jsxs.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Controller
public class PayController {
@RequestMapping("/pay")
public void payController(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
//设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商户订单号,商户网站订单系统中唯一订单号,必填
// 订单号 order
String order = UUID.randomUUID().toString().replaceAll("-", "");
// 付款金额 money
String payMoney="100";
//订单名称
String orderName="江道远火锅店";
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date());
//商品描述
String orderDescription=format+" "+"消费了蔬菜类";
//
String out_trade_no = new String(order.getBytes("ISO-8859-1"), "UTF-8");
//付款金额,必填
String total_amount = new String(payMoney.getBytes("ISO-8859-1"), "UTF-8");
//订单名称,必填
String subject = new String(orderName.getBytes("ISO-8859-1"), "gbk");
//商品描述,可空
String body = new String(orderDescription.getBytes("ISO-8859-1"), "gbk");
alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
+ "\"total_amount\":\"" + total_amount + "\","
+ "\"subject\":\"" + subject + "\","
+ "\"body\":\"" + body + "\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明
//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
// + "\"total_amount\":\""+ total_amount +"\","
// + "\"subject\":\""+ subject +"\","
// + "\"body\":\""+ body +"\","
// + "\"timeout_express\":\"10m\","
// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
//请求
String form = "";
try {
form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
} catch (AlipayApiException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
response.getWriter().write(form);//直接将完整的表单html输出到页面
response.getWriter().flush();
response.getWriter().close();
}
@RequestMapping("/")
public String toTest(){
return "index";
}
}
前端优化
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>阿里云支付操作</title>
</head>
<body>
<form th:action="@{/pay}" method="post">
<input type="submit" value="下单"> <input type="reset" value="重置">
</form>
</body>
</html>