Spring-boot实现沙箱支付

Spring-boot实现沙箱支付

1.支付宝开放平台****(注册账号自己找到沙箱)

2.设置自定义的公钥私钥

在这里插入图片描述在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3.复制公钥–到填写框中
在这里插入图片描述

在这里插入图片描述

4.创建一个spring-boot项目

Maven

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    </dependencies>

5.目录结构
在这里插入图片描述

6.yml配置文件

在这里插入图片描述

server:
  port: 8080

spring:
  thymeleaf:
    cache: false
    suffix: .html
    prefix: classpath:/templates/

#ssbqis6091@sandbox.com
alipay:
   #(URL填写自己的)
  url: 
  #(APPID填写自己的)
  appid: 
  
  #私钥(填写自己的)
  privateKey:
  
  #公钥(填写自己的)
  publicKey:
  
  #
  notifyUrl: http://localhost:8080/notify
  #支付成功返回的页面
  returnUrl: http://localhost:8080/return

7.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>支付宝支付index</title>
</head>
<body>
<h1>支付宝支付index</h1>
<form method="post" action="createDan">
    <p> 订单编号:<input type="text" name="id"></p>
    <p> 订单金额:<input type="text" name="price"></p>
    <p> 订单标题:<input type="text" name="title"></p>
    <p> <input type="submit" value="订单提交"></p>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>pay</title>
</head>
<body>
<div th:utext="${form}"></div>
</body>
</html>```

```html
<!DOCTYPE html>
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>paySE</title>
</head>
<body>
<h1>PaySE......</h1>
<div th:text="${paySe}"></div>

</body>
</html>

8.util代码

package com.xmx.alipay.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @create: 2022-03-08 20:54
 * @author: 郑兴源
 * @description:
 **/
@Component
public class AliPayUtil {
    @Value("${alipay.appid}")
    private String appid;

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

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

    @Value("${alipay.publicKey}")
    private String publicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    public String pay(String id, String price, String title) {

        //订单生成--支付
        AlipayClient alipayClient = new DefaultAlipayClient(url, appid, privateKey, "json", "UTF-8", publicKey, "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        bizContent.put("total_amount", price);
        bizContent.put("subject", title);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");


        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        String form = null;
        try {
            response = alipayClient.pageExecute(request);
            form = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return form;
    }

    //查询订单支付是否成功
    public String selectPaySE(String id) {
        AlipayClient alipayClient = new DefaultAlipayClient(url, appid, privateKey, "json", "UTF-8", publicKey, "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        //bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String boby = null;
        try {
            response = alipayClient.execute(request);
            boby = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return boby;
    }

}

9.controller代码

package com.xmx.alipay.controller;

import com.xmx.alipay.util.AliPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @create: 2022-03-08 20:30
 * @author: 郑兴源
 * @description:
 **/
@Controller
public class AliPayController {


    @Autowired
    AliPayUtil aliPayUtil;

    public void setAliPayUtil(AliPayUtil aliPayUtil) {
        this.aliPayUtil = aliPayUtil;
    }
    //进入支付首页
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /*创建订单*/
    @PostMapping("/createDan")
    public String createDan(String id, String price, String title, Model model) {
        String pay = aliPayUtil.pay(id, price, title);
        model.addAttribute("form", pay);
        return "pay";
    }

    //支付成功返回页面
    @GetMapping("/return")
    public String returns(String out_trade_no, Model model) {
        String s = aliPayUtil.selectPaySE(out_trade_no);
        model.addAttribute("paySe", s);
        return "paySE";
    }

}

10运行结果
查看自己的账号
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
跳入自定义页面

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的支付沙箱支付Spring Boot后端代码示例: 首先,你需要引入以下依赖: ``` <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>3.7.110.ALL</version> </dependency> ``` 然后,创建一个支付服务类: ``` @Service public class AlipayService { // 私钥 private static final String APP_PRIVATE_KEY = "xxxxxx"; // 公钥 private static final String ALIPAY_PUBLIC_KEY = "xxxxxx"; // 应用ID private static final String APP_ID = "xxxxxx"; // 编码格式 private static final String CHARSET = "utf-8"; // 支付宝网关 private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do"; /** * 支付支付 * @param orderId 订单ID * @param totalAmount 订单总金额 * @return 支付结果 * @throws AlipayApiException */ public String alipay(String orderId, String totalAmount) throws AlipayApiException { AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); alipayRequest.setReturnUrl("http://localhost:8080/alipay/return"); alipayRequest.setNotifyUrl("http://localhost:8080/alipay/notify"); alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderId + "\"," + "\"total_amount\":\"" + totalAmount + "\"," + "\"subject\":\"测试订单\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); String result = alipayClient.pageExecute(alipayRequest).getBody(); return result; } /** * 支付支付异步通知处理 * @param request * @throws AlipayApiException */ public void alipayNotify(HttpServletRequest request) throws AlipayApiException { Map<String, String> params = new HashMap<String, String>(); Map<String, String[]> requestParams = request.getParameterMap(); for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } params.put(name, valueStr); } boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2"); if (signVerified) { // 验证成功 String tradeStatus = request.getParameter("trade_status"); if ("TRADE_SUCCESS".equals(tradeStatus)) { // 处理支付成功业务逻辑 } } } } ``` 在这个代码中,我们使用了支付宝提供的 Java SDK,使用沙箱环境的网关 URL。我们还提供了一个处理支付宝异步通知的方法,以便在收到支付宝通知时处理业务逻辑。 最后,我们需要在控制器中定义支付接口和异步通知接口: ``` @RestController @RequestMapping("/alipay") public class AlipayController { @Autowired private AlipayService alipayService; @GetMapping("/pay") public String alipay(@RequestParam String orderId, @RequestParam String totalAmount) throws AlipayApiException { return alipayService.alipay(orderId, totalAmount); } @PostMapping("/notify") public void alipayNotify(HttpServletRequest request) throws AlipayApiException { alipayService.alipayNotify(request); } @GetMapping("/return") public String alipayReturn(HttpServletRequest request) throws AlipayApiException { // 处理支付宝同步通知 return "支付成功"; } } ``` 在这个示例中,我们定义了一个支付接口,`/alipay/pay`,接收订单ID和总金额,返回支付支付页面的 HTML 代码。我们还定义了一个异步通知接口,`/alipay/notify`,用于处理支付宝异步通知,并处理支付成功业务逻辑。最后,我们还定义了一个同步通知接口,`/alipay/return`,用于处理支付宝同步通知。 这是一个简单的支付沙箱支付Spring Boot后端代码示例。你可以根据自己的业务需求进行修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值