包括:
支付宝沙箱 支付 + 异步通知 + 退款功能
正式版本的sdk
通用版本SDK文档:https://opendocs.alipay.com/open/02np94
<dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-sdk-java</artifactId><version>4.22.110.ALL</version></dependency>
AlipayConfig.java 只需要获取配置alipay的参数即可
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Data
@Component
@ConfigurationProperties(prefix = "alipay")
public class AliPayConfig {private String appId;private String appPrivateKey;private String alipayPublicKey;private String notifyUrl;}
参数更新:
import lombok.Data;@Data
public class AliPay {private String traceNo;private double totalAmount;private String subject;private String alipayTraceNo;
}
完整的支付宝通用版本支付代码:
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.springboot.common.Result;
import com.example.springboot.config.AliPayConfig;
import com.example.springboot.controller.dto.AliPay;
import com.example.springboot.entity.Orders;
import com.example.springboot.mapper.OrdersMapper;
import org.springframework.web.bind.annotation.GetMapping;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;// xjlugv6874@sandbox.com
// 9428521.24 - 30 = 9428491.24 + 30 = 9428521.24
@RestController
@RequestMapping("/alipay")
public class AliPayController {private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";private static final String FORMAT = "JSON";private static final String CHARSET = "UTF-8";//签名方式private static final String SIGN_TYPE = "RSA2";@Resourceprivate AliPayConfig aliPayConfig;@Resourceprivate OrdersMapper ordersMapper;@GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxxpublic void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {// 1. 创建Client,通用SDK提供的Client,负责调用支付宝的APIAlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);// 2. 创建 Request并设置Request参数AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的 Request类request.setNotifyUrl(aliPayConfig.getNotifyUrl());JSONObject bizContent = new JSONObject();bizContent.set("out_trade_no", aliPay.getTraceNo()); // 我们自己生成的订单编号bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额bizContent.set("subject", aliPay.getSubject()); // 支付的名称bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置request.setBizContent(bizContent.toString());// 执行请求,拿到响应的结果,返回给浏览器String form = "";try {form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单} catch (AlipayApiException e) {e.printStackTrace();}httpResponse.setContentType("text/html;charset=" + CHARSET);httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面httpResponse.getWriter().flush();httpResponse.getWriter().close();}@PostMapping("/notify") // 注意这里必须是POST接口public String payNotify(HttpServletRequest request) throws Exception {if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {System.out.println("=========支付宝异步回调========");Map<String, String> params = new HashMap<>();Map<String, String[]> requestParams = request.getParameterMap();for (String name : requestParams.keySet()) {params.put(name, request.getParameter(name));// System.out.println(name + " = " + request.getParameter(name));}String tradeNo = params.get("out_trade_no");String gmtPayment = params.get("gmt_payment");String alipayTradeNo = params.get("trade_no");String sign = params.get("sign");String content = AlipaySignature.getSignCheckContentV1(params);boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名// 支付宝验签if (checkSignature) {// 验签通过System.out.println("交易名称: " + params.get("subject"));System.out.println("交易状态: " + params.get("trade_status"));System.out.println("支付宝交易凭证号: " + params.get("trade_no"));System.out.println("商户订单号: " + params.get("out_trade_no"));System.out.println("交易金额: " + params.get("total_amount"));System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));System.out.println("买家付款时间: " + params.get("gmt_payment"));System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));// 更新订单未已支付ordersMapper.updateState(tradeNo, "已支付", gmtPayment, alipayTradeNo);}}return "success";}@GetMapping("/return")public Result returnPay(AliPay aliPay) throws AlipayApiException {// 7天无理由退款String now = DateUtil.now();Orders orders = ordersMapper.getByNo(aliPay.getTraceNo());if (orders != null) {// hutool工具类,判断时间间隔long between = DateUtil.between(DateUtil.parseDateTime(orders.getPaymentTime()), DateUtil.parseDateTime(now), DateUnit.DAY);if (between > 7) {return Result.error("-1", "该订单已超过7天,不支持退款");}}// 1. 创建Client,通用SDK提供的Client,负责调用支付宝的APIAlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET,aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);// 2. 创建 Request,设置参数AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();JSONObject bizContent = new JSONObject();bizContent.set("trade_no", aliPay.getAlipayTraceNo()); // 支付宝回调的订单流水号bizContent.set("refund_amount", aliPay.getTotalAmount()); // 订单的总金额bizContent.set("out_request_no", aliPay.getTraceNo()); // 我的订单编号// 返回参数选项,按需传入//JSONArray queryOptions = new JSONArray();//queryOptions.add("refund_detail_item_list");//bizContent.put("query_options", queryOptions);request.setBizContent(bizContent.toString());// 3. 执行请求AlipayTradeRefundResponse response = alipayClient.execute(request);if (response.isSuccess()) { // 退款成功,isSuccess 为trueSystem.out.println("调用成功");// 4. 更新数据库状态ordersMapper.updatePayState(aliPay.getTraceNo(), "已退款", now);return Result.success();} else { // 退款失败,isSuccess 为falseSystem.out.println(response.getBody());return Result.error(response.getCode(), response.getBody());}}}
至此,后端集成完毕。
注意事项
如果你在支付的过程中出现了这样的一个界面,不用慌,直接使用 隐私窗口打开即可。
参考SQL
商品表:
CREATE TABLE `goods` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '名称',`price` decimal(10,2) DEFAULT NULL COMMENT '单价',`store` int(10) DEFAULT NULL COMMENT '库存',`unit` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '单位',`img` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '封面',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
订单表
CREATE TABLE `orders` (`id` int(11) NOT NULL AUTO_INCREMENT,`no` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '订单编号',`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '名称',`time` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '订单时间',`state` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '待支付' COMMENT '支付状态',`total` decimal(10,2) DEFAULT NULL COMMENT '订单总价',`user_id` int(11) DEFAULT NULL COMMENT '用户id',`payment_time` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '支付时间',`alipay_no` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '支付宝交易号',`return_time` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '退款时间',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
购买下订单的模拟接口:
@PostMapping("/{goodsId}/{num}")public Result createOrder(@PathVariable Integer goodsId, @PathVariable Integer num) {Goods goods = goodsService.getById(goodsId);if (goods == null) {throw new ServiceException("-1", "未找到商品");}User currentUser = TokenUtils.getCurrentUser();Integer userId = currentUser.getId();Orders orders = new Orders();orders.setName(goods.getName());orders.setNo(DateUtil.format(new Date(), "yyyyMMdd") + System.currentTimeMillis());orders.setTime(DateUtil.now());orders.setUserId(userId);orders.setTotal(goods.getPrice().multiply(BigDecimal.valueOf(num)));ordersService.save(orders);return Result.success();}
附赠前端调用代码:
Goods.vue
<template><div><div style="margin: 10px 0"><el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
<!-- <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
<!-- <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>--><el-button class="ml-5" type="primary" @click="load">搜索</el-button><el-button type="warning" @click="reset">重置</el-button></div><div style="margin: 10px 0"><el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button><el-popconfirmclass="ml-5"confirm-button-text='确定'cancel-button-text='我再想想'icon="el-icon-info"icon-color="red"title="您确定批量删除这些数据吗?"@confirm="delBatch"><el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button></el-popconfirm><!-- <el-upload action="http://localhost:9090/goods/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block"><el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button></el-upload><el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> --></div><el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange"><el-table-column type="selection" width="55"></el-table-column><el-table-column prop="id" label="ID" width="80" sortable></el-table-column><el-table-column prop="name" label="名称"></el-table-column><el-table-column prop="price" label="单价"></el-table-column><el-table-column prop="store" label="库存"></el-table-column><el-table-column prop="unit" label="单位"></el-table-column><el-table-column label="图片"><template slot-scope="scope"><el-image style="width: 100px; height: 100px" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image></template></el-table-column><el-table-column label="购买" width="180" align="center"><template v-slot="scope"><el-button type="primary" @click="buy(scope.row.id)">购 买</el-button></template></el-table-column><el-table-column label="操作" width="180" align="center"><template slot-scope="scope"><el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button><el-popconfirmclass="ml-5"confirm-button-text='确定'cancel-button-text='我再想想'icon="el-icon-info"icon-color="red"title="您确定删除吗?"@confirm="del(scope.row.id)"><el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button></el-popconfirm></template></el-table-column></el-table><div style="padding: 10px 0"><el-pagination@size-change="handleSizeChange"@current-change="handleCurrentChange":current-page="pageNum":page-sizes="[2, 5, 10, 20]":page-size="pageSize"layout="total, sizes, prev, pager, next, jumper":total="total"></el-pagination></div><el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false"><el-form label-width="100px" size="small" style="width: 90%"><el-form-item label="名称"><el-input v-model="form.name" autocomplete="off"></el-input></el-form-item><el-form-item label="单价"><el-input v-model="form.price" autocomplete="off"></el-input></el-form-item><el-form-item label="库存"><el-input v-model="form.store" autocomplete="off"></el-input></el-form-item><el-form-item label="单位"><el-input v-model="form.unit" autocomplete="off"></el-input></el-form-item><el-form-item label="封面"><el-upload action="http://localhost:9090/file/upload" ref="img" :on-success="handleImgUploadSuccess"><el-button size="small" type="primary">点击上传</el-button></el-upload></el-form-item></el-form><div slot="footer" class="dialog-footer"><el-button @click="dialogFormVisible = false">取 消</el-button><el-button type="primary" @click="save">确 定</el-button></div></el-dialog></div>
</template><script>
export default {name: "Goods",data() {return {tableData: [],total: 0,pageNum: 1,pageSize: 10,name: "",form: {},dialogFormVisible: false,multipleSelection: [],user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}}},created() {this.load()},methods: {buy(goodsId) {this.request.post("/orders/" + goodsId + "/" + 1).then(res => {if (res.code === '200') {this.$message.success("购买成功,请前往订单页面支付")} else {this.$message.error(res.msg)}})},load() {this.request.get("/goods/page", {params: {pageNum: this.pageNum,pageSize: this.pageSize,name: this.name,}}).then(res => {this.tableData = res.data.recordsthis.total = res.data.total})},save() {this.request.post("/goods", this.form).then(res => {if (res.code === '200') {this.$message.success("保存成功")this.dialogFormVisible = falsethis.load()} else {this.$message.error("保存失败")}})},handleAdd() {this.dialogFormVisible = truethis.form = {}this.$nextTick(() => {if(this.$refs.img) {this.$refs.img.clearFiles();}if(this.$refs.file) {this.$refs.file.clearFiles();}})},handleEdit(row) {this.form = JSON.parse(JSON.stringify(row))this.dialogFormVisible = truethis.$nextTick(() => {if(this.$refs.img) {this.$refs.img.clearFiles();}if(this.$refs.file) {this.$refs.file.clearFiles();}})},del(id) {this.request.delete("/goods/" + id).then(res => {if (res.code === '200') {this.$message.success("删除成功")this.load()} else {this.$message.error("删除失败")}})},handleSelectionChange(val) {console.log(val)this.multipleSelection = val},delBatch() {if (!this.multipleSelection.length) {this.$message.error("请选择需要删除的数据")return}let ids = this.multipleSelection.map(v => v.id) // [{}, {}, {}] => [1,2,3]this.request.post("/goods/del/batch", ids).then(res => {if (res.code === '200') {this.$message.success("批量删除成功")this.load()} else {this.$message.error("批量删除失败")}})},reset() {this.name = ""this.load()},handleSizeChange(pageSize) {console.log(pageSize)this.pageSize = pageSizethis.load()},handleCurrentChange(pageNum) {console.log(pageNum)this.pageNum = pageNumthis.load()},handleFileUploadSuccess(res) {this.form.file = res},handleImgUploadSuccess(res) {this.form.img = res},download(url) {window.open(url)},exp() {window.open("http://localhost:9090/goods/export")},handleExcelImportSuccess() {this.$message.success("导入成功")this.load()}}
}
</script><style>
.headerBg {background: #eee!important;
}
</style>
Orders.vue
<template><div><div style="margin: 10px 0"><el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
<!-- <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
<!-- <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>--><el-button class="ml-5" type="primary" @click="load">搜索</el-button><el-button type="warning" @click="reset">重置</el-button></div><div style="margin: 10px 0"><el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button><el-popconfirmclass="ml-5"confirm-button-text='确定'cancel-button-text='我再想想'icon="el-icon-info"icon-color="red"title="您确定批量删除这些数据吗?"@confirm="delBatch"><el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button></el-popconfirm><!-- <el-upload action="http://localhost:9090/orders/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block"><el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button></el-upload><el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> --></div><el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange"><el-table-column type="selection" width="55"></el-table-column><el-table-column prop="id" label="ID" width="80" sortable></el-table-column><el-table-column prop="no" label="订单编号"></el-table-column><el-table-column prop="name" label="名称"></el-table-column><el-table-column prop="time" label="订单时间"></el-table-column><el-table-column prop="state" label="支付状态"></el-table-column><el-table-column prop="total" label="订单总价"></el-table-column><el-table-column prop="paymentTime" label="支付时间"></el-table-column><el-table-column prop="alipayNo" label="支付宝宝流水号"></el-table-column><el-table-column prop="returnTime" label="退款时间"></el-table-column><el-table-column label="支付" width="180" align="center"><template v-slot="scope"><el-button type="primary" @click="pay(scope.row)" :disabled="scope.row.state !== '待支付'">支 付</el-button><el-button type="danger" @click="returnPay(scope.row)" :disabled="scope.row.state !== '已支付'">退款</el-button></template></el-table-column><el-table-column label="操作" width="180" align="center"><template slot-scope="scope"><el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button><el-popconfirmclass="ml-5"confirm-button-text='确定'cancel-button-text='我再想想'icon="el-icon-info"icon-color="red"title="您确定删除吗?"@confirm="del(scope.row.id)"><el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button></el-popconfirm></template></el-table-column></el-table><div style="padding: 10px 0"><el-pagination@size-change="handleSizeChange"@current-change="handleCurrentChange":current-page="pageNum":page-sizes="[2, 5, 10, 20]":page-size="pageSize"layout="total, sizes, prev, pager, next, jumper":total="total"></el-pagination></div><el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false"><el-form label-width="100px" size="small" style="width: 90%"><el-form-item label="订单编号"><el-input v-model="form.no" autocomplete="off"></el-input></el-form-item><el-form-item label="名称"><el-input v-model="form.name" autocomplete="off"></el-input></el-form-item><el-form-item label="订单时间"><el-date-picker v-model="form.time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker></el-form-item><el-form-item label="支付状态"><el-input v-model="form.state" autocomplete="off"></el-input></el-form-item><el-form-item label="订单总价"><el-input v-model="form.total" autocomplete="off"></el-input></el-form-item></el-form><div slot="footer" class="dialog-footer"><el-button @click="dialogFormVisible = false">取 消</el-button><el-button type="primary" @click="save">确 定</el-button></div></el-dialog></div>
</template><script>
export default {name: "Orders",data() {return {tableData: [],total: 0,pageNum: 1,pageSize: 10,name: "",form: {},dialogFormVisible: false,multipleSelection: [],user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}}},created() {this.load()},methods: {pay(row) {const url = `http://localhost:9090/alipay/pay?subject=${row.name}&traceNo=${row.no}&totalAmount=${row.total}`window.open(url); // 得到一个url,这个url就是支付宝支付的界面url, 新窗口打开这个url就可以了},returnPay(row) {const url = `http://localhost:9090/alipay/return?totalAmount=${row.total}&alipayTraceNo=${row.alipayNo}&traceNo=${row.no}`this.request.get(url).then(res => {if(res.code === '200') {this.$message.success("退款成功")} else {this.$message.error("退款失败")}this.load()})},load() {this.request.get("/orders/page", {params: {pageNum: this.pageNum,pageSize: this.pageSize,name: this.name,}}).then(res => {this.tableData = res.data.recordsthis.total = res.data.total})},save() {this.request.post("/orders", this.form).then(res => {if (res.code === '200') {this.$message.success("保存成功")this.dialogFormVisible = falsethis.load()} else {this.$message.error("保存失败")}})},handleAdd() {this.dialogFormVisible = truethis.form = {}this.$nextTick(() => {if(this.$refs.img) {this.$refs.img.clearFiles();}if(this.$refs.file) {this.$refs.file.clearFiles();}})},handleEdit(row) {this.form = JSON.parse(JSON.stringify(row))this.dialogFormVisible = truethis.$nextTick(() => {if(this.$refs.img) {this.$refs.img.clearFiles();}if(this.$refs.file) {this.$refs.file.clearFiles();}})},del(id) {this.request.delete("/orders/" + id).then(res => {if (res.code === '200') {this.$message.success("删除成功")this.load()} else {this.$message.error("删除失败")}})},handleSelectionChange(val) {console.log(val)this.multipleSelection = val},delBatch() {if (!this.multipleSelection.length) {this.$message.error("请选择需要删除的数据")return}let ids = this.multipleSelection.map(v => v.id) // [{}, {}, {}] => [1,2,3]this.request.post("/orders/del/batch", ids).then(res => {if (res.code === '200') {this.$message.success("批量删除成功")this.load()} else {this.$message.error("批量删除失败")}})},reset() {this.name = ""this.load()},handleSizeChange(pageSize) {console.log(pageSize)this.pageSize = pageSizethis.load()},handleCurrentChange(pageNum) {console.log(pageNum)this.pageNum = pageNumthis.load()},handleFileUploadSuccess(res) {this.form.file = res},handleImgUploadSuccess(res) {this.form.img = res},download(url) {window.open(url)},exp() {window.open("http://localhost:9090/orders/export")},handleExcelImportSuccess() {this.$message.success("导入成功")this.load()}}
}
</script><style>
.headerBg {background: #eee!important;
}
</style>