2023最新之 教你如何使用Springboot集成支付宝沙箱支付(支持回调- 亲测有效)

2023最新之 教你如何使用Springboot集成支付宝沙箱支付(支持回调- 亲测有效)

1、进入支付宝开放平台

https://openhome.alipay.***https://openhome.alipay.***

 2、进入沙箱

2.1 点击启用公钥

点击查看:

3、java集成沙箱支付

3.1  在pom.xml文件中添加依赖

     <!--支付宝依赖 -->
        <dependency>
            <groupId>***.alipay.sdk</groupId>
            <artifactId>alipay-easysdk</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>***.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>4.22.113.ALL</version>
        </dependency>

3.2 在 application.yml 文件中配置

alipay:
  appId:
  appPrivateKey:
  alipayPublicKey:
  notifyUrl: 

3.3 alipay的java配置:AplipayConfig.java

package ***.shijiu.config;
import ***.alipay.easysdk.factory.Factory;
import ***.alipay.easysdk.kernel.Config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.***ponent;

import javax.annotation.PostConstruct;

/**
 * @Author 
 * @Date Created in  2023/5/5 15:06
 * @DESCRIPTION:
 * @Version V1.0
 */

@Data
@***ponent
//读取yml文件中alipay 开头的配置
@ConfigurationProperties(prefix = "alipay")
public class AliPayConfig {
   private String appId;
   private String appPrivateKey;
   private String alipayPublicKey;
   private String notifyUrl;


   @PostConstruct
   public void init() {
      // 设置参数(全局只需设置一次)
      Config config = new Config();
      config.protocol = "https";
      config.gatewayHost = "openapi.alipaydev.***";
      config.signType = "RSA2";
      config.appId = this.appId;
      config.merchantPrivateKey = this.appPrivateKey;
      config.alipayPublicKey = this.alipayPublicKey;
      config.notifyUrl = this.notifyUrl;
      Factory.setOptions(config);
      System.out.println("=======支付宝SDK初始化成功=======");
   }
}

 3.4   **注意:在拦截器里面加上 忽略alipay接口的配置,这很重要!**

3.5 新建一个AliPayController.java

package ***.shijiu.controller;

import ***.hutool.core.date.DatePattern;
import ***.hutool.core.date.DateUtil;
import ***.alipay.easysdk.factory.Factory;
import ***.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import ***.shijiu.***mon.Result;
import ***.shijiu.config.AliPayConfig;
import ***.shijiu.dao.mapper.ShopOrderMapper;
import ***.shijiu.pojo.AliPay;
import ***.shijiu.pojo.ShopOrder;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.***.URLEncoder;
import ***.alipay.api.AlipayApiException;
import ***.alipay.api.AlipayClient;
import ***.alipay.api.DefaultAlipayClient;
import ***.alipay.api.request.AlipayTradePagePayRequest;
import ***.alipay.easysdk.factory.Factory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * @Author 
 * @Date Created in  2023/5/5 15:23
 * @DESCRIPTION:
 * @Version V1.0
 */
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

   @Resource
   AliPayConfig aliPayConfig;

   @Resource
   private ShopOrderMapper shopOrderMapper;
   private static final String GATEWAY_URL ="https://openapi.alipaydev.***/gateway.do";
   private static final String FORMAT ="JSON";
   private static final String CHARSET ="utf-8";
   private static final String SIGN_TYPE ="RSA2";
   @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
   public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
      AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
              aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
      AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
      request.setNotifyUrl(aliPayConfig.getNotifyUrl());
      request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
              + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
              + "\"subject\":\"" + aliPay.getSubject() + "\","
              + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
      String form = "";
      try {
         // 调用SDK生成表单
         form = alipayClient.pageExecute(request).getBody();
      } catch (AlipayApiException e) {
         e.printStackTrace();
      }
      httpResponse.setContentType("text/html;charset=" + CHARSET);
      // 直接将完整的表单html输出到页面
      httpResponse.getWriter().write(form);
      httpResponse.getWriter().flush();
      httpResponse.getWriter().close();
   }
   @PostMapping("/notify")  // 注意这里必须是POST接口
   public String payNotify(HttpServletRequest request) throws Exception {
      if (request.getParameter("trade_status").equals("TRADE_SU***ESS")) {
         System.out.println("=========支付宝异步回调========");

         Map<String, String> params = new HashMap<>();
         Map<String, String[]> requestParams = request.getParameterMap();
         for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
            // System.out.println(name + " = " + request.getParameter(name));
         }

         String tradeNo = params.get("out_trade_no");
         String gmtPayment = params.get("gmt_payment");
         String alipayTradeNo = params.get("trade_no");
         // 支付宝验签
         if (Factory.Payment.***mon().verifyNotify(params)) {
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            // 更新订单未已支付
            ShopOrder order = new ShopOrder();
            order.setId(tradeNo);
            order.setStatus("1");
            Date payTime = DateUtil.parse(gmtPayment, "yyyy-MM-dd HH:mm:ss");
            order.setZhhifuTime(payTime);
            shopOrderMapper.updateById(order);
         }
      }
      return "su***ess";
   }
}

 3.6 新建  AliPay.java 参数

package ***.shijiu.pojo;

import lombok.Data;

/**
 * @Author 
 * @Date Created in  2023/5/5 15:26
 * @DESCRIPTION:
 * @Version V1.0
 */
@Data
public class AliPay {
   private String traceNo;
   private double totalAmount;
   private String subject;
   private String alipayTraceNo;
}

 前端vue 代码:(重点)

    handleEdit(row) {
      this.$confirm('确认支付?, 是否继续?', '删除打卡信息?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(`http://localhost:8888/alipay/pay?subject=${row.orderName}&traceNo=${row.id}&totalAmount=${row.prince}`)
        this.$message.su***ess('付款成功')
        this.load()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消付款'
        })
        this.load()
      })
    },

3.7 接口测试

然后我们访问URL进行测试,测试的url格式:

http://localhost:8888/alipay/pay?subject=测试商品&traceNo= 666&totalAmount=1000

 

 

3.8 内网穿透:https://natapp.***/

配置免费的隧道,端口:8888:(你项目中的地址端口号

 

3.9 新建文本文档 (启动内网穿透工具):

内容为下列内容。修改格式为 .bat

 每次启动回调地址都不同!!!

 3.10  回调地址:(如果一次不行,就多重新启动start.bat ,并更新yml文件中的回调地址

触发回调函数:

看下方的:

3.11 支付结果:(示例:227)

已支付

 学习来源:

Springboot集成支付宝沙箱支付_哔哩哔哩_bilibili大坑!集成支付宝沙箱支付!文档:https://blog.csdn.***/xqnode/article/details/124457790, 视频播放量 16884、弹幕量 103、点赞数 390、投硬币枚数 400、收藏人数 517、转发人数 72, 视频作者 程序员青戈, 作者简介 毕设私聊Q:1938976892,相关视频:支付宝沙箱支付快速集成版,沙箱支付宝项目实战教学 SpringBoot + Vue前后端分离项目整合沙箱支付宝完成支付功能,黑马程序员Java在线支付教程,深度学习掌握Java(微信支付+支付宝支付等)常用支付方式,从0开始带你手撸一套SpringBoot+Vue后台管理系统(2022年最新版),计算机毕业设计轻松搞定支付宝沙箱支付配置,8分钟学完springboot+vue前后分离的增删改查,springboot实现支付宝沙箱付款和退款功能,【尚硅谷】微信支付&支付宝支付,一套搞定Java在线支付开发教程,【java毕业设计】springboot vue校园二手闲置物品交易平台源码和论文 含支付宝沙箱支付功能,支付宝在线支付接入视频教程-Java版https://www.bilibili.***/video/BV1KS4y1w7yE/?spm_id_from=333.999.0.0&vd_source=419fe38ebae639bb2494d02c5fe95313

转载请说明出处内容投诉
CSS教程_站长资源网 » 2023最新之 教你如何使用Springboot集成支付宝沙箱支付(支持回调- 亲测有效)

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买