SpringBoot项目集成支付宝

在 Spring Boot 项目中对接支付宝的第三方支付接口涉及几个主要步骤:集成支付宝 SDK、配置支付宝相关信息、实现支付和退款逻辑。

1. 添加依赖

首先,你需要在项目的 pom.xml 文件中添加支付宝 SDK 的依赖。如果使用 Maven,可以添加如下依赖:

<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>4.14.37.ALL</version> <!-- 使用最新的版本 -->
</dependency>

2. 配置支付宝信息

application.propertiesapplication.yml 文件中配置支付宝相关的信息,包括商户 ID、应用 ID、私钥和支付宝公钥等。

# application.properties
alipay.app-id=YOUR_APP_ID
alipay.merchant-private-key=YOUR_PRIVATE_KEY
alipay.alipay-public-key=ALIPAY_PUBLIC_KEY
alipay.gateway-url=https://openapi.alipay.com/gateway.do

3. 创建支付服务

创建一个服务类来处理支付宝支付和退款请求。首先是支付请求的构造和发送:

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.response.AlipayTradePagePayResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AlipayService {

    @Value("${alipay.gateway-url}")
    private String gatewayUrl;

    @Value("${alipay.app-id}")
    private String appId;

    @Value("${alipay.merchant-private-key}")
    private String privateKey;

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    private AlipayClient alipayClient;

    public AlipayService() {
        alipayClient = new DefaultAlipayClient(
            gatewayUrl,
            appId,
            privateKey,
            "json",
            "UTF-8",
            alipayPublicKey,
            "RSA2"
        );
    }

    public String createPaymentUrl(String outTradeNo, String totalAmount, String subject) throws AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl("http://yourdomain.com/return_url");
        request.setNotifyUrl("http://yourdomain.com/notify_url");

        StringBuilder bizContent = new StringBuilder();
        bizContent.append("{")
                .append("\"out_trade_no\":\"").append(outTradeNo).append("\",")
                .append("\"total_amount\":\"").append(totalAmount).append("\",")
                .append("\"subject\":\"").append(subject).append("\",")
                .append("\"product_code\":\"FAST_INSTANT_TRADE_PAY\"")
                .append("}");
        
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody(); // 这是支付宝返回的支付页面的 HTML 内容
        } else {
            throw new RuntimeException("Alipay request failed: " + response.getSubMsg());
        }
    }
}

4. 创建退款服务

退款服务类处理退款请求:

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AlipayRefundService {

    @Value("${alipay.gateway-url}")
    private String gatewayUrl;

    @Value("${alipay.app-id}")
    private String appId;

    @Value("${alipay.merchant-private-key}")
    private String privateKey;

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    private AlipayClient alipayClient;

    public AlipayRefundService() {
        alipayClient = new DefaultAlipayClient(
            gatewayUrl,
            appId,
            privateKey,
            "json",
            "UTF-8",
            alipayPublicKey,
            "RSA2"
        );
    }

    public String refund(String outTradeNo, String refundAmount) throws AlipayApiException {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{"
                + "\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"refund_amount\":\"" + refundAmount + "\""
                + "}");
        
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return "Refund successful";
        } else {
            throw new RuntimeException("Alipay refund failed: " + response.getSubMsg());
        }
    }
}

5. 创建控制器

在控制器中创建端点来处理支付和退款请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayApiException;

@RestController
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private AlipayRefundService alipayRefundService;

    @GetMapping("/pay")
    public String pay(@RequestParam String outTradeNo, @RequestParam String totalAmount, @RequestParam String subject) {
        try {
            String paymentUrl = alipayService.createPaymentUrl(outTradeNo, totalAmount, subject);
            return paymentUrl; // 返回支付页面的 HTML 内容
        } catch (AlipayApiException e) {
            return "Error occurred: " + e.getMessage();
        }
    }

    @PostMapping("/refund")
    public String refund(@RequestParam String outTradeNo, @RequestParam String refundAmount) {
        try {
            return alipayRefundService.refund(outTradeNo, refundAmount);
        } catch (AlipayApiException e) {
            return "Error occurred: " + e.getMessage();
        }
    }
}

6. 处理异步通知

支付宝支付和退款成功后会向你配置的 notify_url 发送异步通知。你需要在应用中创建一个处理这些通知的端点:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;

@RestController
public class AlipayNotifyController {

    @PostMapping("/notify_url")
    public String notifyUrl(@RequestParam Map<String, String> params) {
        // 验证通知的真实性
        // 处理支付或退款成功后的逻辑

        String outTradeNo = params.get("out_trade_no");
        // 处理支付逻辑
        // ...
        return "success"; // 返回给支付宝,确认收到通知
    }
}
在Spring Boot和Vue集成支付宝支付功能的具体步骤如下: 1. 注册支付宝开发者账号并创建应用 前往支付宝开放平台(https://open.alipay.com)注册开发者账号,并创建一个应用,获取应用的AppId、私钥和公钥。 2. 后端集成支付宝SDK 在Spring Boot项目中引入支付宝的Java SDK,可以使用Maven或Gradle添加相关依赖。例如使用Maven,将以下依赖添加到pom.xml文件中: ```xml <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>3.7.110.ALL</version> </dependency> ``` 3. 创建支付接口和回调接口 在Spring Boot中创建一个支付接口,提供生成支付订单的功能,并在回调接口中处理支付宝的异步通知。 4. 前端集成支付宝支付组件 在Vue项目中引入支付宝的前端支付组件,可以使用官方提供的组件或第三方库,如vue-alipay-box。 5. 前后端交互 前端发起支付请求时,将订单信息传递给后端接口,后端接口使用支付宝SDK生成支付链接,并将该链接返回给前端。 6. 处理支付回调 支付宝在用户支付成功后会异步通知后端,后端需要校验通知的合法性,并处理订单状态的更新等业务逻辑。 以上是集成支付宝支付的一般步骤,具体实现会因项目结构和需求而有所差异。在实际开发过程中,还需注意数据安全、接口调试和异常处理等方面的问题。希望以上信息对您有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fittt_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值