调用支付宝接口的简单demo

依赖:

1 
2         
3             com.alipay.sdk
4             alipay-sdk-java
5             3.4.49.ALL
6         

配置类:

 1 package com.sdk.pay.alipay;
 2 
 3 public class AlipayConfig {
 4     // 商户appid
 5     public static String APPID = "2016102100729846";
 6     // 私钥 pkcs8格式的
 7     public static String RSA_PRIVATE_KEY =
 8                     "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHiiREGifXUNV4" +
 9                     "2QJixj0NEq4DgOBhjA3lTdQxCrJBeOBz7UUPXQfKw39LGKhoyrgPmJKzYwWosfIl" +
10                     "mFk4qvGGsxbvuIGW8aUpxwFR9PmUetgoLroko/6mddnCA1+pSkBVA2vZhKO7MgZc" +
11                     "onfJN305izNcGMSbYm20W0mAnmRCZgux5nZpFq6kUYP45WAmyMUoXVQOrUOb6Ec0" +
12                     "6+CPuTpeV32IWpW6Sr/Ukvxt6BNw+XMhwM7vrIYsN8RW50aMsOlTwACQ19G5EOKe" +
13                     "vA07urMxwdeEoDxggYFG0o4As6IxzlUdd4eYWKOuX1l0/zZpOCxQiMrXrv+eRZFa" +
14                     "lBPvN++3AgMBAAECggEAEt73qxEmL3DPn4w2c4z3/SKFHoOztMYAEm2X4cN3NEXw" +
15                     "REZuP5O2xvBSO5Hra22wlpkBVsHIqTmbAv8zgO55xRlu0+EJMHNOAXN2pn+akvZD" +
16                     "NxmkNQ7laGzA2V5kT6hcCS43puyqZ2vFukELPxZmW2jUxKL7BQ77/RCdFPLl3HmL" +
17                     "QEJsOITqf7+q8pMWaaKF3mesqzz8AGzD0LC/pQwCh7h6ur0ojle6hDslHMK7UkEY" +
18                     "QUTK+Kz6ZGgXJWIc3xsE0oG6O/+QgAgssoaKgDPFmzfOt4yq4cfCzx8xlDCBDmC6" +
19                     "hdqdegwICxqxmbKlp9cRnLnEOv3Q5gUB0YlorM3e8QKBgQD1eIeUJkyM2v1Gobtm" +
20                     "eOFdtblc2E5cy2P5DGC5nawCtpK3kIGDxDM8Np5xasRkwsaSovQkH1bJ5ocStwLX" +
21                     "rDOj57oENrdieIGEHP8ffpAVsa7SgTYUjwdyA79FsMEZWX1PanbqF7J3NS2coneg" +
22                     "HVkdPQXRkmXMuJ/l96ZSMxGfJQKBgQDQGT/4B8LSCv62WaQHMnMyNdxCbg/135ov" +
23                     "suMymgGre13onOblCyUb3SnvOAO1vnSHWNbmj5Knz5/cRYzxBAPXaJ0gYVJkMxEy" +
24                     "nQelWCBhPRqfRIjeHTN9F98g2fsTArPy1zhR+NzwSdRx4aL08beDOwYIMPZuTGod" +
25                     "xmt58L96qwKBgGQDXcog6KOjPfqfPsl7iucxeXq4rwTj4bHBN0+pTEI2vQSJnhtf" +
26                     "vzhTUK8JP0eGjH2GY06sbiIJCRO4+TGCee/YJFQ/LuyyCKMZZWEhofcU1BP0jWJG" +
27                     "/FOZ7z6ny6VWbtYCnLy4NwCW7CSblX3pNzvQdyRyL4P/3TZHdr6bDBz5AoGBAJQW" +
28                     "w+0QKNYsuOKvnAj7H/tFVP95L6Z7f1Aeb4xdCH8uBcA5mB669aeElgkExa8aX/bJ" +
29                     "g/UDiwwctticLhZ+EvXCHr8iQu3HYZ+xG/XQZwqL31wj+3qFMVT+He1U8lWvALv5" +
30                     "6Lx8602cXLDGL588PKoI4NwHa/dGLeYOhAF9D+aNAoGBAK6geTKYSbdh/0IEBxSx" +
31                     "kMVx4D1pYKUOgTEqGuw7IYeNrwwE/F/SVhgkpAvz3ppYUM+bsPHbofEu7W/uanP8" +
32                     "2Akf8D0dpTcQju+6MuQmCPcLmJSq2pqVNHG4gUnzz5CZoi+IrK/VMTXfU2O+i+H0" +
33                     "rGQXtgvpSTBHlrcRklSvYjaC";
34     // 服务器异步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
35     public static String notify_url = "http://28k6010n77.wicp.vip/callback.html";
36     // 页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 商户可以自定义同步跳转地址
37     public static String return_url = "http://28k6010n77.wicp.vip/return.html";
38     // 请求网关地址
39     public static String URL = "https://openapi.alipaydev.com/gateway.do";
40     // 编码
41     public static String CHARSET = "UTF-8";
42     // 返回格式
43     public static String FORMAT = "json";
44     // 支付宝公钥
45     public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAov3L35qUSYI2E5iDZmjXgJJs4cWKW2LhaddgKw5D7UgFYOcOv/ZYf5SdiWVk4tjhhJxFy1iDRxB+V5d0KD0cOc0PHBA0jQ6UfEu1BSV6rNL+ipgF1xLDudwT+iuVyKg2EEkFWb14Mm1D06qqen7yQyftzCU4TQ/gOUBzHcrQ5HJ1TxqgP0kHRUwe44utEwAMYNgJk9hxZ01ULVBQVAVxjGirju47OSIjnOCIfhk1fMrHIZreZFPp5uhzluJnIUHRugw+w7MunWy3iAOpNM47FKs4RuV/YHqeEdc1jFflAmeJhXT84ySuQZc6ZkwpY3JJc4ObGIchSj3SOqy1iSN9BwIDAQAB";
46     // 日志记录目录
47     public static String log_path = "/log";
48     // RSA2
49     public static String SIGNTYPE = "RSA2";
50 }

controller:

  1 package com.sdk.pay.controller;
  2 
  3 import com.alipay.api.AlipayApiException;
  4 import com.alipay.api.AlipayClient;
  5 import com.alipay.api.DefaultAlipayClient;
  6 import com.alipay.api.domain.AlipayTradeWapPayModel;
  7 import com.alipay.api.internal.util.AlipaySignature;
  8 import com.alipay.api.request.AlipayTradeWapPayRequest;
  9 
 10 import com.sdk.pay.alipay.AlipayConfig;
 11 import org.springframework.stereotype.Controller;
 12 import org.springframework.web.bind.annotation.RequestMapping;
 13 
 14 import javax.servlet.http.HttpServletRequest;
 15 import javax.servlet.http.HttpServletResponse;
 16 import java.io.PrintWriter;
 17 import java.util.HashMap;
 18 import java.util.Iterator;
 19 import java.util.Map;
 20 
 21 
 22 @Controller
 23 public class AliPayController {
 24     @RequestMapping("ali.html")
 25     public String page() {
 26         return "alipay";
 27     }
 28 
 29     @RequestMapping("alipay.html")
 30     public void order(HttpServletRequest request, HttpServletResponse response, Integer amount) throws Exception {
 31         // 商户订单号,商户网站订单系统中唯一订单号,必填
 32         String out_trade_no = System.currentTimeMillis() + "";
 33         // 订单名称,必填
 34         String subject = "测试";
 35         System.out.println(subject);
 36         // 付款金额,必填
 37         String total_amount = amount.toString();
 38         // 超时时间 可空
 39         String timeout_express = "2m";
 40         // 销售产品码 必填
 41         String product_code = "QUICK_WAP_WAY";
 42         /**********************/
 43         // SDK 公共请求类,包含公共请求参数,以及封装了签名与验签,开发者无需关注签名与验签
 44         //调用RSA签名方式
 45         AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
 46         AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();
 47 
 48         // 封装请求支付信息
 49         AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
 50         model.setOutTradeNo(out_trade_no);
 51         model.setSubject(subject);
 52         model.setTotalAmount(total_amount);
 53         // model.setBody(body);
 54         model.setTimeoutExpress(timeout_express);
 55         model.setProductCode(product_code);
 56         alipay_request.setBizModel(model);
 57         // 设置异步通知地址
 58         alipay_request.setNotifyUrl(AlipayConfig.notify_url);
 59         // 设置同步地址
 60         alipay_request.setReturnUrl(AlipayConfig.return_url);
 61 
 62         // form表单生产
 63         String form = "";
 64         try {
 65             // 调用SDK生成表单
 66             form = client.pageExecute(alipay_request).getBody();
 67             System.out.println(form);
 68             response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
 69             response.getWriter().write(form);//直接将完整的表单html输出到页面
 70             response.getWriter().flush();
 71             response.getWriter().close();
 72         } catch (AlipayApiException e) {
 73             // TODO Auto-generated catch block
 74             e.printStackTrace();
 75         }
 76     }
 77 
 78     @RequestMapping("callback.html")//以回调方法为准
 79     public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
 80         System.out.println("支付回调============callback.html==================================");
 81         PrintWriter out = response.getWriter();
 82         //获取支付宝POST过来反馈信息
 83         Map params = new HashMap();
 84         Map requestParams = request.getParameterMap();
 85         for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
 86             String name = (String) iter.next();
 87             String[] values = (String[]) requestParams.get(name);
 88             String valueStr = "";
 89             for (int i = 0; i < values.length; i++) {
 90                 valueStr = (i == values.length - 1) ? valueStr + values[i]
 91                         : valueStr + values[i] + ",";
 92             }
 93             //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
 94             //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
 95             params.put(name, valueStr);
 96         }
 97         //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
 98         //商户订单号
 99 
100         String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
101         //支付宝交易号
102 
103         String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
104 
105         //交易状态
106         String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
107 
108         //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
109         //计算得出通知验证结果
110         //boolean AlipaySignature.rsaCheckV1(Map params, String publicKey, String charset, String sign_type)
111         boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
112 
113         if (verify_result) {//验证成功
114             //////////////////////////////////////////////////////////////////////////////////////////
115             //请在这里加上商户的业务逻辑程序代码
116 
117             //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
118 
119             if (trade_status.equals("TRADE_FINISHED")) {
120                 //判断该笔订单是否在商户网站中已经做过处理
121                 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
122                 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
123                 //如果有做过处理,不执行商户的业务程序
124 
125                 //注意:
126                 //如果签约的是可退款协议,退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
127                 //如果没有签约可退款协议,那么付款完成后,支付宝系统发送该交易状态通知。
128             } else if (trade_status.equals("TRADE_SUCCESS")) {
129                 //判断该笔订单是否在商户网站中已经做过处理
130                 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
131                 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
132                 //如果有做过处理,不执行商户的业务程序
133                 //注意:
134                 //如果签约的是可退款协议,那么付款完成后,支付宝系统发送该交易状态通知。
135                 //更新订单
136                 System.out.println("商户订单号:" + out_trade_no);
137                 System.out.println("支付宝订单号:" + trade_no);
138                 System.out.println("支付宝金额:" + request.getParameter("total_amount"));
139             }
140 
141             //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
142             out.println("success");    //请不要修改或删除
143 
144             //////////////////////////////////////////////////////////////////////////////////////////
145         } else {//验证失败
146             out.println("fail");
147         }
148         out.close();
149     }
150 
151     @RequestMapping("return.html")//只给用户一个提示
152     public void success(HttpServletRequest request, HttpServletResponse response) throws Exception {
153         System.out.println("return.html======只给用户一个提示========================================");
154         response.setCharacterEncoding("utf-8");
155         response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
156         PrintWriter out = response.getWriter();
157         //获取支付宝GET过来反馈信息
158         Map params = new HashMap();
159         Map requestParams = request.getParameterMap();
160         for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
161             String name = (String) iter.next();
162             String[] values = (String[]) requestParams.get(name);
163             String valueStr = "";
164             for (int i = 0; i < values.length; i++) {
165                 valueStr = (i == values.length - 1) ? valueStr + values[i]
166                         : valueStr + values[i] + ",";
167             }
168             //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
169             //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
170             System.out.println(valueStr);
171             params.put(name, valueStr);
172         }
173         System.out.println(params);
174         //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
175         //商户订单号
176 
177         String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
178 
179         //支付宝交易号
180 
181         String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
182 
183         //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
184         //计算得出通知验证结果
185         //boolean AlipaySignature.rsaCheckV1(Map params, String publicKey, String charset, String sign_type)
186         boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
187 
188         if (verify_result) {//验证成功
189             //////////////////////////////////////////////////////////////////////////////////////////
190             //请在这里加上商户的业务逻辑程序代码
191             //该页面可做页面美工编辑
192             out.flush();
193             out.println("验证成功
"); 194 //——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— 195 196 ////////////////////////////////////////////////////////////////////////////////////////// 197 } else { 198 //该页面可做页面美工编辑 199 out.flush(); 200 out.println("验证失败"); 201 } 202 out.close(); 203 } 204 }

html:

 1 DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Titletitle>
 6 head>
 7 <body>
 8 <form action="alipay.html" method="post">
 9     金额<input name="amount"/>
10     <input type="submit" value="提交"/>
11 form>
12 body>
13 html>

你可能感兴趣的:(调用支付宝接口的简单demo)