您的位置:首页技术文章
文章详情页

Vue+SpringBoot实现支付宝沙箱支付的示例代码

【字号: 日期:2022-06-09 09:42:14浏览:50作者:猪猪

首先去下载支付宝沙箱的一系列东西,具体的配置什么的我就不说了,有很多博客都讲了,还有蚂蚁金服官方也说的很详细,我就直接说怎么样把后端的支付页面显示到Vue前端来:

在你配置好AlipayConfig这个文件后,就可以写前端的逻辑了,前端是采用支付宝的页面如下:

下面展示一些 内联代码片。

/* 以下是支付确认html */ <div style='text=#000000 bgColor=#ffffff leftMargin=0 topMargin=4'><header class='am-header'> <h1>支付确认</h1></header><div id='main'> <!-- <form name='alipayment' :model='payObject' target='_blank'> --> <div name='divcontent'> <dl class='content'> <dt>商户订单号 :</dt> <dd><input name='WIDout_trade_no' readonly='true' :value='payObject.WIDout_trade_no'/> </dd> <hr /> <dt>订单名称 :</dt> <dd><input name='WIDsubject' readonly='true' :value='payObject.WIDsubject'/> </dd> <hr /> <dt>付款金额 :</dt> <dd><input name='WIDtotal_amount' readonly='true' :value='payObject.WIDtotal_amount'/> </dd> <hr /> <dt>商品描述:</dt> <dd><input name='WIDbody' readonly='true' :value='payObject.WIDbody' /> </dd> <hr /> <dd id='btn-dd'><span class='new-btn-login-sp'> <button @click='paySub()'>付 款</button></span><span class='note-help'>如果您点击“付款”按钮,即表示您同意该次的执行操作。</span> </dd> </dl> </div> <!-- </form> --></div> </div>

我再加上这个页面的css

/* 以下是支付确认样css*/.am-header { display: -webkit-box; display: -ms-flexbox; /* display: flex; */ width: 100%; position: relative; padding: 15px 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;}#main { width: 100%; margin: 0 auto; font-size: 14px;}.show { clear: left; display: block;}.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; inputoutline: none;}.one_line { display: block; height: 1px; border: 0; border-top: 1px solid #eeeeee; width: 100%; margin-left: 20px;}#btn-dd { margin: 20px; text-align: center;}.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: 50px; border-radius: 5px; font-size: 16px;}.note-help { color: #999999; font-size: 12px; line-height: 100%; margin-top: 5px; width: 100%; display: block;}

当然,在html页面的数据是以下这样定义的:

/*html用的数据*/ payObject: {//支付数据WIDsubject: 0,WIDout_trade_no: '',WIDtotal_amount: '',WIDbody: '' },

当然,在你要打开支付这个页面时,你得用函数把这些数据进行赋值,就是以下代码,具体看注释:

//去往支付页面函数 payOrder() { //this.payObject.WIDsubject这个我已经在跳转支付界面时把这个给设为订单号了 //判断oid(订单号)是否是数字 if (typeof this.payObject.WIDsubject != 'string') { //从sessionStorage拿出用户的数据const usertoken = sessionStorage.getItem('usertoken');const user = JSON.parse(sessionStorage.getItem('user'));// console.log(user)//如果用户正常(不为空)if (usertoken != null) { if (user != null) { const uname = user.uname; //我在这里去获取哪个订单需要支付 dishApi.payConfirm(this.payObject.WIDsubject).then(response => { const resp = response.data; if (resp.code === 200) { //生成这个sNow数据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());//绑定页面的data数据this.payObject.WIDout_trade_no = sNow; //绑定tradenothis.payObject.WIDbody = uname;//我这里是绑定的用户名this.payObject.WIDsubject = resp.oid; //返回现在的订单号值this.payObject.WIDtotal_amount = resp.totalValue; //返回支付总价 } else {this.$message({ message: resp.message, type: 'warning', duration: 500 // 弹出停留时间}); } }); } else { this.$message({ message: '请先登录', type: 'warning', duration: 1000 // 弹出停留时间 }); }} else { this.$message({ message: '请先登录', type: 'warning', duration: 1000 // 弹出停留时间 });} } else {this.$message({ message: '支付错误', type: 'warning', duration: 1000 // 弹出停留时间}); } },

然后我在来说当你点击立即付款后怎么做(就是点击付款调用paySub()函数)

//支付开始 /给用户提示 paySub() { this.$message({showClose: true,message: '请在5分钟内完成支付',duration: 5000 // 弹出停留时间 }); //前往支付 //这里向后端传入你的支付数据,就是刚才定义的和绑定的数据 dishApi.pay( this.payObject.WIDout_trade_no, this.payObject.WIDtotal_amount, this.payObject.WIDsubject, this.payObject.WIDbody).then(response => {//后台响应后处理如下 const r = response.data; if (r.code === 200) { //这是后端响应的r,我获取了它的formaction,至于这里面是什么,我们后面说, //获取到的数据先存储在sessionStorage中,为了将来的读取 sessionStorage.setItem('payaction', r.formaction);//然后就将页面跳转到支付的界面 window.open('#pay', '_blank'); } else { this.$message({ message: resp.message, type: 'warning', duration: 500 // 弹出停留时间 }); }}); },

接下来就改springboot后端了:我们来写上面这个dishApi.pay()访问的后端是怎么样的

@ResponseBody @PostMapping('/AliPay') //在这里接收前端传来的数据payInfo public Object goPay(@RequestBody JSONObject payInfo,HttpServletResponse response,HttpServletRequest request) throws IOException, AlipayApiException { //首先在这里JSONObject jsonObject = new JSONObject();try {//这里是解析前端传来的数据 String WIDout_trade_no = payInfo.get('WIDout_trade_no').toString(); String WIDtotal_amount = payInfo.get('WIDtotal_amount').toString(); String WIDsubject = payInfo.get('WIDsubject').toString(); String WIDbody = payInfo.get('WIDbody').toString();//System.out.println(WIDout_trade_no);System.out.println(WIDtotal_amount);System.out.println(WIDsubject);System.out.println(WIDbody); //获得初始化的AlipayClient 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_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'); String out_trade_no = WIDout_trade_no; //付款金额,必填 String total_amount = WIDtotal_amount; //订单名称,必填 String subject = WIDsubject; //商品描述,可空 String body = WIDbody; // 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点, 如 1.5h,可转换为 90m。 String timeout_express = '10m'; //例子去官方api找 alipayRequest.setBizContent('{'out_trade_no':'' + out_trade_no + '',' + ''total_amount':'' + total_amount + '',' + ''subject':'' + subject + '',' + ''body':'' + body + '',' + ''timeout_express':'' + timeout_express + '',' + ''product_code':'FAST_INSTANT_TRADE_PAY'}');////请求 String result = alipayClient.pageExecute(alipayRequest).getBody() ; //这里以上都是支付宝的,接下来是我的 //接下来是一系列的字符串操作,总之就是给支付宝返回的result页面的按钮属性设置为非hidden,并且添加了一些好看的属性,然后取出来<script>标签(因为前端用v-html不能显示<script>)最后将整个改造的result发给前端,就有了上面的前端将接收的内容写入sessionStorage的操作 String befAction = result; StringBuffer aftAction = new StringBuffer(befAction); aftAction = aftAction.reverse(); String midAction = aftAction.substring(68); aftAction = new StringBuffer(midAction).reverse(); aftAction=aftAction.append(' width: 200px; padding:8px; background-color: #428bca; border-color: #357ebd; color: #fff; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px; -khtml-border-radius: 10px;text-align: center; vertical-align: middle; border: 1px solid transparent; font-weight: 900; font-size:125% '> </form>'); jsonObject.put('formaction', aftAction); jsonObject.put('message', StateCode.SUCCESS.getMessage()); jsonObject.put('code', StateCode.SUCCESS.getCode()); return jsonObject;}catch (Exception e){ jsonObject.put('message', StateCode.SERVER_FAILED.getMessage()); jsonObject.put('code', StateCode.SERVER_FAILED.getCode()); return jsonObject;} }

在接下来就又是前端的操作了,由于刚才前端进行了页面跳转,所以我们接下来写的是前端跳转后的那个页面:

//这是跳转到的页面的全部代码<template><div class='top'><h1 class='top'>收银台</h1> <div v-html='payaction'></div></div></template><script>export default { data() { return { payaction: '' }; }, created() { this.showPayPage(); }, methods: { showPayPage() { this.$nextTick(function() { //我们直接把刚才写在sessionStorage的页面显示在当前页面this.payaction = sessionStorage.getItem('payaction');//然后删除sessionStorage的数据sessionStorage.removeItem('payaction'); }); }, }};</script><style scoped>.top{margin-top: 50px;text-align: center;vertical-align: middle;margin-bottom: 100px;}</style>

至此,所有代码就结束了,你在这个页面直接点击支付按钮就会跳转到支付宝沙箱支付的界面了。

到此这篇关于Vue+SpringBoot实现支付宝沙箱支付的示例代码的文章就介绍到这了,更多相关Vue+SpringBoot 支付宝沙箱支付内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: 支付宝
相关文章: