详解java集成支付宝支付接口(JSP+支付宝20160912)

时间:2022-08-31 19:48:39

吐槽一下:

支付宝的接口和微信的DEMO和文档真心太难看懂了,乱七八糟,都不知道去哪里找自己要的东西,最近几天我们公司需要做类似的开发,我作为先锋,率先解决Java集成支付宝支付和微信支付接口工作。

我们的工作环境:JSP网站+支付接口,目前工作的支付宝接口为20160912,微信为V3版本,如遇到版本升级,请联系相关机构的客户服务人员升级。

本文介绍JSP+支付宝接口,本文非原创。

新手注意:

1、本文使用的接口地址和参数为沙箱的地址,无论你在使用沙箱或者正式地址,务必核实使用接口地址和参数,不要想当然。

2、本文使用JAR包:

alipay-sdk-java20160912220103.jar

commons-codec-1.6.jar

commons-httpclient-3.0.1.jar

commons-logging-1.1.1.jar

fastjson-1.2.7.jar

json-lib-2.2.3-jdk13.jar

json.jar

jsp-api.jar

servlet-api.jar

说明:

alipay-sdk-java 是官方支付SDK,请到官方下载,本文使用版本20160912

首页调用:

?
1
2
3
4
5
6
<body>
  <%
  CsPay pay=new CsPay();
  pay.doPost(request, response);
  %>
 </body>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.luozhuang.alipay;
 
import java.util.HashMap;
import java.util.Map;
 
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
 
public class AlipayClientFactory {
  private static final AlipayClient client = new DefaultAlipayClient(
      Config.URL, Config.APPID, Config.RSA_RRIVATE_KEY, Config.FORMAT,
      Config.CHARSET, Config.ALIPAY_PUBLIC_KEY);
 
  public static AlipayClient getAlipayClientInstance() {
    return client;
  }
 
  /**
   * appAuthToken
   * 如ISV代替商家调用当面付接口,需将商户授权后获取的app_auth_token带上;如商家申请当面付自己调用,则传null bizContent
   * JSON格式 商户的请求参数
   */
 
  // 手机网页支付 网站支付
  public String ydAndPc_Pay(Map<String, String> maps)
      throws AlipayApiException {
    AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
    String NotifyUrl = maps.get("NotifyUrl");
    String ReturnUrl = maps.get("ReturnUrl");
    // 后台回调
    if (!StringUtils.isEmpty(NotifyUrl)) {
      alipayRequest.setNotifyUrl(NotifyUrl);
      // bizContent 中不需要 公共参数
      maps.remove("NotifyUrl");
    }
    // 页面回调
    if (!StringUtils.isEmpty(ReturnUrl)) {
      alipayRequest.setReturnUrl(ReturnUrl);
      // bizContent 中不需要 公共参数
      maps.remove("ReturnUrl");
    }
    String bizCon = JSON.toJSONString(maps);
    alipayRequest.setBizContent(bizCon);
    String form = "";
    try {
      form = AlipayClientFactory.getAlipayClientInstance()
          .pageExecute(alipayRequest).getBody();
    } catch (AlipayApiException e) {
      form = "err";
      e.printStackTrace();
    } // 调用SDK生成表单
    return form;
  }
 
  // 查询订单状态
  public AlipayTradeQueryResponse query(String appAuthToken, String bizContent)
      throws AlipayApiException {
    AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
    request.putOtherTextParam("app_auth_token", appAuthToken);
    request.setBizContent(bizContent);
    return AlipayClientFactory.getAlipayClientInstance().execute(request);
  }
 
  // 条码支付
  public AlipayTradePayResponse pay(String appAuthToken, String bizContent)
      throws AlipayApiException {
    AlipayTradePayRequest request = new AlipayTradePayRequest();
    request.putOtherTextParam("app_auth_token", appAuthToken);
    request.setBizContent(bizContent);
    return AlipayClientFactory.getAlipayClientInstance().execute(request);
  }
 
  // 扫码支付
  public AlipayTradePrecreateResponse precreate(String appAuthToken,
      String bizContent) throws AlipayApiException {
    AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
    request.putOtherTextParam("app_auth_token", appAuthToken);
    request.setBizContent(bizContent);
    return AlipayClientFactory.getAlipayClientInstance().execute(request);
  }
 
  // 订单撤销
  public AlipayTradeCancelResponse cancel(String appAuthToken,
      String bizContent) throws AlipayApiException {
    AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
    request.putOtherTextParam("app_auth_token", appAuthToken);
    request.setBizContent(bizContent);
    return AlipayClientFactory.getAlipayClientInstance().execute(request);
  }
 
  // 申请退款
  public AlipayTradeRefundResponse refund(String appAuthToken,
      String bizContent) throws AlipayApiException {
    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
    request.putOtherTextParam("app_auth_token", appAuthToken);
    request.setBizContent(bizContent);
    return AlipayClientFactory.getAlipayClientInstance().execute(request);
  }
 
  @SuppressWarnings("unused")
  public static void main(String[] args) {
    AlipayClientFactory c = new AlipayClientFactory();
    try {
      Map<String, String> map = new HashMap<String, String>();
      map.put("out_trade_no", "20160914113218");
      String bizContent = JSON.toJSONString(map);
      System.err.println(bizContent);
      AlipayTradeQueryResponse rp = c.query(null, bizContent);
    } catch (AlipayApiException e) {
      e.printStackTrace();
    }
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.luozhuang.alipay;
 
public class Config {
  // 开发者应用私钥。java配置PKCS8格式,PHP/.Net语言配置rsa_private_key.pem文件中原始私钥。
  public static final String RSA_RRIVATE_KEY ="luozhuang";
  // 接口请求网关。当面付支付、查询、退款、撤销接口中为固定值
  public static final String URL = "https://openapi.alipaydev.com/gateway.do";
  // 商户应用APPID,只要您的应用中包含当面付接口且是开通状态,就可以用此应用对应的appid。开发者可登录开放平台-管理中心-对应应用中查看
  public static final String APPID = "luozhuang";
  // 编码字符集。默认 utf-8
  public static final String CHARSET = "utf-8";
  // 返回格式。默认json
  public static final String FORMAT = "json";
  // 支付宝公钥,用于获取同步返回信息后进行验证,验证是否是支付宝发送的信息。
  public static final String ALIPAY_PUBLIC_KEY = "luozhuang";
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.luozhuang.alipay;
 
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alipay.api.AlipayApiException;
 
/**
 * Servlet implementation class CsPay
 */
public class CsPay extends HttpServlet {
  private static final long serialVersionUID = 1L;
 
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *   response)
   */
  public void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }
 
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *   response)
   */
  public void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    // 参数目前都是 写死的 根据业务需求 写活
    Map<String, String> maps = new HashMap<String, String>();
    maps.put("out_trade_no", UtilDate.getOrderNum());
    maps.put("total_amount", "0.01");
    maps.put("subject", "Iphone6 16G");
    maps.put("body", "Iphone6 16G");
    maps.put("product_code", "QUICK_WAP_PAY");
    // 下面两个 参数的 KEY 不要乱写 要和工具类里面对应
    maps.put("ReturnUrl", "http://domain.com/CallBack/return_url.jsp");
    maps.put("NotifyUrl", "http://domain.com/CallBack/notify_url.jsp");
    try {
      AlipayClientFactory ali = new AlipayClientFactory();
      String form = ali.ydAndPc_Pay(maps);
      if (!form.equals("err")) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
      }
    } catch (AlipayApiException e) {
      e.printStackTrace();
    }
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.luozhuang.alipay;
 import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
 
public class CsUtil {
  /**
   * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
   *
   * @param params
   *      需要排序并参与字符拼接的参数组
   * @return 拼接后字符串
   */
  public static String createLinkString(Map<String, String> params) {
 
    List<String> keys = new ArrayList<String>(params.keySet());
    Collections.sort(keys);
 
    String prestr = "";
 
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      String value = params.get(key);
 
      if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
        prestr = prestr + key + "=" + value;
      } else {
        prestr = prestr + key + "=" + value + "&";
      }
    }
 
    return prestr;
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.luozhuang.alipay;
import java.util.Date;
import java.util.Random;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
 
/* *
 *类名:UtilDate
 *功能:自定义订单类
 *详细:工具类,可以用作获取系统日期、订单编号等
 *版本:3.3
 *日期:2012-08-17
 *说明:
 *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
 */
public class UtilDate {
   
  /** 年月日时分秒(无下划线) yyyyMMddHHmmss */
  public static final String dtLong         = "yyyyMMddHHmmss";
   
  /** 完整时间 yyyy-MM-dd HH:mm:ss */
  public static final String simple         = "yyyy-MM-dd HH:mm:ss";
   
  /** 年月日(无下划线) yyyyMMdd */
  public static final String dtShort         = "yyyyMMdd";
   
   
  /**
   * 返回系统当前时间(精确到毫秒),作为一个唯一的订单编号
   * @return
   *   以yyyyMMddHHmmss为格式的当前系统时间
   */
  public static String getOrderNum(){
    Date date=new Date();
    DateFormat df=new SimpleDateFormat(dtLong);
    return df.format(date);
  }
   
  /**
   * 获取系统当前日期(精确到毫秒),格式:yyyy-MM-dd HH:mm:ss
   * @return
   */
  public static String getDateFormatter(){
    Date date=new Date();
    DateFormat df=new SimpleDateFormat(simple);
    return df.format(date);
  }
   
  /**
   * 获取系统当期年月日(精确到天),格式:yyyyMMdd
   * @return
   */
  public static String getDate(){
    Date date=new Date();
    DateFormat df=new SimpleDateFormat(dtShort);
    return df.format(date);
  }
   
  /**
   * 产生随机的三位数
   * @return
   */
  public static String getThree(){
    Random rad=new Random();
    return rad.nextInt(1000)+"";
  }
   
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/luozhuang/article/details/53809922