官方文档:https://opendocs.alipay.com/open/270/105899
本地开发环境支付回调调试方法可以参考:https://www.cnblogs.com/pxblog/p/11623053.html
所需内容:
1、APPID(APPID) 即创建应用后生成 获取:https://opendocs.alipay.com/open/200/105310
2、APP_PRIVATE_KEY(开发者私钥) 获取:https://opendocs.alipay.com/open/291/105971
3、ALIPAY_PUBLIC_KEY(支付宝公钥) 获取: https://opendocs.alipay.com/open/291/105971
jar包下载:https://yvioo.lanzous.com/iGR8pe3qkha
配置类
AliPayConfig.java
package com.alipay;
public class AliPayConfig {
/*******支付宝支付参数*********/
// 商户appid 教程:https://opendocs.alipay.com/open/200/105310
public static String APPID = "";
// 私钥 pkcs8格式的 由开发者自己生成 教程:https://opendocs.alipay.com/open/291/105971
public static String RSA\_PRIVATE\_KEY = "";
// 支付宝公钥 由支付宝生成 教程:https://opendocs.alipay.com/open/291/105971
public static String ALIPAY\_PUBLIC\_KEY = "";
// 服务器异步通知路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String notify\_url = "/alipay\_notice";
// 页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 商户可以自定义同步跳转地址
public static String return\_url = "/alipay\_return";
// 请求网关地址
public static String URL = "https://openapi.alipay.com/gateway.do";
// 编码
public static String CHARSET = "UTF-8";
// 返回格式
public static String FORMAT = "json";
// 日志记录目录
public static String log\_path = "/log";
// RSA2
public static String SIGNTYPE = "RSA2";
}
支付工具类
AliPay.java
package com.alipay;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import javax.servlet.http.HttpServletResponse;
public class AliPay {
/\*\*
\* PC网站快速支付
\*
\* @param response
\* @param orderNo 订单号
\* @param totalAmount 支付金额
\*/
public static void enterAlipayInPC(HttpServletResponse response,
String orderNo, Double totalAmount,String returnUrl,String notifyUrl) {
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APPID, AliPayConfig.RSA\_PRIVATE\_KEY,AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY\_PUBLIC\_KEY, AliPayConfig.SIGNTYPE);
//创建API对应的request
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//在公共参数中设置回跳地址
//同步跳转链接
alipayRequest.setReturnUrl(returnUrl);
//异步跳转链接
alipayRequest.setNotifyUrl(notifyUrl);
//填充业务数据
alipayRequest.setBizContent( "{" +
" \\"out\_trade\_no\\":\\""+orderNo+"\\"," +
" \\"product\_code\\":\\"FAST\_INSTANT\_TRADE\_PAY\\"," +
" \\"total\_amount\\":"+totalAmount+"," +
" \\"subject\\":\\"订单标题\\"," +
" \\"extend\_params\\":{" +
" \\"sys\_service\_provider\_id\\":\\"\\"" +
" }" +
" }" );//填充业务参数
String form;
try {
//调用SDK生成表单
form = alipayClient.pageExecute(alipayRequest).getBody();
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(form);//直接将完整的表单html输出到页面
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
控制器调用方法
AliPayController.java
package com.alipay;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Controller
public class AliPayController {
/\*\*
\* 支付宝PC支付,
\* 这只是简单的demo,需要自行完善逻辑
\*/
@RequestMapping(value = "/aliPCPay")
public void aliPay(HttpServletResponse response) {
//订单号
String orderNo = "";
//订单总金额,单位为元,精确到小数点后两位,取值范围\[0.01,100000000\]。 可以参考:https://www.cnblogs.com/pxblog/p/13186037.html
Double totalAmount = 1.00;
AliPay.enterAlipayInPC(response, orderNo, totalAmount,AliPayConfig.returnUrl,AliPayConfig.notifyUrl);
}
/\*\*
\* 支付宝异步通知地址
\*
\* @return
\* @throws IOException
\* @throws AlipayApiException
\*/
@RequestMapping(value = "/alipay\_notice")
public String alipayNotice(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException, AlipayApiException {
PrintWriter out = response.getWriter();
//获取支付宝POST过来反馈信息
Map<String, String> params = new HashMap<String, String>();
Map requestParams = request.getParameterMap();
for (Iterator 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\] + ",";
}
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
params.put(name, valueStr);
}
System.out.println(new JSONObject(params));
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
//商户订单号
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 sign = params.get("sign");
String content = AlipaySignature.getSignCheckContentV1(params);
boolean verify\_result = AlipaySignature.rsaCheck(content,sign, AliPayConfig.ALIPAY\_PUBLIC\_KEY, AliPayConfig.CHARSET,AliPayConfig.SIGNTYPE);
Order order = orderMng.findByOrderNo(out\_trade\_no);
//支付宝交易号
order.setTransactionId(trade\_no);
String result = "success";
System.out.println("订单编号:" + order.getOrderNo());
System.out.println("验证结果:" + verify\_result);
if (verify\_result) {
//验证成功
//判断支付宝是否返回付款成功状态
if ("TRADE\_SUCCESS".equalsIgnoreCase(trade\_status)){
//判断订单状态是否是未支付状态
if (!order.getStatus().equals(PayEnums.PAY\_SUCCESS.getCode())) {
order.setStatus(PayEnums.PAY\_SUCCESS.getCode());
orderMng.update(order);
}
System.out.println("支付成功");
}
out.println(result); //请不要修改或删除
out.flush();
out.close();
} else {
//验证失败
order.setStatus(PayEnums.PAY\_FAIL.getCode());
result = "fail";
orderMng.update(order);
System.out.println("支付失败");
out.println(result); //请不要修改或删除
out.flush();
out.close();
}
return null;
}
/\*\*
\* 支付宝同步通知页面请求
\*
\* @return
\*/
@RequestMapping(value = "/alipay\_return")
public String alipayReturn(HttpServletRequest request, ModelMap model) {
//跳转到支付结果页
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\] + ",";
}
//乱码解决,这段代码在出现乱码时使用
try {
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
params.put(name, valueStr);
}
boolean signVerified = false;
try {
//调用SDK验证签名
String sign = params.get("sign");
String content = AlipaySignature.getSignCheckContentV1(params);
signVerified = AlipaySignature.rsaCheck(content,sign, AliPayConfig.ALIPAY\_PUBLIC\_KEY, AliPayConfig.CHARSET,AliPayConfig.SIGNTYPE);
} catch (Exception e) {
e.printStackTrace();
}
String out\_trade\_no = null;
if (signVerified) {
//商户订单号
try {
out\_trade\_no = new String(request.getParameter("out\_trade\_no").getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
System.out.println("验签失败");
}
Order order = new Order();if (StringUtils.isNotBlank(out\_trade\_no)) {
order = orderMng.findByOrderNo(out\_trade\_no);
if (order != null) {
return "成功页面";
}
}
return "失败页面";
}
@Autowired
private OrderMng orderMng;
}
查询订单支付状态接口
官方文档地址:https://opendocs.alipay.com/apis/api_1/alipay.trade.query/
/**
* 交易查询
* @param out_trade_no 订单号
*/
public static AlipayTradeQueryResponse query(String out_trade_no) {
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APPID, AliPayConfig.RSA_PRIVATE_KEY,AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGNTYPE);
AlipayTradeQueryRequest alipayQueryRequest = new AlipayTradeQueryRequest();
String biz_content = "{\"out_trade_no\":\"" + out_trade_no + "\"}";
alipayQueryRequest.setBizContent(biz_content);
AlipayTradeQueryResponse alipayQueryResponse = null;
try {
alipayQueryResponse = alipayClient.execute(alipayQueryRequest);
if (null != alipayQueryResponse && alipayQueryResponse.isSuccess()) {
if (alipayQueryResponse.getCode().equals("10000")) {
if ("TRADE\_SUCCESS".equalsIgnoreCase(alipayQueryResponse
.getTradeStatus())) {
//表示支付成功
} else if ("TRADE\_CLOSED".equalsIgnoreCase(alipayQueryResponse
.getTradeStatus())) {
// 表示未付款关闭,或已付款的订单全额退款后关闭
} else if ("TRADE\_FINISHED".equalsIgnoreCase(alipayQueryResponse
.getTradeStatus())) {
// 此状态,订单不可退款或撤销
}
} else {
// 如果请求未成功,请重试
}
}
} catch (AlipayApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return alipayQueryResponse;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章