SpringBoot整合支付宝沙箱支付
1.申请支付宝开发者沙箱账号
2.设置支付宝公钥与私钥
使用支付宝提供的工具生成密钥
粘贴刚才生成的应用公钥设置你的应用公钥,生成支付宝公钥(支付宝公钥和你自己的私有后边需要)
3.引入支付宝支付所需依赖
<!--支付宝SDK-->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-easysdk</artifactId>
<version>2.2.0</version></dependency>
</dependency>
4.编写支付配置类并配置所需参数
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import org.springframework.stereotype.Component;
@Component
public class AlipayConfig {
// 1. 设置参数(全局只需设置一次)
static {
Factory.setOptions(getOptions());
}
private static Config getOptions() {
Config config = new Config();
config.protocol = "https";
// 沙箱环境为 openapi.alipaydev.com
config.gatewayHost = "openapi.alipaydev.com";
config.signType = "RSA2";
config.appId = "你的APPID";
config.merchantPrivateKey = "你的私钥";
config.alipayPublicKey = "你的支付宝公钥";
//可设置异步通知接收服务地址(可选)(该地址需要外网能够访问)
config.notifyUrl = "https://www.baidu.com/";
return config;
}
}
5.编写支付业务层
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
/**
* @author yongxin
* @create 2021/6/23
*/
@Service
public class AlipayService {
/**
* 生成支付表单
* @param subject 商品描述
* @param money 支付金额
* @param tradeNo 订单号
* @return 返回一个支付表单
* @throws Exception
*/
public String toPay(String subject, BigDecimal money,String tradeNo) throws Exception {
AlipayTradePagePayResponse pay = Factory.Payment.Page().pay(subject, tradeNo,
String.valueOf(money), "支付成功后跳转地址");
String payForm = null;
if (ResponseChecker.success(pay)) {
payForm = pay.getBody();
}
return payForm;
}
}
6.controller层接口支付接口
@Controller
@RequestMapping("/pay")
@Api(tags = "支付接口")
public class AlipayController {
@Autowired
private AlipayService alipayService;
@GetMapping("/topay")
@ResponseBody
public String toPay(String subject, BigDecimal money,String tradeNo) throws Exception {
return alipayService.toPay(subject, money,tradeNo);
}
}
返回的是一个form表单
7.前端(VUE)解析from跳转支付
axios({
url:"接口路径",
method:"get",
params:{
subject:this.subject,
money:this.money,
tradeNo:this.tradeNo,
}
}).then((resp)=>{
// 添加之前先删除一下,如果单页面,页面不刷新,添加进去的内容会一直保留在页面中,二次调用form表单会出错
const divForm = document.getElementsByTagName('div')
if (divForm.length) {
document.body.removeChild(divForm[0])
}
const div = document.createElement('div')
div.innerHTML = resp.data.data // data就是接口返回的form 表单字符串
document.body.appendChild(div)
document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
document.forms[0].submit()
})