背景:小明在一家IT公司就职,根据客户需求,需要实现对商品支付,包含支付宝和微信,此次演练为支付宝沙箱支付,了解工作流程
步骤1:导入所需依赖
工具分享:link
java"><!-- alipay --><dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-sdk-java</artifactId><version>4.39.2.ALL</version></dependency><dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-easysdk</artifactId><version>2.2.1</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency>
步骤2:登录平台,获取账号信息
平台地址:link
步骤3:配置账号信息application.yml
java">spring:application:name: paydatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8username: rootpassword: 密码# 支付宝支付
alipay:# 沙箱中的应用idappId: copy你的# 应用私钥appPrivateKey: copy你的# 支付宝公钥alipayPublicKey: copy你的# 调用支付宝支付接口后产生的回调[选填]notifyUrl: # 支付成功后的页面跳转[选填]returnUrl:
server:port: 8089
步骤4:编码环节
配置类AliPayConfig
java">@Data
@Component
//读取yml文件中的alipay开头的配置
@ConfigurationProperties(prefix = "alipay")
public class AliPayConfig {private String appId;private String appPrivateKey;private String alipayPublicKey;//异步通知回调地址(可选)private String notifyUrl;//支付成功后的回调地址private String returnUrl;@PostConstructpublic void init(){//设置参数(全局只需要设置一次)Config config = new Config();config.protocol="https";config.gatewayHost="openai.alipaydev.com";config.signType="RSA2";config.appId=this.appId;config.merchantPrivateKey=this.appPrivateKey;config.alipayPublicKey=this.alipayPublicKey;config.notifyUrl=this.notifyUrl;Factory.setOptions(config);System.out.println("======支付宝SDK初始化成功=====");}}
请求体AliPay
java">@Data
public class AliPay {//订单编号private String traceNo;//商品金额private double totalAmount;//商品名称private String subject;//订单追踪号,商户自己生成,可以不使用private String alipayTraceNo;
}
测试类AliPayController
java">@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {@ResourceAliPayConfig aliPayConfig;private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";private static final String FORMAT ="JSON";private static final String CHARSET ="utf-8";private static final String SIGN_TYPE ="RSA2";@GetMapping("/pay") // 前端路径参数格式?subject=xxx&traceNo=xxx&totalAmount=xxxpublic void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();request.setNotifyUrl(aliPayConfig.getNotifyUrl());request.setReturnUrl(aliPayConfig.getReturnUrl());request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","+ "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","+ "\"subject\":\"" + aliPay.getSubject() + "\","+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");String form = "";try {// 调用SDK生成表单form = alipayClient.pageExecute(request).getBody();} catch (AlipayApiException e) {e.printStackTrace();}httpResponse.setContentType("text/html;charset=" + CHARSET);// 直接将完整的表单html输出到页面httpResponse.getWriter().write(form);httpResponse.getWriter().flush();httpResponse.getWriter().close();}@PostMapping("/notify") // 注意这里必须是POST接口public String payNotify(HttpServletRequest request) throws Exception {if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {System.out.println("=========支付宝异步回调========"); //=========支付宝异步回调========Map<String, String> params = new HashMap<>();Map<String, String[]> requestParams = request.getParameterMap();for (String name : requestParams.keySet()) {params.put(name, request.getParameter(name));}String tradeNo = params.get("out_trade_no");String gmtPayment = params.get("gmt_payment");String alipayTradeNo = params.get("trade_no");// 支付宝验签if (Factory.Payment.Common().verifyNotify(params)) {// 验签通过System.out.println("交易名称: " + params.get("subject")); System.out.println("交易状态: " + params.get("trade_status")); System.out.println("支付宝交易凭证号: " + params.get("trade_no")); System.out.println("商户订单号: " + params.get("out_trade_no")); System.out.println("交易金额: " + params.get("total_amount")); System.out.println("买家在支付宝唯一id: " + params.get("buyer_id")); System.out.println("买家付款时间: " + params.get("gmt_payment")); System.out.println("买家付款金额: " + params.get("buyer_pay_amount")); // 更新订单已支付的逻辑代码}}return "success";}}
步骤5:启动并测试
推荐:浏览器测试
http://localhost:8089/alipay/pay?subject=百事可乐&traceNo=123482&totalAmount=5
跳转此页面:恭喜试用通过!
本人正在打造技术交流群,欢迎志同道合的朋友一起探讨,一起努力,通过自己的努力,在技术岗位这条道路上走的更远。QQ群号:914683950 备注:技术交流 即可通过!