pom.xml
<!-- 支付宝支付 -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.7.26.ALL</version>
</dependency>
controller层
package com.wen.controller;
import com.alipay.api.AlipayApiException;
import com.wen.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* 支付宝
* @data
*/
@CrossOrigin
@RestController
@RequestMapping("/alipay")
public class AlipayController {
@Autowired
@Qualifier("alipayService")
private AlipayService alipayService;
/**
* web 订单支付
* @param outTradeNo 订单编号
* @param totalAmount 订单价格
* @param subject 商品名称
* @return
* @throws Exception
*/
@RequestMapping("/getPagePay")
public Map<Object, Object> getPagePay(String outTradeNo,Integer totalAmount,String subject) throws Exception{
System.out.println(outTradeNo+totalAmount+subject);
String pay = alipayService.webPagePay(outTradeNo, totalAmount, subject);
System.out.println(pay);
Map<Object, Object> pays = new HashMap<>();
pays.put("pay", pay);
return pays;
}
/**
* app 订单支付
*/
/**
*
* @param outTradeNo 订单编号
* @param totalAmount 订单价格
* @param subject 商品名称
* @throws Exception
*/
@RequestMapping("/getAppPagePay")
public void getAppPagePay( String outTradeNo ,Integer totalAmount,String subject) throws Exception{
String pay = alipayService.appPagePay(outTradeNo, totalAmount, subject);
System.out.println(pay);
}
/**
* 交易查询
* @param outTradeNo 订单编号
* @throws Exception
*/
@PostMapping("/aipayQuery")
public void alipayQuery(String outTradeNo) throws Exception{
String query = alipayService.query(outTradeNo);
System.out.println(query);
}
/**
* 退款
* @param outTradeNo 订单编号
* @param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
* @param refundAmount 订单金额
* @param refundReason 退货原因
* @throws AlipayApiException
*/
@GetMapping("alipayRefund")
public void alipayRefund(
@RequestParam("outTradeNo")String outTradeNo,
@RequestParam(value = "outRequestNo", required = false)String outRequestNo,
@RequestParam(value = "refundAmount", required = false)Integer refundAmount,
String refundReason) throws AlipayApiException {
String refund = alipayService.refund(outTradeNo, refundReason, refundAmount, outRequestNo);
System.out.println(refund);
return ;
}
/**
* 退款查询
@param outTradeNo 订单编号(唯一)
@param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
* @throws AlipayApiException
*/
@PostMapping("refundQuery")
public void refundQuery(String outTradeNo,String outRequestNo) throws AlipayApiException{
String refund = alipayService.refundQuery(outTradeNo, outRequestNo);
System.out.println(refund);
return ;
}
/**
* 交易关闭
* @throws AlipayApiException
*/
@PostMapping("alipayclose")
public void alipayclose(String outTradeNo) throws AlipayApiException {
String close = alipayService.close(outTradeNo);
System.out.println(close);
return ;
}
@RequestMapping("/errorOrder")
public String errorOrder(){
return "error";
}
@RequestMapping("/returnUrl")
public String returnUrl(){
return "return";
}
}
AlipayConfig
package com.wen.config;
import java.io.FileWriter;
import java.io.IOException;
/**
* 支付宝支付配置类
*/
public class AlipayConfig {
// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
public static String APP_ID = "2021000117693332";
// 商户私钥,您的PKCS8格式RSA2私钥
public static String MERCHANT_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHObS89y6mHKVY1WpLenvlUEWhqXAb5zAFqm9LOsOUEmqsgezF05B5QDAy/I7exAiKaanu2ciikCodlBnY/B0JH90JC6MzzSihs2v2MY0wEeANLStP6bTjkCuSDLwObZxNTPEF0VBlqi4jzLSG2XJvkczI2strK8jI06tnAMUY1cS9CIe1ICmHLkd55ABwn4WDuoyQo589/Qm646KUmkcAeYfFo5EbaRZtvJlKcCuFQMWvlAOBRG1JJm5Tnfg3XJ41698+BNxQplbVr7XIxUoWnHqBffEJE5/HSuZUpcQv75SMbAa0DT3Lf6W3cEdIdSGznP+UMH9e9NizgCVrwlmzAgMBAAECggEAYcejXmSqUakzEro3Q17NCfLydsRLcZHJUr97/H0AgSiUBCtq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xoY0KlIs6vLLaZfW76pZMQ4mWz10v6lJMiWxpa5kVpF26UKdAgyTyY+SU4rVjXBL3xMmagDNkor1gFmNc=";
// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApevJdSI5y9p9fX8x6WxZwQFLWdvTVF1zmo4TxJnG/0KnwOg2XtdAQwsWf2eQMpHdvd1LG+H+5ztpN3YDymt9DkzVbVkqqwEvcoS8tl/8tCknbs80t18FIMcOJe/nFBvBty/MB6wfdU2mM+e04j3d0VtLXq9h/4r/PCIEkTp3QKRuJfjLPCJUF3FLIo25IvoFxSqXrtBVh6PjA7CSsSvIHQdoUTZ4CXfHJFMUnwD0tKILHf4iy/f7e0+wzC7t6/n2K7Fc01WQv/omyQCscvaG1XXMaJ34jj8POjYApc5tYKDSII5vNx4B0PoCPGOCjtY+uvd6KryFSRg2ZX95gvUtjQIDAQAB";
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String notify_url = "http://www.jiuxiangheni.com";
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String return_url = "http://www.tangyuxi.cn";
// 签名方式
public static String SIGN_TYPE = "RSA2";
// 字符编码格式
public static String CHARSET = "utf-8";
// 支付宝网关
public static String GATEWAYURL = "https://openapi.alipaydev.com/gateway.do";
// 支付宝网关
public static String LOG_PATH = "D:\\";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
*
* @param sWord 要写入日志里的文本内容
*/
public static void logResult(String sWord) {
FileWriter writer = null;
try {
writer = new FileWriter(LOG_PATH + "alipay_log_" + System.currentTimeMillis() + ".txt");
writer.write(sWord);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
service
import com.alipay.api.AlipayApiException;
/**
* 支付接口
*/
public interface AlipayService {
/**
* web端订单支付
* @param outTradeNo 订单编号(唯一)
* @param totalAmount 订单价格
* @param subject 商品名称
*/
String webPagePay(String outTradeNo, Integer totalAmount, String subject) throws Exception;
/**
* app端订单支付
* @param outTradeNo 订单编号
* @param totalAmount 订单价格
* @param subject 商品名称
*/
String appPagePay(String outTradeNo, Integer totalAmount, String subject) throws Exception;
/**
* 退款
* @param outTradeNo 订单编号
* @param refundReason 退款原因
* @param refundAmount 退款金额
* @param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
*/
String refund(String outTradeNo, String refundReason, Integer refundAmount, String outRequestNo) throws AlipayApiException;
/**
* 交易查询
* @param outTradeNo 订单编号(唯一)
*/
String query(String outTradeNo) throws AlipayApiException;
/**
* 交易关闭
* @param outTradeNo 订单编号(唯一)
*/
String close(String outTradeNo) throws AlipayApiException;
/**
* 退款查询
* @param outTradeNo 订单编号(唯一)
* @param outRequestNo 标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
*/
String refundQuery(String outTradeNo, String outRequestNo) throws AlipayApiException;
}
service实现类
package com.wen.service.impl;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.*;
import com.wen.config.AlipayConfig;
import com.wen.service.AlipayService;
import org.springframework.stereotype.Service;
/**
* 支付实现类
*/
@Service("alipayService")
public class AlipayServiceImpl implements AlipayService {
/** 调取支付宝接口 web端支付*/
DefaultAlipayClient alipayClient = new DefaultAlipayClient(
AlipayConfig.GATEWAYURL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
/** 调取支付宝接口app端支付*/
AlipayClient alipayClients = new DefaultAlipayClient(
AlipayConfig.GATEWAYURL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
@Override
public String webPagePay(String outTradeNo, Integer totalAmount, String subject) throws Exception {
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
/** 同步通知,支付完成后,支付成功页面*/
alipayRequest.setReturnUrl(AlipayConfig.return_url);
/** 异步通知,支付完成后,需要进行的异步处理*/
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
+ "\"total_amount\":\""+ totalAmount +"\","
+ "\"subject\":\""+ subject +"\","
+ "\"body\":\"商品名称\","
+ "\"timeout_express\":\"90m\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
/**转换格式*/
String result = alipayClient.pageExecute(alipayRequest).getBody().replace('\"','\'').replace('\n',' ');
return result;
}
@Override
public String refund(String outTradeNo,String refundReason,Integer refundAmount,String outRequestNo) throws AlipayApiException {
AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
/** 调取接口*/
alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
+ "\"refund_amount\":\""+ refundAmount +"\","
+ "\"refund_reason\":\""+ refundReason +"\","
+ "\"out_request_no\":\""+ outRequestNo +"\"}");
String result = alipayClient.execute(alipayRequest).getBody();
return result;
}
@Override
public String query(String outTradeNo) throws AlipayApiException {
AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
/**请求接口*/
alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","+"\"trade_no\":\""+ "" +"\"}");
/**转换格式*/
String result = alipayClient.execute(alipayRequest).getBody();
return result;
}
@Override
public String close(String outTradeNo) throws AlipayApiException {
AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\"," +"\"trade_no\":\""+ "" +"\"}");
String result = alipayClient.execute(alipayRequest).getBody();
return result;
}
@Override
public String refundQuery(String outTradeNo , String outRequestNo) throws AlipayApiException {
AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();
/** 请求接口*/
alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
+"\"out_request_no\":\""+ outRequestNo +"\"}");
/** 格式转换*/
String result = alipayClient.execute(alipayRequest).getBody();
return result;
}
@Override
public String appPagePay(String outTradeNo, Integer totalAmount, String subject) throws Exception {
AlipayTradeWapPayRequest alipayRequest=new AlipayTradeWapPayRequest();
/** 同步通知,支付完成后,支付成功页面*/
alipayRequest.setReturnUrl(AlipayConfig.return_url);
/** 异步通知,支付完成后,需要进行的异步处理*/
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
/**销售产品码(固定)*/
String productCode="QUICK_WAP_WAY";
/** 进行赋值 */
AlipayTradeWapPayModel wapPayModel=new AlipayTradeWapPayModel();
wapPayModel.setOutTradeNo(outTradeNo);
wapPayModel.setSubject(subject);
wapPayModel.setTotalAmount(totalAmount.toString());
wapPayModel.setBody("商品名称");
wapPayModel.setTimeoutExpress("2m");
wapPayModel.setProductCode(productCode);
alipayRequest.setBizModel(wapPayModel);
/** 格式转换*/
String result = alipayClients.pageExecute(alipayRequest).getBody().replace('\"','\'').replace('\n',' ');
return result;
}
}
前端发送接收代码
let params = new URLSearchParams();
params.append('outTradeNo', orderid);
params.append('totalAmount', resp.data.sum);
params.append('subject', resp.data.name);
axios.post("http://127.0.0.1:7000/alipay/getPagePay", params)
.then(function (resp) {
$("#div").html(resp.data.pay);//div盒子
});
这是和网上大哥做的,但是容易出现钓鱼网站的问题
第一种解决办法是删除缓存和更换浏览器,但还是要看脸
第二种解决办法(我也没用过):
//设置请求参数
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//同步回调,如果本地调度只会走同步,这里的界面就是你付款后跳转的界面
alipayRequest.setReturnUrl(AlipayConfig.return_url);
//异步回调,没有服务器实际上我们用不到
alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//订单名称,必填
String subject=request.getParameter("Name");
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no =request.getParameter("Order");
//付款金额,必填
ShopName String total_amount =request.getParameter("Money");
//商品描述,可空
String body ="购物测试";
// 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d- 天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点, 如 1.5h,可转换为 90m。
String timeout_express = "1c"; alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\"," + "\"timeout_express\":\""+ timeout_express +"\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
/* //请求
String url = "";
try {
url = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生 成表单
} catch (AlipayApiException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
return url;*/
//这两种方式都是可以的,就是上面那种可能很容易报错,看运气是否成功
//请求
String form = ""; try {form = alipayClient.pageExecute(alipayRequest).getBody();
//调用SDK生 成表单
} catch (AlipayApiException e) { e.printStackTrace(); }response.setContentType("text/html;charset=" + AlipayConfig.CHARSET); response.getWriter().write(form);
//直接将完整的表单html输出到页面
response.getWriter().flush();
response.getWriter().close();
return form;