Java利用沙箱支付实现电脑扫码支付教程
程序员文章站
2022-06-22 11:43:06
目录一、准备工作二、效果展示三、实现代码3.1 后台代码3.2 前台代码一、准备工作1、注册支付宝开放平台账号,成为开发者。地址:https://open.alipay.com/platform/ho...
一、准备工作
1、注册支付宝开放平台账号,成为开发者。
地址:https://open.alipay.com/platform/home.htm
2、进入沙箱,进行配置。
3.我们可以看到这个界面
4.后面需要使用的参数
- appid
- 商户私钥(使用系统默认密钥的公钥模式,点击查看获取)
- 支付宝公钥
- 支付宝网关
5、手机上下载沙箱支付宝 (到时候支付用这个支付宝支付)
6、下载好支付宝沙箱版后,登录支付宝提供的账号
二、效果展示
1、随手写的一个前台vue界面
2、进入确定订单界面,可以添加商品描述
3、跳转支付界面,利用沙箱支付宝完成支付
4、完成支付
5、跳回自己设置的界面
三、实现代码
3.1 后台代码
(我这里利用的是springboot集成的ssm,当然不使用springboot也可以)
3.1.1 pom.xml文件
不用全部的,重点是 :支付宝sdk包、fastjson
<?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.zking</groupid> <artifactid>springboot02</artifactid> <version>0.0.1-snapshot</version> <name>springboot02</name> <description>demo project for spring boot</description> <properties> <java.version>1.8</java.version> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding> <spring-boot.version>2.1.18.release</spring-boot.version> </properties> <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-jdbc</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.mybatis.spring.boot</groupid> <artifactid>mybatis-spring-boot-starter</artifactid> <version>2.1.4</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.44</version> <scope>runtime</scope> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <optional>true</optional> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.junit.jupiter</groupid> <artifactid>junit-jupiter</artifactid> <version>release</version> <scope>test</scope> </dependency> <dependency> <groupid>com.github.pagehelper</groupid> <artifactid>pagehelper-spring-boot-starter</artifactid> <version>1.4.1</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-aop</artifactid> <version>2.6.2</version> </dependency> <!-- 支付宝sdk包 --> <dependency> <groupid>com.alipay.sdk</groupid> <artifactid>alipay-sdk-java</artifactid> <version>3.1.0</version> </dependency> <!-- fastjson --> <dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.48</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>1.2.6</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>1.2.17</version> </dependency> </dependencies> <dependencymanagement> <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-dependencies</artifactid> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencymanagement> <build> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> <!-- mvn mybatis-generator:generate --> <plugin> <groupid>org.mybatis.generator</groupid> <artifactid>mybatis-generator-maven-plugin</artifactid> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> <!--配置文件的位置--> <configurationfile>src/main/resources/generatorconfig.xml</configurationfile> </configuration> </plugin> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <version>2.1.18.release</version> <configuration> <mainclass>com.zking.springboot02.springboot02application</mainclass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
3.1.2 model包
package com.zking.springboot02.model; import lombok.data; /** * 支付实体对象 * 根据支付宝接口协议,其中的属性名,必须使用下划线,不能修改 * * @author 借我丹青妙笔 */ @data public class alipaybean { private static final long serialversionuid = 1l; /** * 商户订单号,必填 * */ private string out_trade_no; /** * 订单名称,必填 */ private string subject; /** * 付款金额,必填 * 根据支付宝接口协议,必须使用下划线 */ private string total_amount; /** * 商品描述,可空 */ private string body; /** * 超时时间参数 */ private string timeout_express= "10m"; /** * 产品编号 */ private string product_code= "fast_instant_trade_pay"; public string getout_trade_no() { return out_trade_no; } public void setout_trade_no(string out_trade_no) { this.out_trade_no = out_trade_no; } public string getsubject() { return subject; } public void setsubject(string subject) { this.subject = subject; } public string gettotal_amount() { return total_amount; } public void settotal_amount(string total_amount) { this.total_amount = total_amount; } public string getbody() { return body; } public void setbody(string body) { this.body = body; } }
3.1.3 utils包alipayconfig类
(请配置好该类,防止报错)
- appid:appid,沙箱应用提供的
- privatekey: 商户私钥,点击公钥证书查看
- returnurl : 支付完成后跳转的页面,例如我填的是:http://localhost:8088/
package com.zking.springboot02.utils; import lombok.data; import org.springframework.context.annotation.configuration; import org.springframework.context.annotation.propertysource; import org.springframework.stereotype.component; /** * 配置文件读取 * */ @configuration @data @component public class alipayconfig { /** * 应用id,您的appid,收款账号既是您的appid对应支付宝账号 */ private string appid = ""; /** * 商户私钥,您的pkcs8格式rsa2私钥 */ private string privatekey = ""; /** * 支付宝公钥, */ private string publickey = "miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeayqan9wzwigim0/3fbk97rfz7juu31+dfxmvhthstp+4wpvr80ztiiqmt9xtfvgbgd8bbx0xelxqlqxsyqm/mgegcchtnckpp7ci979yuwzyjoysdtc6bno/6rqpzruih6wsydjnujugy/hwuwi+owudbhl7nvz8r/taijvezzhjvrtmsibqbe66lre7ge2avwev8qck9e4yexsdud7ja1+2t1ltfhap2u/sbod+7pkkpgvkinpdht4bxz9dihphosiw8iideenixj/ku1wtgetll/btjljhhxq98jhblw94+yx+bq+9s2s2cjxkxfdzdb9s+jfy80e6uiv76xxfb0qidaqab"; /** * 服务器异步通知页面路径需http://格式的完整路径,不能加?id=123这类自定义参数 */ private string notifyurl = "https://www.duan33f.top"; /** * 页面跳转同步通知页面路径 需http://格式的完整路径. * 支付完成后返回的地址 */ private string returnurl = ""; /** * 签名方式 */ private string signtype = "rsa2"; /** * 字符编码格式 */ private string charset = "utf-8"; /** * 支付宝网关 */ private string gatewayurl = "https://openapi.alipaydev.com/gateway.do"; /** * 支付宝网关 */ private string logpath = "c:\\"; }
alipay类
package com.zking.springboot02.utils; 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.zking.springboot02.model.alipaybean; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.component; import javax.annotation.resource; /** * 支付宝支付接口 * @author 借我丹青妙笔 */ @component public class alipay { @autowired private alipayconfig alipayconfig; /** * 支付接口 * @param alipaybean * @return * @throws alipayapiexception */ public string pay(alipaybean alipaybean) throws alipayapiexception { // 1、获得初始化的alipayclient string serverurl = alipayconfig.getgatewayurl(); string appid = alipayconfig.getappid(); string privatekey = alipayconfig.getprivatekey(); string format = "json"; string charset = alipayconfig.getcharset(); string alipaypublickey = alipayconfig.getpublickey(); string signtype = alipayconfig.getsigntype(); string returnurl = alipayconfig.getreturnurl(); string notifyurl = alipayconfig.getnotifyurl(); //system.out.println(appid); alipayclient alipayclient = new defaultalipayclient(serverurl, appid, privatekey, format, charset, alipaypublickey, signtype); // 2、设置请求参数 alipaytradepagepayrequest alipayrequest = new alipaytradepagepayrequest(); // 页面跳转同步通知页面路径 alipayrequest.setreturnurl(returnurl); // 服务器异步通知页面路径 alipayrequest.setnotifyurl(notifyurl); // 封装参数 alipayrequest.setbizcontent(json.tojsonstring(alipaybean)); // 3、请求支付宝进行付款,并获取支付结果 string result = alipayclient.pageexecute(alipayrequest).getbody(); // 返回付款信息 return result; } }
3.1.4 service包
payservice接口
package com.zking.springboot02.service; import com.alipay.api.alipayapiexception; import com.zking.springboot02.model.alipaybean; /** * 支付服务 * @author 借我丹青妙笔 * @date dec 12, 2018 */ public interface payservice { /** * 支付宝支付接口 * @param alipaybean * @return * @throws alipayapiexception */ string alipay(alipaybean alipaybean) throws alipayapiexception; }
payserviceimpl类
package com.zking.springboot02.service.impl; import com.alipay.api.alipayapiexception; import com.zking.springboot02.model.alipaybean; import com.zking.springboot02.service.payservice; import com.zking.springboot02.utils.alipay; import org.springframework.stereotype.service; import javax.annotation.resource; @service public class payserviceimpl implements payservice { @resource private alipay alipay; @override public string alipay(alipaybean alipaybean) throws alipayapiexception { return alipay.pay(alipaybean); } }
3.1.5 contorller包
paycontroller类
package com.zking.springboot02.contorller; import com.alipay.api.alipayapiexception; import com.zking.springboot02.model.alipaybean; import com.zking.springboot02.service.payservice; import org.springframework.web.bind.annotation.crossorigin; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import javax.annotation.resource; import java.util.hashmap; import java.util.map; @restcontroller @requestmapping("/pay") @crossorigin public class paycontroller { @resource private payservice payservice; /** * 阿里支付 * @param alipaybean * @return * @throws alipayapiexception */ @postmapping("/alipay") public map alipay(alipaybean alipaybean) throws alipayapiexception { system.out.println(alipaybean); map<string,object> map = new hashmap<string,object>(); string str = payservice.alipay(alipaybean); system.out.println(str); map.put("msg",str); map.put("code",0); // return map; } }
3.1.6 application.yml文件
server: port: 8080 #端口号 servlet: context-path: /s02 #项目名
3.2 前台代码
(前台是利用脚手架搭建的vue项目)
3.2.1 src下api包下action.js文件
/** * 对后台请求的地址的封装,url格式如下: * 模块名_实体名_操作 */ export default { //服务器 'server': 'http://localhost:8080/s02', 'alipay' : 'http://localhost:8080/s02/pay/alipay', //获得请求的完整地址,用于mockjs测试时使用 'getfullpath': k => { return this.server + this[k]; } }
3.2.2 src下api包下http.js文件
/** * vue项目对axios的全局配置 */ import axios from 'axios' import qs from 'qs' //引入action模块,并添加至axios的类属性urls上 import action from '@/api/action' axios.urls = action // axios默认配置 axios.defaults.timeout = 10000; // 超时时间 // axios.defaults.baseurl = 'http://localhost:8080/crm'; // 默认地址 axios.defaults.baseurl = action.server; //整理数据 // 只适用于 post,put,patch,transformrequest` 允许在向服务器发送前,修改请求数据 axios.defaults.transformrequest = function(data) { data = qs.stringify(data); return data; }; // 请求拦截器 axios.interceptors.request.use(function(config) { // let jwt = sessionstorage.getitem('jwt'); // if (jwt) { // config.headers['jwt'] = jwt; // } return config; }, function(error) { return promise.reject(error); }); // 响应拦截器 axios.interceptors.response.use(function(response) { return response; }, function(error) { return promise.reject(error); }); export default axios;
3.2.3 src下router下index.js文件
import vue from 'vue' import router from 'vue-router' import shop from '@/views/shop' import buy from '@/views/buy' vue.use(router) export default new router({ routes: [ { path: '/', name: 'shop', component: shop }, { path: '/buy', name: 'buy', component: buy } ] })
3.2.4 src下views下shop.vue文件
<template> <el-table :data="tabledata" style="width: 100%"> <el-table-column prop="out_trade_no" label="编号"> </el-table-column> <el-table-column prop="subject" label="订单名称" > </el-table-column> <el-table-column prop="total_amount" label="付款金额"> </el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button @click="tobuy(scope.row)" type="text" size="small">去支付</el-button> </template> </el-table-column> </el-table> </template> <script> export default { name: "shop", data: function() { return { tabledata: [{ out_trade_no: '101', subject: 'java从入门到入土', total_amount: 33 }, { out_trade_no: '202', subject: 'mysql删库跑路指南', total_amount: 44 }, { out_trade_no: '303', subject: 'java编程思想', total_amount: 89 }, { out_trade_no: '404', subject: 'java设计模式', total_amount: 56 }] }; }, methods: { tobuy(row){ console.log(row); //利用$router.push进行跳转 this.$router.push({ //path后面跟跳转的路由地址 path: '/buy', //name后面跟跳转的路由名字(必须有亲测,不使用命名路由会传参失败) name: 'buy', params: { //imgslistsurl2是自己定义的名字,this.imgslistsurl是要被传递的值 payinfo: row } }) } }, created: function() { } } </script> <style> </style>
3.2.5 src下views下buy.vue文件
<template> <div class="main"> <center> <div class="box"> <h2>确定订单</h2> <el-form :model="payinfo" :rules="rules" ref="ruleform" label-width="100px" class="demo-ruleform"> <el-form-item label="订单号" prop="out_trade_no"> <el-input v-model="payinfo.out_trade_no" readonly="true"></el-input> </el-form-item> <el-form-item label="商品名称" prop="subject"> <el-input v-model="payinfo.subject" readonly="true"></el-input> </el-form-item> <el-form-item label="商品价格" prop="total_amount"> <el-input v-model="payinfo.total_amount" readonly="true"></el-input> </el-form-item> <el-form-item label="商品描述" prop="body"> <el-input v-model="payinfo.body"></el-input> </el-form-item> <el-button type="primary" plain @click="submit" style="width: 100%;" round>付款</el-button> </el-form> </div> </center> </div> </template> <script> //import axios from 'axios' export default { name: "buy", data() { return { payinfo: { out_trade_no: '', subject: '', total_amount: null, body: '' } } }, mounted() { //this.$route.params.imgslistsurl2是传过来的参数 var time = new date(); this.payinfo = this.$route.params.payinfo this.payinfo.out_trade_no = time.gettime(); }, methods: { submit() { var url = this.axios.urls.alipay;//得到api下action.js中的alipay this.axios.post(url, this.payinfo).then(resp => {//调用后台方法 console.log(resp); const divform = document.getelementsbytagname('div') if (divform.length) { document.body.removechild(divform[0]) } const div = document.createelement('div') div.innerhtml = resp.data.msg // data就是接口返回的form 表单字符串 document.body.appendchild(div) document.forms[0].setattribute('target', '_blank') // 新开窗口跳转 document.forms[0].submit() }).catch(resp => { console.log(resp); }); } } } </script> <style scoped> .box { width: 800px; } .left { width: 85px; padding-top: 5px; font-size: 15px; } .right { width: 400px; } </style>
3.2.6 src下main.js文件
import vue from 'vue' import elementui from 'element-ui' //新添加1 import 'element-ui/lib/theme-chalk/index.css' //新添加2,避免后期打包样式不同,要放在import app from './app';之前 import axios from '@/api/http' //vue项目对axios的全局配置 import app from './app' import router from './router' import vueaxios from 'vue-axios' vue.use(vueaxios,axios) vue.use(elementui) //新添加3 vue.config.productiontip = false /* eslint-disable no-new */ new vue({ el: '#app', router, components: { app }, template: '<app/>' })
ok,重要的代码已经完全提供了。
声明:实现沙箱支付可以让我们了解如何调用如支付宝的接口,让我们理解接口的调用。
以上就是java利用沙箱支付实现电脑扫码支付教程的详细内容,更多关于java电脑扫码支付的资料请关注其它相关文章!