Step‑by‑Step Alipay SDK Integration in Java with Full Code Samples

This guide walks you through configuring the new Alipay transfer API in a Java Spring Boot project, covering certificate placement, property files, Maven dependencies, bean definitions, client configuration, utility methods, and the data models required for secure payments.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Step‑by‑Step Alipay SDK Integration in Java with Full Code Samples

Introduction

Alipay released a new transfer interface alipay.fund.trans.uni.transfer with higher security and richer features. The old interface alipay.fund.trans.toaccount.transfer is deprecated. To use the new API, upgrade the SDK to the latest version (e.g., 4.10.97).

1. Place certificates

Download the three certificates from the Alipay Open Platform and put them under the resources directory.

Certificates
Certificates

2. Create configuration file

Create alipay.properties with the following content:

alipay.appId=YOUR_APP_ID<br/>alipay.serverUrl=https://openapi.alipay.com/gateway.do<br/>alipay.privateKey=YOUR_PRIVATE_KEY<br/>alipay.format=json<br/>alipay.charset=UTF-8<br/>alipay.signType=RSA2<br/>alipay.appCertPath=/cert/appCertPublicKey_2021001164652941.crt<br/>alipay.alipayCertPath=/cert/alipayCertPublicKey_RSA2.crt<br/>alipay.alipayRootCertPath=/cert/alipayRootCert.crt<br/>

3. Add Maven dependency

<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>4.10.97.ALL</version>
</dependency>

4. Define AliPayBean

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:/production/alipay.properties")
@ConfigurationProperties(prefix = "alipay")
@Data
public class AliPayBean {
    private String appId;
    private String privateKey;
    private String publicKey;
    private String serverUrl;
    private String domain;
    private String format;
    private String charset;
    private String signType;
    private String appCertPath;
    private String alipayCertPath;
    private String alipayRootCertPath;
}

5. Create configuration class

import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.FileCopyUtils;
import java.io.InputStream;

@Configuration
public class AliConfig {
    @Value("${custom.http.proxyHost}")
    private String proxyHost;
    @Value("${custom.http.proxyPort}")
    private int proxyPort;
    @Value("${spring.profiles.active}")
    private String activeEnv;

    @Autowired
    private AliPayBean aliPayBean;

    @Bean(name = {"alipayClient"})
    public AlipayClient alipayClientService() throws Exception {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(aliPayBean.getServerUrl());
        certAlipayRequest.setAppId(aliPayBean.getAppId());
        certAlipayRequest.setPrivateKey(aliPayBean.getPrivateKey());
        certAlipayRequest.setFormat(aliPayBean.getFormat());
        certAlipayRequest.setCharset(aliPayBean.getCharset());
        certAlipayRequest.setSignType(aliPayBean.getSignType());
        if ("prod".equals(activeEnv) || "stage".equals(activeEnv) || "test".equals(activeEnv)) {
            certAlipayRequest.setCertContent(getCertContentByPath(aliPayBean.getAppCertPath()));
            certAlipayRequest.setAlipayPublicCertContent(getCertContentByPath(aliPayBean.getAlipayCertPath()));
            certAlipayRequest.setRootCertContent(getCertContentByPath(aliPayBean.getAlipayRootCertPath()));
            certAlipayRequest.setProxyHost(proxyHost);
            certAlipayRequest.setProxyPort(proxyPort);
        } else {
            String serverPath = this.getClass().getResource("/").getPath();
            certAlipayRequest.setCertPath(serverPath + aliPayBean.getAppCertPath());
            certAlipayRequest.setAlipayPublicCertPath(serverPath + aliPayBean.getAlipayCertPath());
            certAlipayRequest.setRootCertPath(serverPath + aliPayBean.getAlipayRootCertPath());
        }
        return new DefaultAlipayClient(certAlipayRequest);
    }

    public String getCertContentByPath(String name) {
        InputStream inputStream = null;
        String content = null;
        try {
            inputStream = this.getClass().getClassLoader().getResourceAsStream(name);
            content = new String(FileCopyUtils.copyToByteArray(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
}

6. Implement utility class

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AliPayUtils {
    @Autowired
    @Qualifier("alipayClient")
    private AlipayClient alipayClient;

    public boolean isTradeQuery(AlipayTradeQueryModel model) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
        return response.isSuccess();
    }

    public String startAppPay(AlipayTradeAppPayModel model, String notifyUrl) throws AlipayApiException {
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setNotifyUrl(notifyUrl);
        request.setBizModel(model);
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        return response.getBody();
    }

    public AlipayFundTransUniTransferResponse doTransferNew(TransferParams transferParams) throws Exception {
        String title = (transferParams.getRemark() != null && !transferParams.getRemark().isEmpty())
                ? transferParams.getRemark() : "转账";
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        BizContentForUniTransfer biz = new BizContentForUniTransfer();
        biz.setOut_biz_no(transferParams.getOutBizNo());
        biz.setTrans_amount(MathUtil.changeF2Y(Math.abs(Integer.parseInt(transferParams.getAmount()))));
        biz.setProduct_code("TRANS_ACCOUNT_NO_PWD");
        biz.setBiz_scene("DIRECT_TRANSFER");
        biz.setOrder_title(title);
        Participant participant = new Participant();
        participant.setIdentity(transferParams.getPayeeAccount());
        participant.setIdentity_type(transferParams.getPayeeType());
        participant.setName(transferParams.getPayeeRealName() != null ? transferParams.getPayeeRealName() : "");
        biz.setPayee_info(participant);
        biz.setRemark(title);
        request.setBizContent(JSON.toJSONString(biz));
        AlipayFundTransUniTransferResponse response = null;
        try {
            response = alipayClient.certificateExecute(request);
        } catch (Exception e) {
            log.info("doTransfer exception, {}", e.toString());
            log.info("Alipay response: {}", JSONObject.toJSONString(response));
        }
        log.info("doTransfer response: {}", JSONObject.toJSONString(response));
        return response;
    }
}

7. Data models

@Data
public class TransferParams {
    private Long appId;
    private Long createdBy;
    private String outBizNo;
    private String payeeType;
    private String payeeAccount;
    private String amount;
    private String payerShowName;
    private String payeeRealName;
    private String remark;
    private String orderId;
}
@Data
public class Participant {
    private String identity;
    private String identity_type;
    private String name;
}

The above steps provide a complete, runnable setup for integrating Alipay's new transfer API into a Java Spring Boot backend.

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.

JavaSDKSpring BootPayment IntegrationAlipay
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

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.