[关闭]
@kangwg 2017-04-09T14:37:05.000000Z 字数 7921 阅读 1397

layout: post
title: "支付宝支付"
subtitle: "app支付,网页支付,扫码支付"
date: 2017-04-09 12:00:00
author: "kangwg"
header-img: "img/post-bg-2015.jpg"
catalog: true

- 支付宝

先导入第三方jar包
建立基类,所有支付类型都继承它

  1. import java.util.*;
  2. import org.slf4j.*;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.stereotype.Service;
  5. import com.alipay.api.*;
  6. import com.alipay.api.internal.util.AlipaySignature;
  7. import com.alipay.api.request.*;
  8. import com.alipay.api.response.*;
  9. import cn.swao.baselib.util.*;
  10. @Service
  11. public class AliParamService {
  12. private static Logger log = LoggerFactory.getLogger(AliParamService.class);
  13. @Value("${partner:}")
  14. protected String partner;
  15. @Value("${private_key:}")
  16. protected String private_key;
  17. @Value("${public_key:}")
  18. protected String public_key;
  19. @Value("${alipay_public_key:}")
  20. protected String alipay_public_key;
  21. @Value("${notify_url:}")
  22. protected String notify_url;
  23. @Value("${app_id:}")
  24. protected String app_id;
  25. @Value("${timeout_express:}")
  26. protected String timeout_express;
  27. protected String sign_type = "RSA";
  28. protected String input_charset = "utf-8";
  29. protected String format = "json";
  30. protected String version = "1.0";
  31. protected AlipayClient alipayClient = null;
  32. public void getClient(String requestUrl) {
  33. alipayClient = new DefaultAlipayClient(requestUrl, app_id, private_key, format, input_charset, alipay_public_key);
  34. }
  35. // 异步 synNotify
  36. public boolean asynNotify(Map<String, String> map) {
  37. boolean flag = false;
  38. try {
  39. log.info(LogUtils.gen("map", map));
  40. if (partner.equals(map.get("seller_id")) && app_id.equals(map.get("app_id"))) {
  41. log.info("partner:" + partner + "seller_id" + map.get("seller_id"));
  42. flag = AlipaySignature.rsaCheckV1(map, alipay_public_key, input_charset);
  43. }
  44. } catch (AlipayApiException e) {
  45. log.info("异步通知校验失败", e);
  46. flag = false;
  47. }
  48. return flag;
  49. }
  50. // 同步
  51. public boolean synNotify(Map<String, String> alipay, String sign) {
  52. boolean flag = false;
  53. log.info("同步验证参数,alipay={},sign={}", alipay, sign);
  54. try {
  55. if (partner.equals(alipay.get("seller_id")) && app_id.equals(alipay.get("app_id"))) {
  56. log.info("开始同步签名验证");
  57. flag = AlipaySignature.rsaCheckContent(JSONUtils.toJson(alipay).toString(), sign, alipay_public_key, input_charset);
  58. }
  59. } catch (AlipayApiException e) {
  60. log.info("同步通知校验失败", e);
  61. flag = false;
  62. }
  63. return flag;
  64. }
  65. /**
  66. * out_trade_no 支付时传入的商户订单号,与trade_no必填一个 trade_no 支付时返回的支付宝交易号,与out_trade_no必填一个
  67. */
  68. public String queryOrder(Map<String, String> map) {
  69. AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();// 创建API对应的request类
  70. AlipayTradeQueryResponse response = null;
  71. String result = null;
  72. try {
  73. request.setBizContent(JSONUtils.toJson(AlipayCore.emptyFilter(map)).toString());// 设置业务参数
  74. response = alipayClient.execute(request);
  75. result = response.getBody();
  76. } catch (AlipayApiException e) {
  77. log.info("查询订单失败{}", map);
  78. }
  79. return result;
  80. }
  81. // 退款
  82. public Map<String, Object> refund(Map<String, String> map) {
  83. log.info("ali开始退款");
  84. log.info(LogUtils.gen("map", map));
  85. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  86. request.setBizContent(JSONUtils.toJson(AlipayCore.emptyFilter(map)).toString());
  87. AlipayTradeRefundResponse response = null;
  88. boolean flag = false;
  89. String msg = null;
  90. String subCode = null;
  91. String out_trade_no = null;
  92. Map<String, Object> data = new HashMap<String, Object>();
  93. try {
  94. response = alipayClient.execute(request);
  95. out_trade_no = response.getOutTradeNo();
  96. // Map body = WebUtils.getJsonParams(response.getBody());
  97. } catch (Exception e) {
  98. msg = "退款失败:" + e;
  99. log.info(msg);
  100. data.put("flag", flag);
  101. data.put("msg", "退款失败");
  102. return data;
  103. }
  104. if (response != null && response.isSuccess()) {
  105. String fundChange = response.getFundChange();
  106. if ("Y".equals(fundChange)) {
  107. flag = true;
  108. msg = "退款成功";
  109. data.put("out_trade_no", out_trade_no);
  110. data.put("refund_fee", response.getRefundFee());
  111. data.put("gmtRefundPay", response.getGmtRefundPay());
  112. data.put("buyer_logon_id", response.getBuyerLogonId());
  113. } else if ("N".equals(fundChange)) {
  114. msg = "已完成退款,不可重复退款";
  115. flag = false;
  116. }
  117. } else {
  118. msg = response.getSubMsg();
  119. subCode = response.getSubCode();
  120. flag = false;
  121. }
  122. data.put("msg", msg);
  123. data.put("flag", flag);
  124. data.put("subCode", subCode);
  125. log.info(LogUtils.gen("refund return", "out_trade_no", out_trade_no, "msg", msg, "subCode", subCode));
  126. return data;
  127. }
  128. }

基类提供了获取支付对象、查询、退款的方法
1.app支付

  1. import java.util.*;
  2. import javax.annotation.PostConstruct;
  3. import org.slf4j.*;
  4. import org.springframework.stereotype.Service;
  5. import com.alipay.api.AlipayApiException;
  6. import com.alipay.api.internal.util.AlipaySignature;
  7. import cn.swao.baselib.util.*;
  8. @Service
  9. public class AlipayService extends AliParamService {
  10. private static Logger log = LoggerFactory.getLogger(AlipayService.class);
  11. private String method = "alipay.trade.app.pay";
  12. private String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
  13. @PostConstruct
  14. public void init() {
  15. super.getClient(ALIPAY_GATEWAY_NEW);
  16. }
  17. // 获取签名
  18. public String buildRequestPara(Map<String, String> sParaTemp) throws Exception {
  19. log.info("ali开始获取签名");
  20. log.info(LogUtils.gen("sParaTemp", sParaTemp));
  21. Map<String, String> map = new HashMap<String, String>();
  22. map.put("app_id", app_id);
  23. map.put("method", method);
  24. map.put("format", format);
  25. map.put("charset", input_charset);
  26. map.put("sign_type", sign_type);
  27. map.put("notify_url", notify_url);
  28. map.put("timestamp", DateUtils.toDateTimeString(new Date()));
  29. map.put("version", version);
  30. sParaTemp.put("seller_id", partner);
  31. sParaTemp.put("timeout_express", timeout_express);
  32. map.put("biz_content", JSONUtils.toJson(sParaTemp).toString());
  33. String sign = AlipaySignature.rsaSign(map, private_key, input_charset);
  34. map.put("sign", sign);
  35. String linkString = AlipayCore.encodeMap2String(map);
  36. log.info("签名alipay:" + linkString);
  37. return linkString;
  38. }
  39. }

其他app支付的验签查询的方法都来自父类

2.网页支付和扫码支付

  1. import cn.swao.baselib.util.JSONUtils;
  2. import com.alipay.api.AlipayApiException;
  3. import com.alipay.api.request.AlipayTradePrecreateRequest;
  4. import com.alipay.api.request.AlipayTradeWapPayRequest;
  5. import com.alipay.api.response.AlipayTradePrecreateResponse;
  6. import org.assertj.core.util.Strings;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.stereotype.Service;
  11. import javax.annotation.PostConstruct;
  12. import java.io.UnsupportedEncodingException;
  13. import java.net.URLEncoder;
  14. import java.util.Map;
  15. @Service
  16. public class AliMpService extends AliParamService {
  17. private static Logger log = LoggerFactory.getLogger(AliMpService.class);
  18. private String method = "alipay.trade.wap.pay";
  19. private String ALIPAY_OPEN_NEW = "https://openapi.alipay.com/gateway.do";
  20. private String apiVersion = "3";
  21. private String product_code = "QUICK_WAP_PAY";
  22. @Value("${returnUrl:}")
  23. private String return_url;
  24. @Value("${qrCodeUrl:}")
  25. public String LIANTU_URL;//生成二维码
  26. @PostConstruct
  27. public void init() {
  28. super.getClient(ALIPAY_OPEN_NEW);
  29. }
  30. // 手机网站支付下单
  31. public String buildRequestPara(Map<String, String> sParaTemp) throws Exception {
  32. AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();// 创建API对应的request
  33. alipayRequest.setNotifyUrl(notify_url);
  34. alipayRequest.setApiVersion(apiVersion);
  35. if (!Strings.isNullOrEmpty(sParaTemp.get("selfparam"))) {
  36. String returnUrl = new StringBuffer(return_url).append("?selfparam=").append(sParaTemp.get("selfparam")).toString();
  37. alipayRequest.setReturnUrl(returnUrl);
  38. sParaTemp.remove("selfparam");
  39. } else {
  40. alipayRequest.setReturnUrl(return_url);
  41. }
  42. sParaTemp.put("product_code", product_code);
  43. String biz_content = JSONUtils.toJson(AlipayCore.emptyFilter(sParaTemp)).toString();
  44. alipayRequest.setBizContent(biz_content);
  45. log.info("支付宝手机网站支付业务参数:{}", alipayRequest);
  46. String form = super.alipayClient.pageExecute(alipayRequest).getBody();
  47. log.info("支付宝手机网站支付下单后参数:{}", form);
  48. return form;
  49. }
  50. /**
  51. * 扫码支付生成二维码 map中必要参数 out_trade_no,total_amount,subject,store_id(门店编号)
  52. */
  53. public String buildRequestQrCode(Map<String, String> sParaTemp) {
  54. AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
  55. request.setNotifyUrl(notify_url);
  56. sParaTemp.put("timeout_express", timeout_express);
  57. String bizContent = JSONUtils.toJson(sParaTemp);
  58. request.setBizContent(bizContent);
  59. log.info("扫码预下单:sParaTemp:{}", sParaTemp);
  60. try {
  61. AlipayTradePrecreateResponse execute = super.alipayClient.execute(request);
  62. String qrCode = execute.getQrCode();
  63. String qrCodeUrl = LIANTU_URL + URLEncoder.encode(qrCode, "UTF-8");
  64. String body = execute.getBody();
  65. log.info("qrCode:{},qrCodeUrl:{},AlipayTradePrecreateResponse.Body:{}", qrCode, qrCodeUrl, body);
  66. return qrCodeUrl;
  67. } catch (AlipayApiException | UnsupportedEncodingException e) {
  68. log.error("扫码预下单失败", e);
  69. return null;
  70. }
  71. }
  72. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注