这里结合别人网上的教程
详细请点
写了支付宝沙箱支付,查询,和退款
pom.xml
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.0.1</version>
</dependency>
前端需要传送相应参数
这里是后端代码
package com.springboot.demospringboot.alpay;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Controller
public class alipay {
// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
public static String app_id = "2016id";
// 商户私钥,您的PKCS8格式RSA2私钥
public static String merchant_private_key = "";
// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
public static String alipay_public_key = "";
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String notify_url = "http://127.0.0.1/success";
// public static String notify_url = "https://test.utools.club/success";
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String return_url = "http://127.0.0.1/success";
// public static String return_url = "https://test.utools.club/success";
// 签名方式
public static String sign_type = "RSA2";
// 字符编码格式
public static String charset = "utf-8";
//沙箱网关
public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
// 仅支持JSON
public static String format = "JSON";
// @ApiOperation(value = "发起支付", notes = "支付宝")
public static String out_trade_no = "";
public static double total_amout = 0;
public static String subject = "";
SimpleDateFormat format_trade = new SimpleDateFormat("yyyyMMddHHmmss");
@RequestMapping(value = "/pay", method = RequestMethod.POST)
public void pay(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws ServletException, IOException {
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, format, charset,
alipay_public_key, sign_type); // 获得初始化的AlipayClient
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
alipayRequest.setReturnUrl(return_url);
alipayRequest.setNotifyUrl(notify_url);// 在公共参数中设置回跳和通知地址
subject = "商品标题/交易名称";
out_trade_no = format_trade.format(new Date());
total_amout = (int) (Math.random() * 1000) + 0.88;
String order = httpRequest.getParameter("order");
String shopname = httpRequest.getParameter("name");
String price = httpRequest.getParameter("price");
System.out.println(price);
if (price != "") {
total_amout = Double.parseDouble(price);
}
if (order != "") {
out_trade_no = order;
}
if (shopname != "") {
subject = shopname;
}
alipayRequest.setBizContent("{" + " \"out_trade_no\":\"" + out_trade_no + "\","
+ " \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + " \"total_amount\":" + total_amout + ","
+ " \"subject\":\"" + subject + "\"," + " \"body\":\"Iphone6 16G 耐克金\",\"timeout_express\":\"1m\""
+ ", \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","
+ " \"extend_params\":{" + " \"sys_service_provider_id\":\"2088511833207846\"" + " }" + " }");// 填充业务参数
String form = "";
try {
form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
} catch (AlipayApiException e) {
e.printStackTrace();
}
httpResponse.setContentType("text/html;charset=" + charset);
httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
httpResponse.getWriter().flush();
httpResponse.getWriter().close();
}
// @ApiOperation(value = "支付异步回调", notes = "支付宝")
@RequestMapping(value = "/success", method = RequestMethod.POST)
public void notifyUrl(HttpServletRequest request, HttpServletResponse response)
throws AlipayApiException, IOException {
System.out.println("#################################支付异步回调######################################");
// 获取支付宝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);
}
System.out.println(params);
boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, 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 return_trade = 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 return_name = request.getParameter("subject");
// 获取中文乱码把它改成不用string换码
// 交易状态
String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
double money = Double.parseDouble(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));
System.out.println("支付宝:商户订单号=" + return_trade);
System.out.println("支付宝:支付宝交易号=" + trade_no);
System.out.println("支付宝:交易状态=" + trade_status);
if (return_trade.equals(out_trade_no) && money == total_amout && subject.equals(return_name)) {
System.out.println("验证成功!");
} else {
System.out.println("验证失败");
System.out.println(money + ":" + total_amout);
System.out.println(subject + ":" + return_name);
}
if (trade_status.equals("TRADE_FINISHED")) {
// 判断该笔订单是否在商户网站中已经做过处理
// 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
// 如果有做过处理,不执行商户的业务程序
// 注意:
// 退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
} else if (trade_status.equals("TRADE_SUCCESS")) {
// 判断该笔订单是否在商户网站中已经做过处理
// 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
// 如果有做过处理,不执行商户的业务程序
// 注意:
// 付款完成后,支付宝系统发送该交易状态通知
}
System.out.println("异步回调验证成功");
response.getWriter().write("success");
} else {// 验证失败
System.out.println("异步回调验证失败");
response.getWriter().write("fail");
// 调试用,写文本函数记录程序运行情况是否正常
// String sWord = AlipaySignature.getSignCheckContentV1(params);
// AlipayConfig.logResult(sWord);
}
response.getWriter().flush();
response.getWriter().close();
}
// @ApiOperation(value = "支付同步回调", notes = "支付宝")
@RequestMapping(value = "/success", method = RequestMethod.GET)
public String returnUrl(HttpServletRequest request, HttpServletResponse response, Model m)
throws IOException, AlipayApiException {
System.out.println("=================================支付同步回调=====================================");
// 获取支付宝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);
}
System.out.println(params);
// 验证公钥和编码和签名
boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type);
// ——请在这里编写您的程序(以下代码仅作参考)——
if (signVerified) {
// 商户订单号
String return_trade = 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 total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
System.out.println("商户订单号=" + out_trade_no);
System.out.println("支付宝交易号=" + trade_no);
System.out.println("付款金额=" + total_amount);
// response.setHeader("refresh", "5;url=https://test.utools.club");
response.setHeader("refresh", "5;url=http://hhb688.cn");
m.addAttribute("order", out_trade_no);
m.addAttribute("price", total_amount);
m.addAttribute("id", trade_no);
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, format, charset,
alipay_public_key, sign_type);
AlipayTradeQueryRequest checkrequest = new AlipayTradeQueryRequest();
checkrequest.setBizContent("{" +
"\"out_trade_no\":\"" + out_trade_no + "\"" +
" }");
AlipayTradeQueryResponse checkresponse = alipayClient.execute(checkrequest);
if (checkresponse.isSuccess()) {
m.addAttribute("check", "已支付成功");
} else {
m.addAttribute("check", "未支付");
}
} else {
return "error";
}
return "success";
}
@RequestMapping(value = "/checkquery", method = RequestMethod.POST)
public void check(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, format, charset,
alipay_public_key, sign_type);
String order = request.getParameter("order");
if (order != "") {
out_trade_no = order;
}
AlipayTradeQueryRequest checkrequest = new AlipayTradeQueryRequest();
checkrequest.setBizContent("{" +
"\"out_trade_no\":\"" + out_trade_no + "\"" +
" }");
AlipayTradeQueryResponse checkresponse = alipayClient.execute(checkrequest);
if (checkresponse.isSuccess()) {
response.getWriter().println("宁的订单已支付");
} else {
response.getWriter().println("宁的订单不存在或者未支付成功");
}
}
@RequestMapping(value = "/returnpay", method = RequestMethod.POST)
public void returnpay(HttpServletRequest req, HttpServletResponse resp)throws IOException,AlipayApiException{
String check=req.getParameter("check");
String return_trade=req.getParameter("order");
String return_price=req.getParameter("price");
System.out.println("c"+check+"t"+return_trade+"p"+return_price);
if(return_price!=""){total_amout=Double.parseDouble(return_price);}
if(return_trade!=""){out_trade_no=return_trade;}
if(check.equals("1")) {//这里查询是否同意第一步
AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, format, charset,
alipay_public_key, sign_type);
AlipayTradeQueryRequest checkrequest = new AlipayTradeQueryRequest();//判断金额是否一致第二步,有包含查询
checkrequest.setBizContent("{" +
"\"out_trade_no\":\"" + out_trade_no + "\"" +
" }");
AlipayTradeQueryResponse checkresponse = alipayClient.execute(checkrequest);
System.out.println("total"+checkresponse.getTotalAmount());
if (checkresponse.isSuccess()) {
if(total_amout!=Double.parseDouble(checkresponse.getTotalAmount())){
resp.getWriter().println("输入金额和订单不符");
return;
}
} else {
resp.getWriter().println("宁的订单不存在或者未支付成功");//订单不存在
return;
}
//这里开始退款
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
request.setBizContent("{" +
"\"out_trade_no\":\"" + out_trade_no + "\"," +
"\"refund_amount\":" + total_amout +
" }");
AlipayTradeRefundResponse response = alipayClient.execute(request);
if (response.isSuccess()) {
System.out.println("调用成功");
resp.getWriter().println("退款成功!");
} else {
System.out.println("调用失败");
resp.getWriter().println("退款失败!");
}
}
else{
resp.getWriter().println("已发货或未同意退款!");
}
}
}