springboot支付宝沙箱支付详细步骤
支付宝沙箱环境配置
进入支付宝的开放平台——沙箱支付
沙箱环境
进入个人沙箱环境
点击进入沙箱环境并用支付宝登陆
沙箱管理界面如图所示:
appid,支付宝网关,自定义密钥等
沙箱账号界面如图所示:
这里是用来支付的账号和密码
密钥的生成
密钥工具下载
这时我们拿到两个密钥,将它们保存,这两个密钥很重要
- 应用私钥
- 应用公钥
拿到两个密钥后,进行自定义密钥配置
进入最开始的沙箱管理界面,点击自定义密钥,点击设置并查看,我们选择的是公钥模式
在这里将上一步骤生成的应用公钥填进来
得到支付宝公钥这另一个密钥,记住并保存这个支付宝公钥
至此,我们沙箱环境的配置和基本参数都已经获取到。
spring boot 环境配置
导入支付宝支付的依赖到pom.xml中
<!-- 支付宝依赖沙箱支付 --><dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-easysdk</artifactId><version>2.2.0</version></dependency><!-- 支付宝相关--><dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-sdk-java</artifactId><version>4.34.0.ALL</version>
在 application.yml 里面进行配置
alipay:
appId:
appPrivateKey:
alipayPublicKey:
notifyUrl:
alipay的java配置:AplipayConfig.java
packagecom.kp.config;importcom.alipay.easysdk.factory.Factory;importcom.alipay.easysdk.kernel.Config;importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importjavax.annotation.PostConstruct;@Data@Component//读取yml文件中alipay 开头的配置@ConfigurationProperties(prefix ="alipay")publicclassAliPayConfig{privateString appId;privateString appPrivateKey;privateString alipayPublicKey;privateString notifyUrl;@PostConstructpublicvoidinit(){// 设置参数(全局只需设置一次)Config config =newConfig();
config.protocol ="https";
config.gatewayHost ="openapi.alipaydev.com";
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初始化成功=======");}}
支付接口
新建一个 AliPayController.java
packagecom.kp.controller;importcom.alipay.easysdk.factory.Factory;importcom.kp.config.AliPayConfig;importcom.kp.entity.AliPay;importcom.kp.entity.Orders;importcom.kp.mapper.OrderMapper;importorg.springframework.transaction.annotation.Transactional;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importcom.alipay.api.AlipayApiException;importcom.alipay.api.AlipayClient;importcom.alipay.api.DefaultAlipayClient;importcom.alipay.api.request.AlipayTradePagePayRequest;importjavax.annotation.Resource;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.HashMap;importjava.util.Map;@RestController@RequestMapping("alipay")@Transactional(rollbackFor =Exception.class)publicclassAliPayController{@ResourceAliPayConfig aliPayConfig;@ResourceprivateOrderMapper shopOrderMapper;privatestaticfinalStringGATEWAY_URL="https://openapi-sandbox.dl.alipaydev.com/gateway.do";privatestaticfinalStringFORMAT="JSON";privatestaticfinalStringCHARSET="utf-8";privatestaticfinalStringSIGN_TYPE="RSA2";@GetMapping("/pay")// &subject=xxx&traceNo=xxx&totalAmount=xxxpublicvoidpay(AliPay aliPay,HttpServletResponse httpResponse)throwsException{AlipayClient alipayClient =newDefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
aliPayConfig.getAppPrivateKey(),FORMAT,CHARSET, aliPayConfig.getAlipayPublicKey(),SIGN_TYPE);AlipayTradePagePayRequest request =newAlipayTradePagePayRequest();
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接口publicStringpayNotify(HttpServletRequest request)throwsException{if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){System.out.println("=========支付宝异步回调========");Map<String,String> params =newHashMap<>();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.Common().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"));// 更新订单未已支付Orders order =newOrders();
order.setId(Long.valueOf(tradeNo));
order.setStatus(2);// order.setCheckoutTime(params.get("gmt_payment"));
shopOrderMapper.updateById(order);}}return"success";}}
参数 Alipay.java
packagecom.kp.entity;importlombok.Data;@DatapublicclassAliPay{privateString traceNo;privatedouble totalAmount;privateString subject;privateString alipayTraceNo;}
注意:在拦截器里面加上 忽略alipay接口的配置,这很重要!
重要!前端配置!!
res.data.consignee以及其他两个参数都是下单时候的参数
async goToPaySuccess(){const params ={
remark:this.note,
payMethod:1,
addressBookId:this.address.id
}const res = await addOrderApi(params)
console.log('params:', params);
console.log('res:', res);if(res.code ===1){
window.open(`http://localhost:8090/alipay/pay?subject=${res.data.consignee}&traceNo=${res.data.id}&totalAmount=${res.data.amount}`)this.$message.success('付款成功')this.load();})}else{this.$notify({ type:'warning', message:res.msg});}},
接口测试
测试的url格式:
http://localhost:9090/alipay/paysubject=xxx&traceNo=xxx&totalAmount=1000
使用沙箱账号登录,支付就可以
回调接口在上面的Controller中配置
内网穿透:https://natapp.cn/
配置免费的隧道,端口:(你的项目端口)
软件下载地址:
内网穿透软件下载
下载好软件后,打开配置下authtoken:
参考这个步骤,把authtoken复制过来
双击启动 natapp.exe即可。
看到这个表示你启动成功了:
idea里面配置notify接口并测试
更改 application.yml 里的配置:
至此,集成完毕!撒花!坑太多了!
版权归原作者 努力学习积极向上好青年 所有, 如有侵权,请联系我们删除。