Step-by-Step Alipay Payment Integration in Java with Spring Boot
This guide walks through configuring the Alipay sandbox, adding Maven dependencies, setting up application.yml, implementing Java configuration classes, creating controller endpoints for payment, handling asynchronous callbacks, processing refunds, and using RabbitMQ delayed queues to auto‑cancel unpaid orders, all with complete code examples.
This article provides a comprehensive tutorial for integrating Alipay payment services into a Java Spring Boot backend.
Web Operation Steps (Alipay Sandbox)
1. Log in to the Alipay Open Platform sandbox environment.
2. Enter the sandbox and configure the interface signing method, choosing the system default key.
3. Set up an application gateway to receive asynchronous notifications from Alipay.
4. Generate your own RSA key pair if needed.
IDEA Project Setup
1. Import Dependency
<dependency></code>
<code> <groupId>com.alipay.sdk</groupId></code>
<code> <artifactId>alipay-sdk-java</artifactId></code>
<code> <version>4.22.110.ALL</version></code>
<code></dependency>2. Configure application.yml
alipay:</code>
<code> appId: </code>
<code> appPrivateKey: </code>
<code> alipayPublicKey: </code>
<code> notifyUrl: (callback URL)3. Java Configuration Class (AlipayConfig.java)
@Data</code>
<code>@Component</code>
<code>@ConfigurationProperties(prefix = "alipay")</code>
<code>public class AlipayConfig {</code>
<code> private String appId;</code>
<code> private String appPrivateKey;</code>
<code> private String alipayPublicKey;</code>
<code> private String notifyUrl;</code>
<code>}Payment Controller (AliPayController.java)
@Data</code>
<code>public class AliPay {</code>
<code> private String traceNo;</code>
<code> private double totalAmount;</code>
<code> private String subject;</code>
<code> private String alipayTraceNo;</code>
<code>}</code>
<code>private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";</code>
<code>private static final String FORMAT = "JSON";</code>
<code>private static final String CHARSET = "UTF-8";</code>
<code>private static final String SIGN_TYPE = "RSA2";</code>
<code>@Resource</code>
<code>private AlipayConfig alipayConfig;</code>
<code>@Resource</code>
<code>private OrdersMapper ordersMapper;</code>
<code>@GetMapping("/pay")</code>
<code>public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {</code>
<code> AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(), alipayConfig.getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SIGN_TYPE);</code>
<code> AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();</code>
<code> request.setNotifyUrl(alipayConfig.getNotifyUrl());</code>
<code> JSONObject bizContent = new JSONObject();</code>
<code> bizContent.set("out_trade_no", aliPay.getTraceNo());</code>
<code> bizContent.set("total_amount", aliPay.getTotalAmount());</code>
<code> bizContent.set("subject", aliPay.getSubject());</code>
<code> bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");</code>
<code> request.setBizContent(bizContent.toString());</code>
<code> String form = alipayClient.pageExecute(request).getBody();</code>
<code> httpResponse.setContentType("text/html;charset=" + CHARSET);</code>
<code> httpResponse.getWriter().write(form);
<code> httpResponse.getWriter().flush();
<code> httpResponse.getWriter().close();
<code>}Callback Interface
@PostMapping("/notify") // must be POST</code>
<code>public String payNotify(HttpServletRequest request) throws Exception {</code>
<code> if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {</code>
<code> Map<String, String> params = new HashMap<>();</code>
<code> for (String name : request.getParameterMap().keySet()) {</code>
<code> params.put(name, request.getParameter(name));</code>
<code> }</code>
<code> String sign = params.get("sign");</code>
<code> String content = AlipaySignature.getSignCheckContentV1(params);</code>
<code> boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), "UTF-8");</code>
<code> if (checkSignature) {</code>
<code> // update order status to paid</code>
<code> ordersMapper.updateState(params.get("out_trade_no"), "已支付", params.get("gmt_payment"), params.get("trade_no"));</code>
<code> }</code>
<code> }</code>
<code> return "success";</code>
<code>}Refund Process
@GetMapping("/return")
public Result returnPay(AliPay aliPay) throws AlipayApiException {</code>
<code> // check 7‑day refund window</code>
<code> // create client and request</code>
<code> AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();</code>
<code> JSONObject bizContent = new JSONObject();</code>
<code> bizContent.set("trade_no", aliPay.getAlipayTraceNo());</code>
<code> bizContent.set("refund_amount", aliPay.getTotalAmount());</code>
<code> bizContent.set("out_request_no", aliPay.getTraceNo());</code>
<code> request.setBizContent(bizContent.toString());</code>
<code> AlipayTradeRefundResponse response = alipayClient.execute(request);
<code> if (response.isSuccess()) {</code>
<code> ordersMapper.updatePayState(aliPay.getTraceNo(), "已退款", DateUtil.now());
<code> return Result.success();
<code> } else {</code>
<code> return Result.error(response.getCode(), response.getBody());
<code> }
<code>}Automatic Order Cancellation (30‑minute timeout) Using RabbitMQ Delayed Queue
The article explains how to configure RabbitMQ with x-message-ttl and dead‑letter exchange/routing‑key to implement a delayed queue that moves messages to a dead‑letter queue after 30 minutes, where a consumer checks the order status and marks unpaid orders as cancelled.
Advantages: high efficiency, horizontal scalability, persistence for reliability.
Disadvantages: added operational complexity and cost due to RabbitMQ management.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
