本篇文章为大家展示了怎么在Springboot中添加支付接口,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
1. 支付宝支付接口(沙箱实现)
1.1 支付宝沙箱账号获取
如下图:
此处可以自行设置账户金额
1.2 下载客户端(目前好像只支持Android)
下载完成后根据官方提供的账号以及密码登录手机端支付宝账号 如图(商家账号):
1.3 代码配置
工具类AlipayConfig
public class AlipayConfig {//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ // 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号 public static String app_id = ""; // 商户私钥,您的PKCS8格式RSA2私钥 public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/HOeQNyultzkc5cUnqxBSTIpYt6BTgJoCHKiLQDYgPhjvSX16r08Qw82qYdQgWEs4hHNy2COGA5ksw1eW+zyY2alcTEvRMo4sqx7Ytdm250f67wZQkuPRFSJN7ywHkTipjGKNcS9z9U0Dp18jRXHow4/A9OF8jOau7pWyG0Tc87WHf5u0/G16uMpRtGRzzyNvim7cHAnyFPNrAJ+5DRBdhBg+PjV7EcpYg5LRaMqaO8qDSis+AUU4e7QOELqMgr7yxBNScQ6KksnWnztcFxz6M9T66dAZJ0dWpiB8qatM6sT/MeHTAXeYLhIbnUaxM9vGJR3AJHbHmvNa9o0ToT0LAgMBAAECggEBAIk1a1szAPc9EJgaru3H9zPfGASR8V2CGxAhGzC+rR2A9830aU5HxvA2Y9ZL3kxKl9a/4VM2smpo8vQcWypevibPPrSxYk2Tilevk7nq9aBHdHpIWbRHgaB/F930NRxJuvCfhbIe7P7Hwr84zyk3loySuwbByZHuZ0B4sqjowwwN/wbshl5m/5i4ej6AUp1LVEbxUFpNHNjIZejWVJ0Liq69l8o+1HsFIaGW1Vcrf+fmq20moZzFOLi4EmGfBp/na8JDmo3bE3X+ccAJ375OYictfZVKKYI/UIC/D+7y4XuZatLq3V3lql5ukMnAUJwTJeEapSigkJHDOX38xcSA7iECgYEA5qvIl7PGl8CwDOgTe8LoT8toTUmhAVDFwSF+ROCZD8u9qQeGG7SSCovoTQcVDuzVA3bW8d4Guvb7ZTpnUZZyWHD2rOqxh76wqHGiVTJRApNTS7XHXt3FERNgM7Y8lSoYHdarsZ7QZaJDGGkcwuGvJM0klwyuqs6LQq5DRsz9qp8CgYEA1BkiCjD5FUE/i48MFh+qYcOSiqsm7Hrj/4zuHj0QODonuUZPH0V6b3p4SIWHeBsjmSxBsqoLh3qFOzWAUeBVU3+muPHp3uglumtjZ5wE0nHCt2+0ZH+QKSk5mm8j+09xfTJ185FMusx0N9RQ4l6Rpzb7DSLQFelT4M7gvTRjAhUCgYAtUPQwcV4DdBRiBLnHJ4xSGMjd3igmRQMEpRrUVzdathEFgvfiu3+xWLkDYO/PJdHXQ2KI07CIzHqo8WdYzPCb1V1wrQ7BdB06ilB04lSt59mGVyjax0Cu0RqmLhgKyeFBA2ppk6SnQtBhnEzNMF8jILYegpxR7A/JwshuwVjYSwKBgQCTxfMGgLp6iZxZgs/b9jICrX1DKh5Tc0e5PBqHbOoJEtOsbYUg94pncz+s34PUNaxmwwP/FCS2M4wiBZOi+Bba9zxU7Q+R49KtgLagcH6XlPUiUyyvPIVXeEaPB9Jc/SvIG8k8a0a3e02ZvE6G1hETQj2GGZv0ENiSpRQKBgC8qOk7TMndVDi3vlgGky3BmxSpycwGnI0tcBZnzAyzcLPH3RL3nLvUoZ1w550be7mPDt30/WkCMKV8uKRnNVSrp1LSbT0Z6oJxsaHaCxv3C2UFzlqKWsTtiKNKhYEhjsMYj6l2nRg2CC0WIAA6MPP3xaezSWO1la39Slam0w3l"; // 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。 public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvxznkDcrpbc5HOXFJ6sQUkyKWLegU4CaAhyoi0A2ID4Y70l9eq9PEMPNqmHUIFhLOIRzctgjhgOZLMNXlvs8mNmpXb4pu3BwJ8hTzawCfuQ0QXYQYPj41exHKWIOS0WjKmjvKg0orPgFFOHu0DhC6jIK+8sQTUnEOipLJ1p87XBcc+jPU+unQGSdHVqYgfKmrTOrE/zHh0wF3mC4SG51GsTPbxiUdwCR2x5rzWvaNE6E9CwIDAQAB"; // 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 public static String notify_url = "http://localhost:8080/alipay/alipayNotifyNotice.action"; // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 public static String return_url = "http://localhost:8080/alipay/alipayReturnNotice.action"; // 签名方式 public static String sign_type = "RSA2"; // 字符编码格式 public static String charset = "utf-8"; // 支付宝网关 public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; // 支付宝网关 public static String log_path = "C:\\";//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ public static void logResult(String sWord) { FileWriter writer = null; try { writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt"); writer.write(sWord); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
其中的参数获取如下: app_id
商户私钥,以及支付宝公钥获取方法参考官方文档:密钥生成
页面跳转便是支付以后自动跳转的界面
接下来解释编写下单页面:
@RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8") @ResponseBody public String goAlipay(String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception { order = (Order) request.getSession().getAttribute("order"); orderId="FinchII"; //获得初始化的AlipayClient AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type); //设置请求参数 AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); alipayRequest.setReturnUrl(AlipayConfig.return_url); alipayRequest.setNotifyUrl(AlipayConfig.notify_url); //商户订单号,商户网站订单系统中唯一订单号,必填 String out_trade_no = orderId; //付款金额,必填 BigDecimal total_amount = order.getTotalPrice(); //订单名称,必填 int subject = order.getOrderId(); //商品描述,可空 String body = "用户订购商品个数:" + order.getLineItems().size(); // 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点, 如 1.5h,可转换为 90m。 String timeout_express = "1c"; alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," + "\"total_amount\":\""+ total_amount +"\"," + "\"subject\":\""+ subject +"\"," + "\"body\":\""+ body +"\"," + "\"timeout_express\":\""+ timeout_express +"\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); //请求 String result = alipayClient.pageExecute(alipayRequest).getBody(); return result; } @RequestMapping(value = "/alipayReturnNotice") public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception { //获取支付宝GET过来反馈信息 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] + ","; } //乱码解决,这段代码在出现乱码时使用 valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); params.put(name, valueStr); } boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名 ModelAndView mv = new ModelAndView("alipaySuccess"); //——请在这里编写您的程序(以下代码仅作参考)—— if(signVerified) { //商户订单号 Order order= (Order) request.getSession().getAttribute("order"); BigDecimal out_trade_no = order.getTotalPrice(); //支付宝交易号 String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"); //付款金额 String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8"); // 修改叮当状态,改为 支付成功,已付款; 同时新增支付流水 mv.addObject("out_trade_no", out_trade_no); mv.addObject("trade_no", trade_no); mv.addObject("total_amount", total_amount); }else { } return mv; } @RequestMapping(value = "/alipayNotifyNotice") @ResponseBody public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception { //获取支付宝POST过来反馈信息 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] + ","; } //乱码解决,这段代码在出现乱码时使用//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); params.put(name, valueStr); } boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名 //——请在这里编写您的程序(以下代码仅作参考)—— if(signVerified) {//验证成功 //商户订单号 String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"); //支付宝交易号 String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"); //交易状态 String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8"); //付款金额 String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8"); if(trade_status.equals("TRADE_FINISHED")){ //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 //注意: 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码 //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 }else if (trade_status.equals("TRADE_SUCCESS")){ //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 //注意: //付款完成后,支付宝系统发送该交易状态通知 // 修改叮当状态,改为 支付成功,已付款; 同时新增支付流水 } }else {//验证失败 } return "success"; }
上述内容就是怎么在Springboot中添加支付接口,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网行业资讯频道。