当前位置: 首页 > article >正文

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"; // 返回给支付宝,确认收到通知
    }
}

http://www.kler.cn/a/287969.html

相关文章:

  • 丹摩征文活动 |【前端开发】HTML+CSS+JavaScript前端三剑客的基础知识体系了解
  • C/C++静态库引用过程中出现符号未定义的处理方式
  • 华为云前台展示公网访问需要购买EIP,EIP流量走向
  • LeetCode59. 螺旋矩阵 II
  • FBX福币交易所恒指收跌1.96% 半导体股继续回调
  • 【MYSQL】数据库日志 (了解即可)
  • 2024.8.28 C++
  • 物联网之云平台架构
  • 详细解说:ansible自动化运维项目
  • python基础(16面试题附答案一)
  • 【随记】开源 AI(Open source AI)
  • read()和readlines()的区别
  • DReg-NeRF: Deep Registration for Neural Radiance Fields论文解读
  • Flask框架 完整实战案例 附代码解读 【3】
  • 【ag-grid】列宽设置不生效探索
  • 基于vue框架的超市管理系统y9992(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
  • Linux_kernel简介01
  • JavaEE 第21节 UDP数据报结构剖析
  • 【区块链 + 物联网】可信保密的海洋大数据分析平台 | FISCO BCOS应用案例
  • SpringAOPSpring事物管理
  • UE5蓝图 抽卡出货概率
  • 批量替换字符串中的某子串序列为对应的另一子串序列(z3求解器解多元方程时很好用)
  • 【C#】字段
  • 在麒麟系统安装php7.4中遇到的问题
  • uniapp微信小程序3D XR-FRAME
  • 机器学习之监督学习(二)逻辑回归(二元分类问题)