springboot 整合支付宝支付(沙箱)

时间:2024-11-24 09:25:17
// 这里必须加@ResponseBody注解,让当前方法的返回值成为响应体,在浏览器界面上显示支付宝支付界面 @ResponseBody @RequestMapping("/generate/order") public String generateOrder(HttpSession session, OrderVO orderVO) throws AlipayApiException { // 1.从Session域获取orderProjectVO对象 OrderProjectVO orderProjectVO = (OrderProjectVO) session.getAttribute("orderProjectVO"); // 2.将orderProjectVO对象和orderVO对象组装到一起 orderVO.setOrderProjectVO(orderProjectVO); // 3.生成订单号并设置到orderVO对象中 // ①根据当前日期时间生成字符串 String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // ②使用UUID生成用户ID部分 String user = UUID.randomUUID().toString().replace("-", "").toUpperCase(); // ③组装 String orderNum = time + user; // ④设置到OrderVO对象中 orderVO.setOrderNum(orderNum); // 4.计算订单总金额并设置到orderVO对象中 Double orderAmount = (double) (orderProjectVO.getSupportPrice() * orderProjectVO.getReturnCount() + orderProjectVO.getFreight()); orderVO.setOrderAmount(orderAmount); // ※将OrderVO对象存入Session域 session.setAttribute("orderVO", orderVO); // 5.调用专门封装好的方法给支付宝接口发送请求 return sendRequestToAliPay(orderNum, orderAmount, orderProjectVO.getProjectName(), orderProjectVO.getReturnContent()); } /** * 返回支付宝支付页面 * @param outTradeNum 订单号 * @param totalAmount 总金额 * @param subject 商品名称 * @param body 商品描述 * @return 返回支付页面 * @throws AlipayApiException */ private String sendRequestToAliPay(String outTradeNum,Double totalAmount,String subject,String body) throws AlipayApiException { //获得初始化的AlipayClient AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.gatewayUrl, alipayProperties.appId, alipayProperties.merchantPrivateKey, "json", alipayProperties.charset, alipayProperties.alipayPublicKey, alipayProperties.signType); //设置请求参数 AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); alipayRequest.setReturnUrl(alipayProperties.returnUrl); alipayRequest.setNotifyUrl(alipayProperties.notifyUrl); //商户订单号,商户网站订单系统中唯一订单号,必填 // String out_trade_no = new String(("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8"); //付款金额,必填 // String total_amount = new String(("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8"); //订单名称,必填 // String subject = new String(("WIDsubject").getBytes("ISO-8859-1"),"UTF-8"); //商品描述,可空 // String body = new String(("WIDbody").getBytes("ISO-8859-1"),"UTF-8"); alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNum +"\"," + "\"total_amount\":\""+ totalAmount +"\"," + "\"subject\":\""+ subject +"\"," + "\"body\":\""+ body +"\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); //若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明 //("{\"out_trade_no\":\""+ out_trade_no +"\"," // + "\"total_amount\":\""+ total_amount +"\"," // + "\"subject\":\""+ subject +"\"," // + "\"body\":\""+ body +"\"," // + "\"timeout_express\":\"10m\"," // + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); //请求参数可查阅【电脑网站支付的API文档--请求参数】章节 //请求 // String result = (alipayRequest).getBody(); // 返回页面 return alipayClient.pageExecute(alipayRequest).getBody(); // //输出 // (result); }