Integrating Alipay Payment into an SSM (Spring + Spring MVC + MyBatis) Framework

This tutorial provides a step‑by‑step guide for configuring the Alipay sandbox, generating keys, setting up the required database tables, and integrating Alipay payment APIs into a Java SSM project, complete with code snippets, configuration details, and troubleshooting tips.

Java Captain
Java Captain
Java Captain
Integrating Alipay Payment into an SSM (Spring + Spring MVC + MyBatis) Framework

Preface

This tutorial details how to implement Alipay payment using the SSM framework. It is divided into two parts: testing the Alipay sandbox environment and integrating Alipay into an SSM project. The full source code is available at GitHub .

1. Alipay Test Environment Code

1.1 Download the official demo

Download: Alipay official demo

1.2 Import into Eclipse

Read the readme.txt carefully. The demo contains a single Java configuration class and the rest are JSP pages.

1.3 Configure AlipayConfig

(1) Register a free Ant Financial developer account at open.alipay.com , log in with your Alipay account, complete personal information, and select a service type.

(2) Set app_id and gatewayUrl (the gateway contains the "dev" suffix, indicating a sandbox environment).

(3) Generate the RSA key pair (2048 bits) using the provided tool, then copy the generated public and private keys into the configuration fields.

Copy the content of 应用公钥2048.txt into the "Set Application Public Key" dialog and save.

Merchant private key (merchant_private_key): copy the content of 应用私钥2048.txt .

Alipay public key (alipay_public_key): copy the content shown in the screenshot.

If the keys are incorrect the payment will succeed but signature verification will fail.

1.4 Server asynchronous notification URL (notify_url)

Example (local):

http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/notify_url.jsp

1.5 Synchronous return URL (return_url)

Example (local):

http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/return_url.jsp

1.6 Test run

The sandbox buyer account can be found on the "Sandbox Account" page.

After a successful payment the signature verification result is displayed.

Problem solving

When using the sandbox, the gateway URL differs from the production environment; an incorrect gateway causes an "appid error".

2. Integrating Alipay into the SSM Framework

2.1 Project architecture

Framework: spring + springmvc + mybatis

Database: mysql

Deployment: tomcat 9.0

Development: jdk9, IntelliJ IDEA

Payments: Alipay, WeChat Pay

The payment configuration must be updated in the same way as the sandbox.

2.2 Database schema

The following tables are required:

user – user information

order – payment order

flow – transaction flow

product – product catalog for demo purchases

drop table if exists user;
/*==============================================================*/
/* Table: user */
/*==============================================================*/
create table user (
    id varchar(20) not null,
    username varchar(128),
    sex varchar(20),
    primary key (id)
) comment '用户表';

CREATE TABLE `flow` (
  `id` varchar(20) NOT NULL,
  `flow_num` varchar(20) DEFAULT NULL COMMENT '流水号',
  `order_num` varchar(20) DEFAULT NULL COMMENT '订单号',
  `product_id` varchar(20) DEFAULT NULL COMMENT '产品主键ID',
  `paid_amount` varchar(11) DEFAULT NULL COMMENT '支付金额',
  `paid_method` int(11) DEFAULT NULL COMMENT '支付方式
            1:支付宝
            2:微信',
  `buy_counts` int(11) DEFAULT NULL COMMENT '购买个数',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  primary key (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='流水表';

CREATE TABLE `orders` (
  `id` varchar(20) NOT NULL,
  `order_num` varchar(20) DEFAULT NULL COMMENT '订单号',
  `order_status` varchar(20) DEFAULT NULL COMMENT '订单状态
            10:待付款
            20:已付款',
  `order_amount` varchar(11) DEFAULT NULL COMMENT '订单金额',
  `paid_amount` varchar(11) DEFAULT NULL COMMENT '实际支付金额',
  `product_id` varchar(20) DEFAULT NULL COMMENT '产品表外键ID',
  `buy_counts` int(11) DEFAULT NULL COMMENT '产品购买的个数',
  `create_time` datetime DEFAULT NULL COMMENT '订单创建时间',
  `paid_time` datetime DEFAULT NULL COMMENT '支付时间',
  primary key (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';

CREATE TABLE `product` (
  `id` varchar(20) NOT NULL,
  `name` varchar(20) DEFAULT NULL COMMENT '产品名称',
  `price` varchar(11) DEFAULT NULL COMMENT '价格',
  primary key (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='产品表';

2.3 DAO layer

Typical MyBatis mapper for the orders table (CRUD operations). The code can be generated with a generic mapper or MyBatis Generator.

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);
}

2.4 Service layer

/**
 * Order service interface
 */
public interface OrdersService {
    /**
     * Save a new order
     */
    void saveOrder(Orders order);

    /**
     * Update order status after payment and record the flow
     */
    void updateOrderStatus(String orderId, String alpayFlowNum, String paidAmount);

    /**
     * Retrieve an order by its ID
     */
    Orders getOrderById(String orderId);
}

2.5 Alipay Controller (payment flow)

Payment flow diagram:

After starting the project, navigate to http://localhost:8080/ to see the product list page.

Product page (products.jsp) code:

<%@ 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" %>
<html>
<head></head>
<body>
<table>
<tr><td>产品编号</td><td>产品名称</td><td>产品价格</td><td>操作</td></tr>
<c:forEach items="${pList }" var="p">
<tr>
<td>${p.id }</td>
<td>${p.name }</td>
<td>${p.price }</td>
<td><a href="<%=request.getContextPath() %>/alipay/goConfirm.action?productId=${p.id }">购买</a></td>
</tr>
</c:forEach>
</table>
<input type="hidden" id="hdnContextPath" name="hdnContextPath" value="<%=request.getContextPath() %>"/>
<script type="text/javascript">
$(document).ready(function(){
    var hdnContextPath = $("#hdnContextPath").val();
});
</script>
</body>
</html>

Clicking "购买" leads to the order creation page, where the user specifies the quantity and generates an order.

The order is saved using the generated SID (ID tool) and then the user selects Alipay as the payment method.

Alipay controller code (simplified):

@RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
@ResponseBody
public String goAlipay(String orderId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    Orders order = orderService.getOrderById(orderId);
    Product product = productService.getProductById(order.getProductId());
    // Initialize Alipay client
    AlipayClient alipayClient = new DefaultAlipayClient(
        AlipayConfig.gatewayUrl,
        AlipayConfig.app_id,
        AlipayConfig.merchant_private_key,
        "json",
        AlipayConfig.charset,
        AlipayConfig.alipay_public_key,
        AlipayConfig.sign_type);
    // Set request parameters
    AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
    alipayRequest.setReturnUrl(AlipayConfig.return_url);
    alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
    String out_trade_no = orderId;
    String total_amount = order.getOrderAmount();
    String subject = product.getName();
    String body = "用户订购商品个数:" + order.getBuyCounts();
    String timeout_express = "1c"; // same day closure
    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();
    return result;
}

The above code is identical to the official Alipay demo; copy it into your SSM project and adjust the configuration values.

That completes the full integration of Alipay payment into an SSM application.

PS: If you find this guide helpful, feel free to like and share.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaspringMyBatisPayment IntegrationAlipaySSM
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.