SpringMVC+Spring+Mybatis實(shí)現(xiàn)支付寶支付功能的示例代碼
本博客詳細(xì)介紹了如何使用ssm框架實(shí)現(xiàn)支付寶支付功能。本文章分為兩大部分,分別是「支付寶測(cè)試環(huán)境代碼測(cè)試」和「將支付寶支付整合到ssm框架」,詳細(xì)的代碼和圖文解釋,自己實(shí)踐的時(shí)候一定仔細(xì)閱讀相關(guān)文檔。
教程源代碼:https://github.com/OUYANGSIHAI/sihai-maven-ssm-alipay
一、支付寶測(cè)試環(huán)境代碼測(cè)試:
1、下載電腦網(wǎng)站的官方demo以及查看參考相關(guān)文檔:
地址:https://docs.open.alipay.com/270/106291/

2、下載解壓導(dǎo)入ecplise:

readmetxt仔細(xì)看一下,只有一個(gè)Java配置類,其余都是JSP頁面。
3、配置AlipayConfig:
(1)注冊(cè)螞蟻金服開發(fā)者賬號(hào)(免費(fèi))
注冊(cè)地址:https://open.alipay.com,選擇右上角的”免費(fèi)入駐”→“自研開發(fā)者”,使用你的支付寶賬戶登錄,完善個(gè)人信息。
(2)設(shè)置app_id 和 gatewayUrl:


其中密鑰需要自己生成,APPID和支付寶網(wǎng)關(guān)已經(jīng)給好了,網(wǎng)關(guān)有dev字樣,表明是用于開發(fā)測(cè)試。
(3)設(shè)置密鑰:

點(diǎn)擊“生成方法”,打開界面如下:

下載上圖的密鑰生成工具,解壓打開,執(zhí)行批處理程序,打開密鑰生成工具,選擇2048位生成密鑰:

如果沒有設(shè)置過,此時(shí)下圖顯示文本是"設(shè)置應(yīng)用公鑰",我這里是已經(jīng)設(shè)置過得:

設(shè)置方法,“打開密鑰文件路徑”:

復(fù)制應(yīng)用公鑰2048.txt中的內(nèi)容到點(diǎn)擊“設(shè)置應(yīng)用公鑰”的彈出框中,保存:


①設(shè)置商戶密鑰:(merchant_private_key)
復(fù)制應(yīng)用私鑰2048.txt 中的內(nèi)容到AlipayConfig類的merchant_private_key屬性中。
②設(shè)置支付寶公鑰:(alipay_public_key)

點(diǎn)擊如上圖鏈接,復(fù)制彈出框里面的內(nèi)容到AlipayConfig類的alipay_public_key屬性中。
如果這個(gè)設(shè)置不對(duì),結(jié)果是:支付成功,但是驗(yàn)簽是失敗。
如果是正式環(huán)境,需要上傳到對(duì)應(yīng)的應(yīng)用中,參考文件:https://docs.open.alipay.com/291/105972/

(4)服務(wù)器異步通知頁面路徑(notify_url):
如果沒有改名,修改IP和端口號(hào)就可以了,我自己的如下:
http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/notify_url.jsp
(5) 頁面跳轉(zhuǎn)同步通知頁面的路徑(return_url):
http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/return_url.jsp
4、測(cè)試運(yùn)行:


測(cè)試用的支付寶買家賬戶可以在"沙箱賬號(hào)"這個(gè)頁面可以找到:

支付成功后,驗(yàn)簽結(jié)果:

問題解決:
由于我們使用的是沙箱測(cè)試環(huán)境,測(cè)試環(huán)境和正式上線的環(huán)境的網(wǎng)關(guān)是不一樣的,如果配置錯(cuò)誤,會(huì)出現(xiàn)你appid錯(cuò)誤的問題。配置如下:
// 支付寶網(wǎng)關(guān)(測(cè)試環(huán)境) public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; // 支付寶網(wǎng)關(guān)(正式線上環(huán)境) //public static String gatewayUrl = https://openapi.alipay.com/gateway.do;
二、將支付寶支付整合到ssm框架中:
1、項(xiàng)目搭建與項(xiàng)目架構(gòu):
(1)ssm項(xiàng)目的搭建可以參考我以前寫過的這篇博客:http://www.dbjr.com.cn/article/161244.htm
在pom.xml文件中引入依賴:
<!-- alipay支付寶 sdk --> <!-- https://mvnrepository.com/artifact/com.alipay.sdk/alipay-sdk-java --> <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>3.1.0</version> </dependency>
項(xiàng)目架構(gòu):

整合到ssm,我們需要像沙箱測(cè)試環(huán)境一樣,需要支付的配置信息:

2、數(shù)據(jù)庫代碼:
user:用戶表
order:支付產(chǎn)生的訂單
flow:流水賬
product:商品表,用于模擬購買商品
drop table if exists user; /*==============================================================*/ /* Table: user */ /*==============================================================*/ create table user ( id varchar(20) not null, username varchar(128), sex varchar(20), primary key (id) ); alter table user comment '用戶表'; CREATE TABLE `flow` ( `id` varchar(20) NOT NULL, `flow_num` varchar(30) DEFAULT NULL COMMENT '流水號(hào)', `order_num` varchar(20) DEFAULT NULL COMMENT '訂單號(hào)', `product_id` varchar(20) DEFAULT NULL COMMENT '產(chǎn)品主鍵ID', `paid_amount` varchar(11) DEFAULT NULL COMMENT '支付金額', `paid_method` int(11) DEFAULT NULL COMMENT '支付方式\r\n 1:支付寶\r\n 2:微信', `buy_counts` int(11) DEFAULT NULL COMMENT '購買個(gè)數(shù)', `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='流水表'; CREATE TABLE `orders` ( `id` varchar(20) NOT NULL, `order_num` varchar(20) DEFAULT NULL COMMENT '訂單號(hào)', `order_status` varchar(20) DEFAULT NULL COMMENT '訂單狀態(tài)\r\n 10:待付款\r\n 20:已付款', `order_amount` varchar(11) DEFAULT NULL COMMENT '訂單金額', `paid_amount` varchar(11) DEFAULT NULL COMMENT '實(shí)際支付金額', `product_id` varchar(20) DEFAULT NULL COMMENT '產(chǎn)品表外鍵ID', `buy_counts` int(11) DEFAULT NULL COMMENT '產(chǎn)品購買的個(gè)數(shù)', `create_time` datetime DEFAULT NULL COMMENT '訂單創(chuàng)建時(shí)間', `paid_time` datetime DEFAULT NULL COMMENT '支付時(shí)間', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='訂單表'; CREATE TABLE `product` ( `id` varchar(20) NOT NULL, `name` varchar(20) DEFAULT NULL COMMENT '產(chǎn)品名稱', `price` varchar(11) DEFAULT NULL COMMENT '價(jià)格', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='產(chǎn)品表 ';
3、dao數(shù)據(jù)接口層:
這里就不介紹了,可以使用`逆向工程`生成,以訂單order為例給出:
public interface OrdersMapper {
int countByExample(OrdersExample example);
int deleteByExample(OrdersExample example);
int deleteByPrimaryKey(String id);
int insert(Orders record);
int insertSelective(Orders record);
List<Orders> selectByExample(OrdersExample example);
Orders selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") Orders record, @Param("example") OrdersExample example);
int updateByExample(@Param("record") Orders record, @Param("example") OrdersExample example);
int updateByPrimaryKeySelective(Orders record);
int updateByPrimaryKey(Orders record);
}
4、service層:
以訂單order為例給出:
/**
* 訂單操作 service
*/
public interface OrdersService {
/**
* 新增訂單
*/
public void saveOrder(Orders order);
/**
* @Description: 修改訂單狀態(tài),改為 支付成功,已付款; 同時(shí)新增支付流水
*/
public void updateOrderStatus(String orderId, String alpayFlowNum, String paidAmount);
/**
* 獲取訂單
*/
public Orders getOrderById(String orderId);
}
5、支付寶controller(支付流程):
支付流程圖:

代碼如下:
/**
* @Description: controller
*/
@Controller
@RequestMapping("/alipay")
public class AlipayController {
final static Logger log = LoggerFactory.getLogger(AlipayController.class);
@Autowired
private ProductService productService;
@Autowired
private OrdersService orderService;
@Autowired
private Sid sid;
/**
* 獲取產(chǎn)品列表
*/
@RequestMapping(value = "/products")
public ModelAndView products() throws Exception {
List<Product> pList = productService.getProducts();
ModelAndView mv = new ModelAndView("products");
mv.addObject("pList", pList);
return mv;
}
/**
* 進(jìn)入確認(rèn)頁面
*/
@RequestMapping(value = "/goConfirm")
public ModelAndView goConfirm(String productId) throws Exception {
Product p = productService.getProductById(productId);
ModelAndView mv = new ModelAndView("goConfirm");
mv.addObject("p", p);
return mv;
}
/**
* 分段提交
* 第一段:保存訂單
*/
@RequestMapping(value = "/createOrder")
@ResponseBody
public LeeJSONResult createOrder(Orders order) throws Exception {
Product p = productService.getProductById(order.getProductId());
String orderId = sid.nextShort();
order.setId(orderId);
order.setOrderNum(orderId);
order.setCreateTime(new Date());
order.setOrderAmount(String.valueOf(Float.valueOf(p.getPrice()) * order.getBuyCounts()));
order.setOrderStatus(OrderStatusEnum.WAIT_PAY.key);
orderService.saveOrder(order);
return LeeJSONResult.ok(orderId);
}
/**
* 分段提交
* 第二段
*/
@RequestMapping(value = "/goPay")
public ModelAndView goPay(String orderId) throws Exception {
Orders order = orderService.getOrderById(orderId);
Product p = productService.getProductById(order.getProductId());
ModelAndView mv = new ModelAndView("goPay");
mv.addObject("order", order);
mv.addObject("p", p);
return mv;
}
/**
* @Description: 前往支付寶第三方網(wǎng)關(guān)進(jìn)行支付
* @version V1.0
*/
@RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
@ResponseBody
public String goAlipay(String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception {
Orders order = orderService.getOrderById(orderId);
Product product = productService.getProductById(order.getProductId());
//獲得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
//設(shè)置請(qǐng)求參數(shù)
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商戶訂單號(hào),商戶網(wǎng)站訂單系統(tǒng)中唯一訂單號(hào),必填
String out_trade_no = orderId;
//付款金額,必填
String total_amount = order.getOrderAmount();
//訂單名稱,必填
String subject = product.getName();
//商品描述,可空
String body = "用戶訂購商品個(gè)數(shù):" + order.getBuyCounts();
// 該筆訂單允許的最晚付款時(shí)間,逾期將關(guān)閉交易。取值范圍:1m~15d。m-分鐘,h-小時(shí),d-天,1c-當(dāng)天(1c-當(dāng)天的情況下,無論交易何時(shí)創(chuàng)建,都在0點(diǎn)關(guān)閉)。 該參數(shù)數(shù)值不接受小數(shù)點(diǎn), 如 1.5h,可轉(zhuǎn)換為 90m。
String timeout_express = "1c";
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\"}");
//請(qǐng)求
String result = alipayClient.pageExecute(alipayRequest).getBody();
return result;
}
/**
* @Description: 支付寶同步通知頁面
*/
@RequestMapping(value = "/alipayReturnNotice")
public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
log.info("支付成功, 進(jìn)入同步通知接口...");
//獲取支付寶GET過來反饋信息
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] + ",";
}
//亂碼解決,這段代碼在出現(xiàn)亂碼時(shí)使用
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = false;
try{
signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //調(diào)用SDK驗(yàn)證簽名
}catch (Exception e) {
System.out.println("SDK驗(yàn)證簽名出現(xiàn)異常");
}
ModelAndView mv = new ModelAndView("alipaySuccess");
//——請(qǐng)?jiān)谶@里編寫您的程序(以下代碼僅作參考)——
if(signVerified) {
//商戶訂單號(hào)
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付寶交易號(hào)
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//付款金額
String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
// 修改叮當(dāng)狀態(tài),改為 支付成功,已付款; 同時(shí)新增支付流水
orderService.updateOrderStatus(out_trade_no, trade_no, total_amount);
Orders order = orderService.getOrderById(out_trade_no);
Product product = productService.getProductById(order.getProductId());
log.info("********************** 支付成功(支付寶同步通知) **********************");
log.info("* 訂單號(hào): {}", out_trade_no);
log.info("* 支付寶交易號(hào): {}", trade_no);
log.info("* 實(shí)付金額: {}", total_amount);
log.info("* 購買產(chǎn)品: {}", product.getName());
log.info("***************************************************************");
mv.addObject("out_trade_no", out_trade_no);
mv.addObject("trade_no", trade_no);
mv.addObject("total_amount", total_amount);
mv.addObject("productName", product.getName());
}else {
log.info("支付, 驗(yàn)簽失敗...");
}
return mv;
}
/**
* @Description: 支付寶異步 通知頁面
*/
@RequestMapping(value = "/alipayNotifyNotice")
@ResponseBody
public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
log.info("支付成功, 進(jìn)入異步通知接口...");
//獲取支付寶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] + ",";
}
//亂碼解決,這段代碼在出現(xiàn)亂碼時(shí)使用
// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //調(diào)用SDK驗(yàn)證簽名
//——請(qǐng)?jiān)谶@里編寫您的程序(以下代碼僅作參考)——
/* 實(shí)際驗(yàn)證過程建議商戶務(wù)必添加以下校驗(yàn):
1、需要驗(yàn)證該通知數(shù)據(jù)中的out_trade_no是否為商戶系統(tǒng)中創(chuàng)建的訂單號(hào),
2、判斷total_amount是否確實(shí)為該訂單的實(shí)際金額(即商戶訂單創(chuàng)建時(shí)的金額),
3、校驗(yàn)通知中的seller_id(或者seller_email) 是否為out_trade_no這筆單據(jù)的對(duì)應(yīng)的操作方(有的時(shí)候,一個(gè)商戶可能有多個(gè)seller_id/seller_email)
4、驗(yàn)證app_id是否為該商戶本身。
*/
if(signVerified) {//驗(yàn)證成功
//商戶訂單號(hào)
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付寶交易號(hào)
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//交易狀態(tài)
String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
//付款金額
String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
if(trade_status.equals("TRADE_FINISHED")){
//判斷該筆訂單是否在商戶網(wǎng)站中已經(jīng)做過處理
//如果沒有做過處理,根據(jù)訂單號(hào)(out_trade_no)在商戶網(wǎng)站的訂單系統(tǒng)中查到該筆訂單的詳細(xì),并執(zhí)行商戶的業(yè)務(wù)程序
//如果有做過處理,不執(zhí)行商戶的業(yè)務(wù)程序
//注意: 尚自習(xí)的訂單沒有退款功能, 這個(gè)條件判斷是進(jìn)不來的, 所以此處不必寫代碼
//退款日期超過可退款期限后(如三個(gè)月可退款),支付寶系統(tǒng)發(fā)送該交易狀態(tài)通知
}else if (trade_status.equals("TRADE_SUCCESS")){
//判斷該筆訂單是否在商戶網(wǎng)站中已經(jīng)做過處理
//如果沒有做過處理,根據(jù)訂單號(hào)(out_trade_no)在商戶網(wǎng)站的訂單系統(tǒng)中查到該筆訂單的詳細(xì),并執(zhí)行商戶的業(yè)務(wù)程序
//如果有做過處理,不執(zhí)行商戶的業(yè)務(wù)程序
//注意:
//付款完成后,支付寶系統(tǒng)發(fā)送該交易狀態(tài)通知
// 修改叮當(dāng)狀態(tài),改為 支付成功,已付款; 同時(shí)新增支付流水
orderService.updateOrderStatus(out_trade_no, trade_no, total_amount);
Orders order = orderService.getOrderById(out_trade_no);
Product product = productService.getProductById(order.getProductId());
log.info("********************** 支付成功(支付寶異步通知) **********************");
log.info("* 訂單號(hào): {}", out_trade_no);
log.info("* 支付寶交易號(hào): {}", trade_no);
log.info("* 實(shí)付金額: {}", total_amount);
log.info("* 購買產(chǎn)品: {}", product.getName());
log.info("***************************************************************");
}
log.info("支付成功...");
}else {//驗(yàn)證失敗
log.info("支付, 驗(yàn)簽失敗...");
}
return "success";
}
}
6、測(cè)試、啟動(dòng)項(xiàng)目:
(1)在瀏覽器地址欄輸入http://localhost:8080,會(huì)進(jìn)入商品products.jsp頁面,如下:


點(diǎn)擊上面的購買,進(jìn)入到訂單goConfirm.jsp頁面:

下面是頁面代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script src="<%=request.getContextPath() %>/static/js/jquery.min.js" type="text/javascript"></script>
<html>
<head>
</head>
<body>
<form action="<%=request.getContextPath() %>/alipay/createOrder.action" method="post">
<input type="hidden" id="productId" name="productId" value="${p.id }" />
<table>
<tr>
<td>
產(chǎn)品編號(hào): ${p.id }
</td>
</tr>
<td>
產(chǎn)品名稱: ${p.name }
</td>
<tr>
</tr>
<td>
產(chǎn)品價(jià)格: ${p.price }
</td>
<tr>
</tr>
<td>
購買個(gè)數(shù): <input id="buyCounts" name="buyCounts"/>
</td>
</tr>
</tr>
<td>
<input type="submit" value="form提交,生成訂單" />
<input type="button" value="ajax提交,生成訂單" onclick="createOrder()" />
</td>
</tr>
</table>
</form>
<input type="hidden" id="hdnContextPath" name="hdnContextPath" value="<%=request.getContextPath() %>"/>
</body>
</html>
<script type="text/javascript">
var hdnContextPath = $("#hdnContextPath").val();
function createOrder() {
$.ajax({
url: hdnContextPath + "/alipay/createOrder.action",
type: "POST",
data: {"productId": $("#productId").val(), "buyCounts": $("#buyCounts").val()},
dataType: "json",
success: function(data) {
if(data.status == 200 && data.msg == "OK") {
debugger;
// 提交訂單成功后, 進(jìn)入購買頁面
window.location.href = hdnContextPath + "/alipay/goPay.action?orderId=" + data.data;
} else {
alert(data.msg);
console.log(JSON.stringify(data));
}
}
});
}
</script>
之后,填寫個(gè)數(shù),然后點(diǎn)擊生成訂單,調(diào)用AlipayController.java中的如下代碼:
/**
* 分段提交
* 第一段:保存訂單
*/
@RequestMapping(value = "/createOrder")
@ResponseBody
public LeeJSONResult createOrder(Orders order) throws Exception {
Product p = productService.getProductById(order.getProductId());
String orderId = sid.nextShort();
order.setId(orderId);
order.setOrderNum(orderId);
order.setCreateTime(new Date());
order.setOrderAmount(String.valueOf(Float.valueOf(p.getPrice()) * order.getBuyCounts()));
order.setOrderStatus(OrderStatusEnum.WAIT_PAY.key);
orderService.saveOrder(order);
return LeeJSONResult.ok(orderId);
}
根據(jù)SID(生成id的工具)等信息生成訂單,保存到數(shù)據(jù)庫。
接著自動(dòng)進(jìn)入到支付頁面:

調(diào)用AlipayController.java中的如下代碼:
/**
* 分段提交
* 第二段
*/
@RequestMapping(value = "/goPay")
public ModelAndView goPay(String orderId) throws Exception {
Orders order = orderService.getOrderById(orderId);
Product p = productService.getProductById(order.getProductId());
ModelAndView mv = new ModelAndView("goPay");
mv.addObject("order", order);
mv.addObject("p", p);
return mv;
}
然后我們選擇支付寶支付,就進(jìn)入到了我們的支付頁面了:

支付過程中,調(diào)用了如下代碼:
/**
* @Description: 第三段 前往支付寶第三方網(wǎng)關(guān)進(jìn)行支付
* @version V1.0
*/
@RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
@ResponseBody
public String goAlipay(String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception {
Orders order = orderService.getOrderById(orderId);
Product product = productService.getProductById(order.getProductId());
//獲得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
//設(shè)置請(qǐng)求參數(shù)
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl(AlipayConfig.return_url);
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//商戶訂單號(hào),商戶網(wǎng)站訂單系統(tǒng)中唯一訂單號(hào),必填
String out_trade_no = orderId;
//付款金額,必填
String total_amount = order.getOrderAmount();
//訂單名稱,必填
String subject = product.getName();
//商品描述,可空
String body = "用戶訂購商品個(gè)數(shù):" + order.getBuyCounts();
// 該筆訂單允許的最晚付款時(shí)間,逾期將關(guān)閉交易。取值范圍:1m~15d。m-分鐘,h-小時(shí),d-天,1c-當(dāng)天(1c-當(dāng)天的情況下,無論交易何時(shí)創(chuàng)建,都在0點(diǎn)關(guān)閉)。 該參數(shù)數(shù)值不接受小數(shù)點(diǎn), 如 1.5h,可轉(zhuǎn)換為 90m。
String timeout_express = "1c";
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\"}");
//請(qǐng)求
String result = alipayClient.pageExecute(alipayRequest).getBody();
return result;
}
支付完成,會(huì)進(jìn)入成功頁面:

到此,利用ssm框架使用支付寶支付功能就整合完成了。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Struts2實(shí)現(xiàn)防止表單重復(fù)提交
這篇文章主要介紹了基于Struts2實(shí)現(xiàn)防止表單重復(fù)提交,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
java中instanceof與Class的等價(jià)性代碼示例
這篇文章主要介紹了java中instanceof與Class的等價(jià)性代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Spring裝配Bean之用Java代碼安裝配置bean詳解
這篇文章主要給大家介紹了關(guān)于Spring裝配Bean之用Java代碼安裝配置bean的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10
Java服務(wù)假死之生產(chǎn)事故的排查與優(yōu)化問題
在服務(wù)器上通過curl命令調(diào)用一個(gè)Java服務(wù)的查詢接口,半天沒有任何響應(yīng),怎么進(jìn)行這一現(xiàn)象排查呢,下面小編給大家記一次生產(chǎn)事故的排查與優(yōu)化——Java服務(wù)假死問題,感興趣的朋友一起看看吧2022-07-07

