Backend Development 11 min read

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

This tutorial provides a step‑by‑step guide on configuring the Alipay sandbox, generating keys, setting up notification URLs, creating the required database tables, and integrating the full payment flow—including DAO, service, controller, and JSP code—into a Java SSM backend project.

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

This tutorial explains how to implement Alipay payment within an SSM (Spring, Spring MVC, MyBatis) framework. It begins with downloading the official Alipay demo, importing it into Eclipse, and configuring the AlipayConfig with app_id, gateway URL, and generated RSA keys.

The guide shows how to generate merchant private keys and Alipay public keys using the provided key‑generation tool, and how to set the merchant_private_key , app_id , and alipay_public_key in the configuration file. It also details the server asynchronous notification URL ( notify_url ) and the synchronous return URL ( return_url ).

After configuring the sandbox, the tutorial walks through testing the payment flow, verifying successful payments, and troubleshooting common issues such as mismatched gateway URLs.

Next, the project architecture is presented: a Spring‑based backend with MySQL, Tomcat 9, JDK 9, and Maven. The required database schema includes user , order , flow , and product tables. Sample SQL for creating these tables is provided:

DROP TABLE IF EXISTS 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 '支付方式\n 1:支付宝\n 2:微信', `buy_counts` INT(11) DEFAULT NULL COMMENT '购买个数', `create_time` DATETIME DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='流水表';
... (additional table definitions omitted for brevity) ...

The DAO layer is illustrated with a simple MyBatis mapper interface:

public interface OrdersMapper {
    int countByExample(OrdersExample example);
    int deleteByExample(OrdersExample example);
    int deleteByPrimaryKey(String id);
    int insert(Orders record);
    int insertSelective(Orders record);
    List
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);
}

The service layer defines business operations for orders:

public interface OrdersService {
    void saveOrder(Orders order);
    void updateOrderStatus(String orderId, String alpayFlowNum, String paidAmount);
    Orders getOrderById(String orderId);
}

A JSP page ( products.jsp ) displays products and provides a “Buy” link that triggers order creation. The essential JSP markup is:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <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="${pageContext.request.contextPath}/alipay/goConfirm.action?productId=${p.id}">购买</a></td>
        </tr>
      </c:forEach>
    </table>
    <input type="hidden" id="hdnContextPath" name="hdnContextPath" value="${pageContext.request.contextPath}" />
  </body>
</html>

The core payment logic resides in AlipayController.java . The controller builds an AlipayClient , sets request parameters (order ID, amount, subject, body, timeout), and returns the generated HTML form to redirect the user to Alipay’s gateway:

@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());
    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 = orderId;
    String total_amount = order.getOrderAmount();
    String subject = product.getName();
    String body = "用户订购商品个数:" + order.getBuyCounts();
    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\"}");
    String result = alipayClient.pageExecute(alipayRequest).getBody();
    return result;
}

By following these steps—setting up the sandbox, configuring keys, creating the database schema, implementing DAO, service, controller, and JSP layers—developers can successfully integrate Alipay payment into an SSM‑based Java web application.

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

login 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.