Java Integration of Alipay Recurring Payments: End‑to‑End Production‑Ready Implementation
This guide walks through a complete Java implementation for Alipay's periodic (cycle) payment service, covering business prerequisites, Spring Boot configuration, signing and deduction APIs, callback verification, retry mechanisms, scheduled tasks, and reconciliation, with production‑grade code examples.
The article introduces the full business flow of Alipay's recurring‑payment (cycle‑pay) service, from user sign‑up to automatic deductions, and shows a diagram that clarifies the three‑step process: user authorises a contract, the merchant initiates a payment, and Alipay executes the transaction.
It first lists the qualification requirements for merchants (enterprise account, business scope, website/app备案, industry‑specific certifications) and the step‑by‑step activation procedure on the Alipay Open Platform console.
Technical preparation includes adding Maven dependencies for spring-boot-starter-web, alipay-sdk-java, Lombok, MyBatis‑Plus, and Hutool. The article shows how to generate RSA2 key pairs (using openssl or Alipay's tool) and how to configure application.yml with app-id, public/private keys, gateway URL, notify and return URLs, and business parameters such as retry count and interval.
# application.yml (excerpt)
alipay:
app-id: 2021000000000000
alipay-public-key: MIIBIjANB... (public key)
private-key: MIIEvQIBAD... (private key)
gateway-url: https://openapi.alipay.com/gateway.do
notify-url: https://yourdomain.com/api/alipay/notify
return-url: https://yourdomain.com/api/alipay/return
business:
deduct-retry-count: 3
deduct-retry-interval: 5The signing flow is encapsulated in AlipaySignService. A SignRequest object carries user ID, product code, deduct type, amount, title, description, and optional validity days. The service generates a merchant sign number ( outSignNo) if not supplied, persists an AlipayAgreement record with status SIGNING, builds an AlipayUserAgreementPageSignRequest, and calls alipayClient.pageExecute. On success it returns a SignResponse containing the HTML form; on failure it updates the agreement status to UNSIGNED and returns an error message.
Deduction uses AlipayDeductService. A DeductRequest includes user ID, agreement ID, amount, subject, body, order type, and period. The service validates that the agreement exists and is in SIGNED state, generates an outRequestNo, creates an AlipayDeductRecord with status PENDING, and builds an AlipayTradePayRequest. If the Alipay trade_pay call succeeds, the record is marked SUCCESS with the Alipay trade number; otherwise it records the failure code, reason, and schedules a retry based on the configured interval and exponential back‑off.
Callback verification is performed by AlipayVerifyServiceImpl, which parses the JSON payload, extracts parameters, and calls AlipaySignature.rsaCheckV1 with the configured public key, charset, and sign type. Both sign and deduct callbacks invoke their respective service handleSignNotify / handleDeductNotify methods, which update the database records, set timestamps, and trigger business actions such as sending MQ events or updating order status. The controller also provides a unified /api/alipay/notify endpoint that dispatches to the appropriate handler based on the presence of agreement_id or trade_no.
Retry logic is implemented in AlipayDeductServiceImpl.retryFailedDeducts, which selects records with FAIL status whose nextRetryTime has passed, checks the agreement status, and re‑executes the trade_pay request. A Spring @Scheduled(cron="0 */1 * * * ?") method runs every minute to invoke the retry routine.
Periodic deduction plans are generated by DeductPlanService. The generatePlan method validates the agreement, iterates over the date range according to the chosen cycle (DAILY, WEEKLY, MONTHLY, YEARLY), creates pending AlipayDeductRecord entries with descriptive subjects, and stores them. Another scheduled task ( scheduledExecuteDeducts) queries due records, verifies agreement status, and triggers the deduction service for each entry.
Reconciliation is handled by ReconciliationServiceImpl. It calls Alipay's AlipayDataDataserviceBillDownloadurlQueryRequest to obtain a CSV bill URL, downloads the file to a temporary location, parses each line into BillItem objects, and compares them with locally stored successful deduction records. Differences such as missing local records, missing Alipay records, or amount mismatches are collected into DiffItem objects, and a summary result reports counts and status (SUCCESS, DIFF, FAILED).
Finally, the article lists production‑grade considerations: use certificate mode for keys, keep private keys out of source control, enforce HTTPS callbacks, verify signatures, implement idempotent updates, encrypt sensitive fields, and apply log sanitisation. Performance tips include adding database indexes, sharding deduction tables, caching agreement status in Redis, and processing callbacks asynchronously. Monitoring suggestions cover success rates, retry queue depth, reconciliation diffs, and endpoint latency.
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.
Cloud Architecture
Focuses on cloud‑native and distributed architecture engineering, sharing practical solutions and lessons learned. Covers microservice governance, Kubernetes, observability, and stability engineering to help your systems run stable, fast, and cost‑effectively.
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.
