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+ROCZD8u9qQeGG7SSCovoTQcVDuzVA3bW8d4Guvb7ZTpnUZZyWHD2rOqxh66wqHGiVTJRApNTS7XHXt3FERNgM7Y8lSoYHdarsZ7QZaJDGGkcwuGvJM0klwyuqs6LQq5DRsz9qp8CgYEA1BkiCjD5FUE/i48MFh+qYcOSiqsm7Hrj/4zuHj0QODonuUZPH0V6b3p4SIWHeBsjmSxBsqoLh2qFOzWAUeBVU3+muPHp3uglumtjZ5wE0nHCt2+0ZH+QKSk5mm8j+09xfTJ185FMusx0N9RQ4l6Rpzb7DSLQFelT4M7gvTRjAhUCgYAtUPQwcV4DdBRiBLnHJ4xSGMjd3igmRQMEpRrUVzdathEFgvfiu3+xWLkDYO/PJdHXQ2KI07CIzHqo8WdYzPCb1V1wrQ7BdB06ilB04lSt59mGVyjax0Cu0RqmLhgKyeFBA2ppk6SnQtBhnEzNMF8jILYegpxR7A/JwshuwVjYSwKBgQCTxfMGgLp6iZxZgs/b9jICrX1DKh4Tc0e5PBqHbOoJEtOsbYUg94pncz+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:\\";
- //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
- /**
- * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
- * @param sWord 要写入日志里的文本内容
- */
- 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
商户私钥,以及支付宝公钥获取方法参考官方文档:密钥生成
页面跳转便是支付以后自动跳转的界面
接下来解释编写下单页面:
- /**
- *
- * @Title: AlipayController.java
- * @Package com.sihai.controller
- * @Description: 前往支付宝第三方网关进行支付
- * Copyright: Copyright (c) 2017
- * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
- */
- @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");
- // 修改叮当状态,改为 支付成功,已付款; 同时新增支付流水
- /* Orders order = orderService.getOrderById(out_trade_no);
- Product product = productService.getProductById(order.getProductId());
- log.info("********************** 支付成功(支付宝同步通知) **********************");
- log.info("* 订单号: {}", out_trade_no);
- log.info("* 支付宝交易号: {}", trade_no);
- log.info("* 实付金额: {}", total_amount);
- log.info("* 购买产品: {}", product.getName());
- log.info("***************************************************************");*/
- mv.addObject("out_trade_no", out_trade_no);
- mv.addObject("trade_no", trade_no);
- mv.addObject("total_amount", total_amount);
- /* mv.addObject("productName", product.getName());*/
- }else {
- /* log.info("支付, 验签失败...");*/
- }
- return mv;
- }
- /**
- *
- * @Title: AlipayController.java
- * @Package com.sihai.controller
- * @Description: 支付宝异步 通知页面
- * Copyright: Copyright (c) 2017
- * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
- *
- * @author sihai
- * @date 2017年8月23日 下午8:51:13
- * @version V1.0
- */
- @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验证签名
- //——请在这里编写您的程序(以下代码仅作参考)——
- /* 实际验证过程建议商户务必添加以下校验:
- 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,
- 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
- 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email)
- 4、验证app_id是否为该商户本身。*/
- 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)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
- //如果有做过处理,不执行商户的业务程序
- //注意:
- //付款完成后,支付宝系统发送该交易状态通知
- // 修改叮当状态,改为 支付成功,已付款; 同时新增支付流水
- /* orderService.updateOrderStatus(out_trade_no, trade_no, total_amount);
- Orders order = orderService.getOrderById(out_trade_no);
- Product product = productService.getProductById(order.getProductId());
- log.info("********************** 支付成功(支付宝异步通知) **********************");
- log.info("* 订单号: {}", out_trade_no);
- log.info("* 支付宝交易号: {}", trade_no);
- log.info("* 实付金额: {}", total_amount);
- log.info("* 购买产品: {}", product.getName());
- log.info("***************************************************************");*/
- }
- /* log.info("支付成功...");*/
- }else {//验证失败
- /* log.info("支付, 验签失败...");*/
- }
- return "success";
- }
基本就是根据客服下单的信息进行后端数据的获取。
以上就是springboot添加支付接口的详细内容,更多关于springboot 加支付接口的资料请关注服务器之家其它相关文章!
原文链接:https://juejin.cn/post/6949465301717123102