SpringBoot实现支付宝沙箱支付

1.支付页面

<!-- 个人中心 -->
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<title>新闻资讯</title>
		<link rel="stylesheet" href="../../layui/css/layui.css">
		<!-- 样式 -->
		<link rel="stylesheet" href="../../css/style.css" />
		<!-- 主题(主要颜色设置) -->
		<link rel="stylesheet" href="../../css/theme.css" />
		<!-- 通用的css -->
		<link rel="stylesheet" href="../../css/common.css" />
	</head>
	<body>

		<div id="app">
			<!-- 轮播图 -->
			<div class="layui-carousel" id="swiper">
				<div carousel-item id="swiper-item">
					<div v-for="(item,index) in swiperList" v-bind:key="index">
						<img class="swiper-item" :src="item.img">
					</div>
				</div>
			</div>
			<!-- 轮播图 -->

			<!-- 标题 -->
			<h2 style="margin-top: 20px;" class="index-title">CONFIRM / ORDER</h2>
			<div class="line-container">
				<p class="line"> 确认下单 </p>
			</div>
			<!-- 标题 -->

			<div class="container">
				<h2 v-if="seat!=1">选择收货地址</h2>
				<table v-if="seat!=1" class="layui-table address-table" lay-skin="nob">
					<!-- <colgroup>
				    <col width="150">
				    <col width="200">
				    <col>
				  </colgroup> -->
					<thead>
						<tr>
							<th>选择</th>
							<th>收件人</th>
							<th>联系方式</th>
							<th>地址</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(item,index) in addressList" v-bind:key="index">
							<td v-if="item.isdefault=='是'"><input type="radio" checked="checked" :value="index" name="address" /></td>
							<td v-if="item.isdefault!='是'"><input type="radio" :value="index" name="address" /></td>
							<td>{{item.name}} </td>
							<td>{{item.phone}}</td>
							<td>{{item.address}}</td>
						</tr>
					</tbody>
				</table>
				<h2>清单列表</h2>
				<table class="layui-table" lay-skin="nob" style="border: 3px dotted #EEEEEE;margin: 20px 0;">
					<thead>
						<tr>
							<th>购买商品</th>
							<th>价格</th>
							<th v-if="seat==1">座位</th>
							<th v-else>数量</th>
							<th>总价</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(item,index) in dataList" v-bind:key="index">
							<td style="display: flex;text-align: left;">
								<img :src="baseurl+item.picture" style="width: 100px;height: 100px;object-fit: cover;">
								<div style="margin-left: 10px;margin-top: 10px;">
									{{item.goodname}}
								</div>
							</td>
							<td v-if="type==2" style="width: 100px;">{{item.price}} 积分</td>
							<td v-else style="width: 100px;"><span :style='{"fontSize":"12px"}'></span>{{Number(item.price).toFixed(2)}}</td>
							<td v-if="seat==1" style="width: 140px;">
								{{item.activeSeat}}
							</td>
							<td  v-else style="width: 140px;">
								{{item.buynumber}}
							</td>
							<td v-if="type==2" style="width: 100px;">{{item.price*item.buynumber}} 积分</td>
							<td v-else-if="seat==1"  style="width: 100px;"><span :style='{"fontSize":"12px"}'></span>{{Number(item.total).toFixed(2)}}</td>
							<td v-else  style="width: 100px;"><span :style='{"fontSize":"12px"}'></span>{{Number((item.price*item.buynumber)).toFixed(2)}}</td>
						</tr>
					</tbody>
				</table>

				<div v-if="seat==1" class="btn-container">
					<span style="font-size: 18px;font-weight: bold;color: #ce0b07;margin-right: 20px;">
						总价:<span :style='{"fontSize":"12px"}'></span>{{Number(dataList[0].total).toFixed(2)}}
					</span>
					<button @click="xuanzuoClick()" type="button" class="layui-btn layui-btn-lg btn-theme">
						<i class="layui-icon">&#xe657;</i> 余额支付
					</button>
					<button @click="xuanzuoAlipayClick()" type="button" class="layui-btn layui-btn-lg btn-theme">
						沙箱支付
					</button>
				</div>
				<div v-else-if="type==2" class="btn-container">
					<span style="font-size: 18px;font-weight: bold;color: #ce0b07;margin-right: 20px;">
						总价:{{totalPrice}}积分
					</span>
					<button @click="jfClick()" type="button" class="layui-btn layui-btn-lg btn-theme">
						<i class="layui-icon">&#xe657;</i> 兑换
					</button>
				</div>
				<div v-else class="btn-container">
					<span style="font-size: 18px;font-weight: bold;color: #ce0b07;margin-right: 20px;">
						总价:<span :style='{"fontSize":"12px"}'></span>{{Number(totalPrice).toFixed(2)}}
					</span>
					<button @click="payClick()" type="button" class="layui-btn layui-btn-lg btn-theme">
						<i class="layui-icon">&#xe657;</i> 余额支付
					</button>
					<button @click="alipayClick()" type="button" class="layui-btn layui-btn-lg btn-theme">
						沙箱支付
					</button>
				</div>
			</div>

		</div>

		<!-- layui -->
		<script src="../../layui/layui.js"></script>
		<!-- vue -->
		<script src="../../js/vue.js"></script>
		<!-- 组件配置信息 -->
		<script src="../../js/config.js"></script>
		<!-- 扩展插件配置信息 -->
		<script src="../../modules/config.js"></script>
		<!-- 工具方法 -->
		<script src="../../js/utils.js"></script>
		<!-- 校验格式工具类 -->
		<script src="../../js/validate.js"></script>

		<script>
			var vue = new Vue({
				el: '#app',
				data: {
					// 轮播图
					swiperList: [{
						img: '../../img/banner.jpg'
					}],
					dataList: [],
					baseurl: '',
					addressList: [],
					seat: 0,
					type: 0,
					// 当前用户信息
					user: {}
				},
				computed: {
					totalPrice: function() {
						var total = 0;
						for (var item of this.dataList) {
							total += item.price * item.buynumber
						}
						return total;
					}
				},
				methods: {
					jump(url) {
						jump(url)
					},
					// 正常下单,生成订单,减少余额,添加积分,减少库存,修改状态已支付
					payClick() {
						console.log('payClick')
						var index = layui.jquery('input[name=address]:checked').val();
						console.log(index);
						if (!index) {
							layui.layer.msg('请选择收货地址', {
								time: 2000,
								icon: 5
							});
							return
						}

						// 生成订单
						for (let item of this.dataList) {
							
							// 获取商品详情信息
							layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
								// 订单编号
								var orderId = genTradeNo();
								let data = res.data;
								// 减少库存
								data.alllimittimes = data.alllimittimes - item.buynumber;
								// 更新库存信息
								layui.http.requestJson(`${item.tablename}/update`, 'post', data, (res) => {
									// 添加订单信息
									let order = {
										orderid: orderId,
										tablename: item.tablename,
										userid: this.user.id,
										goodid: item.goodid,
										goodname: item.goodname,
                                        shangjiazhanghao: item.shangjiazhanghao,
										picture: item.picture,
										buynumber: item.buynumber,
										discountprice: item.price,
										price: item.price,
										total: item.price * item.buynumber,
										discounttotal: item.price * item.buynumber,
										type: 1,
										//total: this.totalPrice,
										address: this.addressList[index].address,
										tel: this.addressList[index].phone,
										consignee: this.addressList[index].name,
										status: '未支付'
									}
									layui.http.requestJson(`orders/add`, 'post', order, (res) => {
										// 减少余额,更新订单状态
                                        // 判断余额是否充足
                                        if (this.user.money < Number(item.price * item.buynumber)) {
                                            layui.layer.msg('余额不足,请先充值', {
                                                time: 2000,
                                                icon: 5
                                            });
                                            return
                                        }
										// 如果该商品存在积分
										if (data.jf) {
											this.user.jf = Number(this.user.jf) + Number(item.price * item.buynumber);
										}
										this.user.money = this.user.money - item.price * item.buynumber;
										// 更新用户余额
										layui.http.requestJson(`${localStorage.getItem("userTable")}/update`, 'post', this.user, (res) => {
											order.status = '已支付'
											layui.http.request(`orders/list`, 'get', {
												orderid: orderId,
												page: 1,
												limit: 1,
											}, (res) => {
												order.id = res.data.list[0].id;
												layui.http.requestJson(`orders/update`, 'post', order, (res) => {
													// 删除购物车数据(如果是购物车下单)
													if (item.id) {
														layui.http.requestJson(`cart/delete`, 'post', [item.id], (res) => {});
													}
													layui.layer.msg('购买成功', {
														time: 2000,
														icon: 6
													}, function() {
														window.location.href='../shop-order/list.html'
													});
												});
											});
										});
									})
								})
							});
						}
					},
					alipayClick() {
						var index = layui.jquery('input[name=address]:checked').val();
						if (!index) {
							layui.layer.msg('请选择收货地址', {
								time: 2000,
								icon: 5
							});
							return
						}

						// 生成订单
						for (let item of this.dataList) {
							
							// 获取商品详情信息
							layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
								// 订单编号
								var orderId = genTradeNo();
								let data = res.data;
								// 减少库存
								data.alllimittimes = data.alllimittimes - item.buynumber;
								// 更新库存信息
								layui.http.requestJson(`${item.tablename}/update`, 'post', data, (res) => {
									// 添加订单信息
									let order = {
										orderid: orderId,
										tablename: item.tablename,
										userid: this.user.id,
										goodid: item.goodid,
										goodname: item.goodname,
                                        shangjiazhanghao: item.shangjiazhanghao,
										picture: item.picture,
										buynumber: item.buynumber,
										discountprice: item.price,
										price: item.price,
										total: item.price * item.buynumber,
										discounttotal: item.price * item.buynumber,
										type: 1,
										//total: this.totalPrice,
										address: this.addressList[index].address,
										tel: this.addressList[index].phone,
										consignee: this.addressList[index].name,
										status: '未支付'
									}
                                    layui.http.requestJson(`orders/add`, 'post', order, (res) => {
                                        layui.http.request(`orders/alipay`, 'get',{"tradeno":order.orderid,"totalamount":order.total,"subject":order.goodname}, (res) => {
                                            if(res.code == 0){
                                                var newWin = window.open('_blank');
                                                newWin.document.querySelector('body').innerHTML = res.data;
                                                const div = document.createElement('div') // 创建div
                                                div.innerHTML = res.data // 将返回的form 放入div
                                                newWin.document.body.appendChild(div)
                                                newWin.document.forms[0].submit()
                                            }
                                        });
                                    })
								})
							});
						}
					},
					// 积分兑换,生成订单,减少用户积分,减少库存
					jfClick() {
						var index = layui.jquery('input[name=address]:checked').val();
						console.log(index);
						if (!index) {
							layui.layer.msg('请选择收货地址', {
								time: 2000,
								icon: 5
							});
							return
						}

						// 生成订单
						for (let item of this.dataList) {
							// 订单编号
							var orderId = genTradeNo();
							layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
								let data = res.data;
								// 减少库存
								data.alllimittimes = data.alllimittimes - item.buynumber;
								// 更新库存信息
								layui.http.requestJson(`${item.tablename}/update`, 'post', data, (res) => {
									// 判断积分是否充足
									if (this.user.jf < this.totalPrice) {
										layui.layer.msg('积分不足,兑换失败', {
											time: 2000,
											icon: 5
										});
										return
									}
									// 添加订单信息
									let order = {
										orderid: orderId,
										tablename: item.tablename,
										userid: this.user.id,
										goodid: item.goodid,
										goodname: item.goodname,
                                        shangjiazhanghao: item.shangjiazhanghao,
										picture: item.picture,
										buynumber: item.buynumber,
										discountprice: item.price,
										price: item.price,
										total: item.price * item.buynumber,
										discounttotal: item.price * item.buynumber,
										type: 2,
										total: this.totalPrice,
										address: this.addressList[index].address,
										tel: this.addressList[index].phone,
										consignee: this.addressList[index].name,
										status: '已支付'
									}
									layui.http.requestJson(`orders/add`, 'post', order, (res) => {
										this.user.jf = this.user.jf - item.price * item.buynumber;
										// 更新用户余额
										layui.http.requestJson(`${localStorage.getItem("userTable")}/update`, 'post', this.user, (res) => {
											layui.layer.msg('兑换成功', {
												time: 2000,
												icon: 6
											}, function() {
												window.location.href='../shop-order/list.html'
											});
										});
									})
								})
							});
						}
					},
					// 选座下单,生成订单,减少余额,添加积分,减少库存,修改状态为已支付
					xuanzuoClick() {
						console.log('xuanzuoClick')
						// 生成订单
						for (let item of this.dataList) {
							// 订单编号
							var orderId = genTradeNo();
							// 获取商品详情信息
							layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
								let data = res.data;
								// 减少库存
								data.alllimittimes = data.alllimittimes - item.buynumber;
								// 获取已经被预定的座位号
                                let selectArray = data.selected?data.selected.split(','):[];
								// 获取用户预定的座位号
								let activeArray = item.address.split(',');
								// 新的预定座位号
								let newSelectArray = selectArray.concat(activeArray);
								// 赋值给参数
								data.selected = newSelectArray.join(',');
								// 更新库存,座位信息
								layui.http.requestJson(`${item.tablename}/update`, 'post', data, (res) => {
									// 添加订单信息
									let order = {
										orderid: orderId,
										tablename: item.tablename,
										userid: this.user.id,
										goodid: item.goodid,
										goodname: item.goodname,
                                        shangjiazhanghao: item.shangjiazhanghao,
										picture: item.picture,
										buynumber: item.buynumber,
										discountprice: item.price,
										price: item.price,
										total: item.total,
										discounttotal: item.total,
										type: 1,
										address: item.address,
										status: '未支付'
									}
									layui.http.requestJson(`orders/add`, 'post', order, (res) => {
										// 减少余额,更新订单状态
                                        // 判断余额是否充足
                                        if (this.user.money < Number(item.price * item.buynumber)) {
                                            layui.layer.msg('余额不足,请先充值', {
                                                time: 2000,
                                                icon: 5
                                            });
                                            return
                                        }
										// 如果该商品存在积分
										if (data.jf) {
											this.user.jf = Number(this.user.jf) + Number(data.jf * item.buynumber);
										}
										this.user.money = this.user.money - item.price * item.buynumber;
										// 更新用户余额
										layui.http.requestJson(`${localStorage.getItem("userTable")}/update`, 'post', this.user, (res) => {
											order.status = '已支付'
											layui.http.request(`orders/list`, 'get', {
												orderid: orderId,
												page: 1,
												limit: 1,
											}, (res) => {
												order.id = res.data.list[0].id;
												layui.http.requestJson(`orders/update`, 'post', order, (res) => {
													layui.layer.msg('购买成功', {
														time: 2000,
														icon: 6
													}, function() {
														window.location.href='../shop-order/list.html'
													});
												});
											});
										});
									})
								})
							});
						}
					},
                    **//选座沙箱支付
					xuanzuoAlipayClick() {
						// 生成订单
						for (let item of this.dataList) {
							// 订单编号
							var orderId = genTradeNo();
							// 获取商品详情信息
							layui.http.request(`${item.tablename}/info/${item.goodid}`, 'get', {}, (res) => {
								let data = res.data;
								// 减少库存
								data.alllimittimes = data.alllimittimes - item.buynumber;
								// 获取已经被预定的座位号
                                let selectArray = data.selected?data.selected.split(','):[];
								// 获取用户预定的座位号
								let activeArray = item.address.split(',');
								// 新的预定座位号
								let newSelectArray = selectArray.concat(activeArray);
								// 赋值给参数
								data.selected = newSelectArray.join(',');
								// 更新库存,座位信息
								layui.http.requestJson(`${item.tablename}/update`, 'post', data, (res) => {
									// 添加订单信息
									let order = {
										orderid: orderId,
										tablename: item.tablename,
										userid: this.user.id,
										goodid: item.goodid,
										goodname: item.goodname,
                                        shangjiazhanghao: item.shangjiazhanghao,
										picture: item.picture,
										buynumber: item.buynumber,
										discountprice: item.price,
										price: item.price,
										total: item.total,
										discounttotal: item.total,
										type: 1,
										address: item.address,
										status: '未支付'
									}
                                    layui.http.requestJson(`orders/add`, 'post', order, (res) => {
                                        layui.http.request(`orders/alipay`, 'get',{"tradeno":order.orderid,"totalamount":order.total,"subject":order.goodname}, (res) => {
                                            if(res.code == 0){
                                                var newWin = window.open('_blank');
                                                newWin.document.querySelector('body').innerHTML = res.data;
                                                const div = document.createElement('div') // 创建div
                                                div.innerHTML = res.data // 将返回的form 放入div
                                                newWin.document.body.appendChild(div)
                                                newWin.document.forms[0].submit()
                                            }
                                        });
                                    })
								})
							});
						}
					},
				}
			})**

			layui.use(['layer', 'element', 'carousel', 'http', 'jquery', 'form', 'upload'], function() {
				var layer = layui.layer;
				var element = layui.element;
				var carousel = layui.carousel;
				var http = layui.http;
				var jquery = layui.jquery;
				var form = layui.form;
				var upload = layui.upload;
				vue.baseurl = http.baseurl;

				// 订单类型,2则是积分兑换,其他是正常下单
				vue.type = http.getParam('type');
				// 订单类型,seat存在值则是选座下单,否则是其他类型
				vue.seat = http.getParam('seat');

				// 充值
				jquery('#btn-recharge').click(function(e) {
					layer.open({
						type: 2,
						title: '用户充值',
						area: ['900px', '600px'],
						content: '../shop-recharge/recharge.html'
					});
				});

				// 获取轮播图 数据
				http.request('config/list', 'get', {
					page: 1,
					limit: 5
				}, function(res) {
					if (res.data.list.length > 0) {
						var swiperItemHtml = '';
						for (let item of res.data.list) {
							if (item.name.indexOf('picture') >= 0 && item.value && item.value != "" && item.value != null) {
								swiperItemHtml +=
									'
' + '<img class="swiper-item" src="' + http.baseurl+item.value + '">' + '
'
; } } jquery('#swiper-item').html(swiperItemHtml); // 轮播图 carousel.render({ elem: '#swiper', width: swiper.width,height:swiper.height, arrow: swiper.arrow, anim: swiper.anim, interval: swiper.interval, indicator: "none" }); } }); // 获取地址数据 http.request('address/page', 'get', { userid: localStorage.getItem('userid') }, function(res) { vue.addressList = res.data.list }) // 获取商品购买的清单列表 var orderGoods = localStorage.getItem('orderGoods') // 转换成json类型,localstorage保存的是string数据 vue.dataList = JSON.parse(orderGoods); // 用户当前用户信息 let table = localStorage.getItem("userTable"); http.request(`${table}/session`, 'get', {}, function(data) { vue.user = data.data; }); }); </script> </body> </html>

2.后台接口

public class AlipayConfig {
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
	// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
	public static String app_id = "2016092600599799";
	
	// 商户私钥,您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCBP/DL/HPTRdL2dOxKO+1UnxjDr/d6CllRDsQ65ws/RYR2h0Qufgccm/2OxmIkh9HJkc6dW6XL+El3+nWQbtoqWsN+9r1CW714HiTHo4cDzlOYT/3TfM11yLImN3ByCDQvE7wfOQ/gqUmS+XEeo9CvtS+pap5YYYRX3c2Uin3qO1/rWDO670wykq7KmULCvWrf2A8SJT5eRj9OtM76X/LvCrFs4hdqnME7eCq5dUm382K/Yra3d2BB/oS6fSG9JqZr7idU5C9uCpnOiO+c/JjO8lq2SXzVppCUkmcFh9kMz3oKTaeg8/xX6dHyKnD5ojCb13buTbX7NiUTgZ9EvdzXAgMBAAECggEAKVguytHCqz6WsUfNniF1VbBe15oea+eLkqZKlxz5OBAgw1mZsdWWqMwtW9KR6mWX8ga2NRfv/UM7HSn9GWqcVxgZmS+McwGtphLeaQ4iTlFd5EcSRuiRQLAmbJsnWRLOvpBtiP9T2OXOJzmrucVlKA+pY2Q7qsHm98R30qBKjvZi3xqEzqOsUWP4jXQwFEqls7zB9+F7vEioStXOeTipzEHCBEMB01Z4tsTHrRbzjEpZaas6iRKGnBBJAzf+r5nBbtIF/R6uFgktcy63V/5AchHeNTnGSrSpmLEV8T768lG4wOLB3ZnxACqzylkC7sG8acs0iVTLnOLx5ZOq3P8coQKBgQC5aXT4JYiX9niupJE0exaHy/6FMj+iN904q/e1BkOkDqZyDPZYlvG8C5ri/CPdJqdVsQ0kakCScRa2CJW2/57RRclTFvjvDgnGsZDB1V7UpE0G6sFwmSjXKB85ciKgu8/PYKOzUgwwX8asqfm3hS8XxSMeTbxWGSrD2X2C5tLgSwKBgQCydNQwe0NNvl6OXqJwKSOQytgmasWSaH5dS0eDkdf8K2yGB5hwKB5YHJnX6LWyR5DajKQpYKRFW8mCjPbgtR+uW8hzu7y2FZJLEts7OmJQ1o3gxk4fbUB32zL2cwxeDucCzBslGcOFghS8l8yGwYUVFVRJhwFdtpbl1g8L/tcWJQKBgQCqcibEZATA5iSlL8YIv8rDhaVyHvJelwp4KaaqtJqD+6/Jkt74K7MIEocNeYsip4EXBo81VbQMq4ecSiIPu8ftTEE6cBjh8j7MeLnBZvwpcO0amb7AWxwvRsQFlEX/CwiL9KQomhl4cuN6ITveGMJlEKYrGn0zjSlCJ/L43mcnJwKBgQCUtpMVC8NciCYYEnjfawj+YmuaKCQZDAcyC8e+tsz8kdtQHghEfso6tyrlKEIyHT1zQvySlryOKB1XM82QGKAcFtSGzY5HVtagxUf4pYDEyOdWxyrXOZ4dw4dGpT1LLLQKOrjsQ/oRygMp3n5MVfxnQ20IEP9sbvp08dt8LZRkGQKBgArPFzVpThTQ/pue95NGoLCaYf0y4MTnKHzo+Vvdy7H6iyeFKTMY4S/wi9JrdZayR8Ni3iewVeNvSYgDVHE4Nb2c1vyXqKlYysiWSheK7tWcEiA6CiJWKVvvLzlC5MDzGA2YPmkZm1yQdqF12KQcmQ2EdILzoAZphXhb7GA6FVk8";
	
	// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgT/wy/xz00XS9nTsSjvtVJ8Yw6/3egpZUQ7EOucLP0WEdodELn4HHJv9jsZiJIfRyZHOnVuly/hJd/p1kG7aKlrDfva9Qlu9eB4kx6OHA85TmE/903zNdciyJjdwcgg0LxO8HzkP4KlJkvlxHqPQr7UvqWqeWGGEV93NlIp96jtf61gzuu9MMpKuyplCwr1q39gPEiU+XkY/TrTO+l/y7wqxbOIXapzBO3gquXVJt/Niv2K2t3dgQf6Eun0hvSama+4nVOQvbgqZzojvnPyYzvJatkl81aaQlJJnBYfZDM96Ck2noPP8V+nR8ipw+aIwm9d27k21+zYlE4GfRL3c1wIDAQAB";

    // 服务器异步通知页面路径  需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
    public static String notify_url = "http://localhost:8080/springbootbpe1s/";

    // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
    public static String return_url = "http://localhost:8080/springbootbpe1s/admin/dist/index.html#/";
    public static String return_url2 = "http://localhost:8080/springbootbpe1s/front/index.html";

	// 签名方式
	public static String sign_type = "RSA2";
	
	// 字符编码格式
	public static String charset = "utf-8";
	
	// 支付宝网关
	public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.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();
                }
            }
        }
    }
}

3.支付接口和通知接口

 @RequestMapping("/alipay")
    public R payController(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url2);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url+"orders"+"/notify");

        String out_trade_no = new String(request.getParameter("tradeno"));
        String total_amount = new String(request.getParameter("totalamount").getBytes("ISO-8859-1"),"UTF-8");
        String subject = new String(request.getParameter("subject"));
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return R.ok().put("data",form);
    }

    @IgnoreAuth
    @RequestMapping("notify")
    public R nofity(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /* *
         * 功能:支付宝服务器异步通知页面
         *************************页面功能说明*************************
         * 创建该页面文件时,请留心该页面文件中无任何HTML代码及空格。
         * 该页面不能在本机电脑测试,请到服务器上做测试。请确保外部可以访问该页面。
         * 如果没有收到该页面返回的 success
         * 建议该页面只做支付成功的业务逻辑处理,退款的处理请以调用退款查询接口的结果为准。
         */

            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决,这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                //如果有做过处理,不执行商户的业务程序

                //注意:
                //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                //如果有做过处理,不执行商户的业务程序

                //注意:
                //付款完成后,支付宝系统发送该交易状态通知
                OrdersEntity orders = ordersService.selectOne(new EntityWrapper<OrdersEntity>().eq("orderid", out_trade_no));
                if(orders!=null) {
                    orders.setStatus("已支付");
                    ordersService.updateById(orders);
                }
            }

            //——请在这里编写您的程序(以上代码仅作参考)——
            return R.ok();
    }

你可能感兴趣的:(javascript,前端,vue.js)