Java 接入支付宝网页支付(SpringBoot + IDEA + 内网穿透 + 沙箱配置 )
一、支付宝沙箱环境配置
首先登陆支付宝开放平台官网(前蚂蚁金服开放平台),登陆并填写相关信息后点击页面最下方提交入驻申请

提交申请后进入如下页面并点击开发者中心

然后进入如下页面并点击研发服务

这里要简单提一下对称加密和非对称加密
- 对称加密即通过一个密匙来加密和解密,常见的如MD5加密,这样就会存在一定安全问题
- 非对称加密即存在一个公钥和私钥,它们是成对存在的,公钥进行加密,私钥进行解密,支付宝支付即采用的非对称加密,简单示意图如下

支付宝也需要设置秘钥,如下图所示,点击设置

然后弹出如下窗口,选择公钥并生成公钥

点击支付宝秘钥生成器跳转到如下页面,并选择自己电脑对应的系统下载生成器

下载安装并运行即可生成秘钥

将公钥复制到我们刚刚的弹框并保存

保存后我们会看到多了一个支付宝公钥,也就是在创建应用公钥的同时支付宝也会对应生成公钥和私钥,如下所示

接下来我们要设置应用网关和支付宝网关一直即可(支付宝网关在页面最上方),复制粘贴保存即可,如下图所示

二、支付宝沙箱应用下载并登录
在沙箱账号一栏,我们可以看到两个账号,分别是商家账号和卖家账号,用于模拟真实支付场景,即从卖家账户扣钱转入商家账户

接下来用手机下载沙箱版钱包,点击后用手机扫描二维码即可下载安装

三、内网穿透
由于我们的机器是可以访问到支付宝的服务器的,但支付宝不能访问我们的机器,因为我们的电脑相当于内网,因此,我们还需要进行一次内网穿透操作,免费的内网穿透服务可选ngrok
- 访问www.ngrok.cc,注册并登录
- 登录后进入如下页面选择开通隧道,然后购买免费服务器,如下图


添加成功后如下图所示

- 返回首页下载客户端

选择自己电脑对应的系统下载

下载并解压得到如下文件夹

进入如下目录启动.bat文件

- 启动客户端如下所示

这里需要我们输入客户端id,也就是我们的隧道id

将隧道id复制粘贴并回车即可,如下图即表示该域名映射到了本地的127.0.0.1:80端口

四、下载官方Demo
首先在沙箱应用中选择电脑网站支付

然后选择如下图所示下载

下载并解压后如下图所示,这是一个web项目

将该项目导入到IDEA中,然后打开打开AlipayConfig类,我们需要使用到这里的配置信息,下图红色框选中的部分为我们需要修改部分,异步通知和同步通知可自定义逻辑功能

五、SpringBoot项目构建接入支付宝支付
先创建一个新的SpringBoot项目(此步骤省略),项目完整结构如下

导入Maven依赖如下
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alipay.sdk/alipay-sdk-java -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.7.110.ALL</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.33</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
首先根据官方Demo修改为alipay.properties如下
#应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
app_id = 2016101800712368
#商户私钥,您的PKCS8格式RSA2私钥
merchant_private_key = xxx
#支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
alipay_public_key = xxx
#服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
notify_url = http://ranran.free.idcfengye.com/alipay/static/notify_url.jsp
#页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
return_url = http://ranran.free.idcfengye.com/alipay/static/return_url.jsp
#签名方式
sign_type = RSA2
#字符编码格
charset = utf-8
#支付宝网关
gatewayUrl = https://openapi.alipaydev.com/gateway.do
# 支付宝网关
log_path = "C:\\"
创建实体类如下
import lombok.Data;
import lombok.experimental.Accessors;
/*支付实体对象*/
@Data
@Accessors(chain = true)
public class AlipayBean {
/*商户订单号,必填*/
private String out_trade_no;
/*订单名称,必填*/
private String subject;
/*付款金额,必填*/
private StringBuffer total_amount;
/*商品描述,可空*/
private String body;
/*超时时间参数*/
private String timeout_express = "10m";
private String product_code = "FAST_INSTANT_TRADE_PAY";
}
创建service接口如下
import com.alipay.api.AlipayApiException;
import com.ranran.alipay.pojo.AlipayBean;
public interface PayService {
String aliPay(AlipayBean alipayBean) throws AlipayApiException;
}
创建service实体类如下
import com.alipay.api.AlipayApiException;
import com.ranran.alipay.config.AlipayUtil;
import com.ranran.alipay.pojo.AlipayBean;
import org.springframework.stereotype.Service;
@Service(value = "alipayOrderService")
public class PayServiceImpl implements PayService {
@Override
public String aliPay(AlipayBean alipayBean) throws AlipayApiException {
return AlipayUtil.connect(alipayBean);
}
}
创建controller类如下
import com.alipay.api.AlipayApiException;
import com.ranran.alipay.pojo.AlipayBean;
import com.ranran.alipay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/* 订单接口 */
@RestController()
@RequestMapping("/order")
public class OrderController {
@Autowired
private PayService payService;//调用支付服务
/*阿里支付*/
@PostMapping(value = "alipay")
public String alipay(String out_trade_no, String subject, String total_amount, String body) throws AlipayApiException {
return payService.aliPay(new AlipayBean()
.setBody(body)
.setOut_trade_no(out_trade_no)
.setTotal_amount(new StringBuffer().append(total_amount))
.setSubject(subject));
}
}
创建支付工具类如下(从官方Demo提取)
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ranran.alipay.pojo.AlipayBean;
public class AlipayUtil {
public static String connect(AlipayBean alipayBean) throws AlipayApiException {
//1、获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(
PropertiesConfig.getKey("gatewayUrl"),//支付宝网关
PropertiesConfig.getKey("app_id"),//appid
PropertiesConfig.getKey("merchant_private_key"),//商户私钥
"json",
PropertiesConfig.getKey("charset"),//字符编码格式
PropertiesConfig.getKey("alipay_public_key"),//支付宝公钥
PropertiesConfig.getKey("sign_type")//签名方式
);
//2、设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//页面跳转同步通知页面路径
alipayRequest.setReturnUrl(PropertiesConfig.getKey("return_url"));
// 服务器异步通知页面路径
alipayRequest.setNotifyUrl(PropertiesConfig.getKey("notify_url"));
//封装参数
alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//3、请求支付宝进行付款,并获取支付结果
String result = alipayClient.pageExecute(alipayRequest).getBody();
//返回付款信息
return result;
}
}
创建配置类读取配置如下
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/* 应用启动加载文件*/
@Component
public class PropertiesConfig implements ApplicationListener {
//保存加载配置参数
private static Map<String, String> aliPropertiesMap = new HashMap<String, String>();
//获取配置参数值
public static String getKey(String key) {
return aliPropertiesMap.get(key);
}
//监听启动完成,执行配置加载到aliPropertiesMap
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationReadyEvent) {
this.init(aliPropertiesMap);//应用启动加载
}
}
//初始化加载aliPropertiesMap
public void init(Map<String, String> map) {
// 获得PathMatchingResourcePatternResolver对象
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//加载resource文件(也可以加载resources)
Resource resources = resolver.getResource("classpath:config/alipay.properties");
PropertiesFactoryBean config = new PropertiesFactoryBean();
config.setLocation(resources);
config.afterPropertiesSet();
Properties prop = config.getObject();
//循环遍历所有得键值对并且存入集合
for (String key : prop.stringPropertyNames()) {
map.put(key, (String) prop.get(key));
}
} catch (Exception e) {
new Exception("配置文件加载失败");
}
}
}
支付首页如下(根据官方Demo修改,注意表单提交路径)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>支付宝电脑网站支付</title>
<style>
* {
margin: 0;
padding: 0;
}
ul, ol {
list-style: none;
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
}
.tab-head {
margin-left: 120px;
margin-bottom: 10px;
}
.tab-content {
clear: left;
display: none;
}
h2 {
border-bottom: solid #02aaf1 2px;
width: 200px;
height: 25px;
margin: 0;
float: left;
text-align: center;
font-size: 16px;
}
.selected {
color: #FFFFFF;
background-color: #02aaf1;
}
.show {
clear: left;
display: block;
}
.hidden {
display: none;
}
.new-btn-login-sp {
padding: 1px;
display: inline-block;
width: 75%;
}
.new-btn-login {
background-color: #02aaf1;
color: #FFFFFF;
font-weight: bold;
border: none;
width: 100%;
height: 30px;
border-radius: 5px;
font-size: 16px;
}
#main {
width: 100%;
margin: 0 auto;
font-size: 14px;
}
.red-star {
color: #f00;
width: 10px;
display: inline-block;
}
.null-star {
color: #fff;
}
.content {
margin-top: 5px;
}
.content dt {
width: 100px;
display: inline-block;
float: left;
margin-left: 20px;
color: #666;
font-size: 13px;
margin-top: 8px;
}
.content dd {
margin-left: 120px;
margin-bottom: 5px;
}
.content dd input {
width: 85%;
height: 28px;
border: 0;
-webkit-border-radius: 0;
-webkit-appearance: none;
}
#foot {
margin-top: 10px;
position: absolute;
bottom: 15px;
width: 100%;
}
.foot-ul {
width: 100%;
}
.foot-ul li {
width: 100%;
text-align: center;
color: #666;
}
.note-help {
color: #999999;
font-size: 12px;
line-height: 130%;
margin-top: 5px;
width: 100%;
display: block;
}
#btn-dd {
margin: 20px;
text-align: center;
}
.foot-ul {
width: 100%;
}
.one_line {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #eeeeee;
width: 100%;
margin-left: 20px;
}
.am-header {
display: -webkit-box;
display: -ms-flexbox;
display: box;
width: 100%;
position: relative;
padding: 7px 0;
-webkit-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
background: #1D222D;
height: 50px;
text-align: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
box-pack: center;
-webkit-box-align: center;
-ms-flex-align: center;
box-align: center;
}
.am-header h1 {
-webkit-box-flex: 1;
-ms-flex: 1;
box-flex: 1;
line-height: 18px;
text-align: center;
font-size: 18px;
font-weight: 300;
color: #fff;
}
</style>
</head>
<body text=#000000 bgColor="#ffffff" leftMargin=0 topMargin=4>
<header class="am-header">
<h1>支付宝电脑网站支付体验入口页</h1>
</header>
<div id="main">
<div id="tabhead" class="tab-head">
<h2 id="tab1" class="selected" name="tab">付 款</h2>
<h2 id="tab2" name="tab">交 易 查 询</h2>
<h2 id="tab3" name="tab">退 款</h2>
<h2 id="tab4" name="tab">退 款 查 询</h2>
<h2 id="tab5" name="tab">交 易 关 闭</h2>
</div>
<form name=alipayment action="/order/alipay" method=post
target="_blank">
<div id="body1" class="show" name="divcontent">
<dl class="content">
<dt>商户订单号 :</dt>
<dd>
<input id="WIDout_trade_no" name="out_trade_no" />
</dd>
<hr class="one_line">
<dt>订单名称 :</dt>
<dd>
<input id="WIDsubject" name="subject" />
</dd>
<hr class="one_line">
<dt>付款金额 :</dt>
<dd>
<input id="WIDtotal_amount" name="total_amount" />
</dd>
<hr class="one_line">
<dt>商品描述:</dt>
<dd>
<input id="WIDbody" name="body" />
</dd>
<hr class="one_line">
<dt></dt>
<dd id="btn-dd">
<span class="new-btn-login-sp">
<button class="new-btn-login" type="submit"
style="text-align: center;">付 款</button>
</span> <span class="note-help">如果您点击“付款”按钮,即表示您同意该次的执行操作。</span>
</dd>
</dl>
</div>
</form>
<div id="foot">
<ul class="foot-ul">
<li>支付宝版权所有 2015-2018 ALIPAY.COM</li>
</ul>
</div>
</div>
</body>
<script language="javascript">
var tabs = document.getElementsByName('tab');
var contents = document.getElementsByName('divcontent');
(function changeTab(tab) {
for(var i = 0, len = tabs.length; i < len; i++) {
tabs[i].onmouseover = showTab;
}
})();
function showTab() {
for(var i = 0, len = tabs.length; i < len; i++) {
if(tabs[i] === this) {
tabs[i].className = 'selected';
contents[i].className = 'show';
} else {
tabs[i].className = '';
contents[i].className = 'tab-content';
}
}
}
function GetDateNow() {
var vNow = new Date();
var sNow = "";
sNow += String(vNow.getFullYear());
sNow += String(vNow.getMonth() + 1);
sNow += String(vNow.getDate());
sNow += String(vNow.getHours());
sNow += String(vNow.getMinutes());
sNow += String(vNow.getSeconds());
sNow += String(vNow.getMilliseconds());
document.getElementById("WIDout_trade_no").value = sNow;
document.getElementById("WIDsubject").value = "测试";
document.getElementById("WIDtotal_amount").value = "0.01";
}
GetDateNow();
</script>
</html>
至此即完成了支付宝网页支付
下面测试演示,启动SpringBoot项目,访问localhost:80端口(注意需配置服务端口号为80端口,因为我们为80端口做了内网穿透)

点击付款

使用沙箱版支付宝扫码或登录支付即可

更多推荐


所有评论(0)