首先要2个jar包
一个是alipay-sdk--java-4.9.79.ALL.jar
一个是aliyun-java-sdk-dysmsapi-1.0.0
基本配置信息:
package com.zhetian.www.alibaba; import java.io.FileWriter; import java.io.IOException; /** * @Copyright (C)遮天网络有限公司 * @Author: YUAN HUAI XING * @Date 2020/3/31 17:34 * @Descripthion: **/ public class AlipayConfig{ //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ // 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号 public static String app_id = ""; // 商户私钥,您的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://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 public static String return_url = ""; // 签名方式 public static String sign_type = "RSA2"; // 字符编码格式 public static String charset = "utf-8"; // 支付宝网关 public static String gatewayUrl ="http://openapi.alipaydev.com/gateway.do"; // 支付宝网关 public static String log_path = "C:\\"; //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ /** * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库) * @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(); } } } } public static String getorderNo() { String num = ""; for (int i = 0 ; i < 10 ; i ++) { num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1)); } return num; } }
调用支付接口
package com.zhetian.www.alibaba; import com.alibaba.fastjson.JSON; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.request.AlipayTradePagePayRequest; import com.alipay.api.response.AlipayTradePagePayResponse; import java.util.HashMap; /** * @Copyright (C)遮天网络有限公司 * @Author: YUAN HUAI XING * @Date 2020/3/31 18:34 * @Descripthion: **/ public class AliPayServer { public String pay(String orderOn, Integer productPrice, String productName) throws Exception { AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type); //设置请求参数 AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); alipayRequest.setReturnUrl(AlipayConfig.return_url); //设置同步回调通知 alipayRequest.setNotifyUrl(AlipayConfig.notify_url); //设置异步回调通知 //设置支付参数 HashMap<Object, Object> hashMap = new HashMap<>(); hashMap.put("out_trade_no",orderOn); hashMap.put("total_amount",productPrice); hashMap.put("subject",productName); hashMap.put("product_code","FAST_INSTANT_TRADE_PAY"); hashMap.put("timeout_express", "90m"); String s1 = JSON.toJSONString(hashMap); alipayRequest.setBizContent(s1); String s=""; System.out.println(s); //请求 try { AlipayTradePagePayResponse execute = alipayClient.pageExecute(alipayRequest); s = JSON.toJSONString(execute); System.out.println(s); } catch (AlipayApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; } }
点击购买跳转支付宝支付接口
/** * 点击购买执行操作 * @return */ @RequestMapping("/listData") @ResponseBody public Result listData(HttpServletRequest request, Integer id, Order order, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); Result result = new Result(); //1.接收商品id Product product = productService.ProductById(id); //2.根据商品id,获取价格,subject 产品名称 String productName = product.getProductName();//产品名称 Integer productPrice = product.getProductPrice();//产品价格 // 1-等待支付,2-支付失败,3-支付成功 String state ="2"; HttpSession session = request.getSession(); LoginUser data = (LoginUser)session.getAttribute("data"); String userName = data.getUserName(); LoginUser loginUser = loginUserService.UserByuserName(userName); Integer userId = loginUser.getId();//获取用户id //3.创建订单 支付状态 等待支付 String orderNo = getorderNo(); order.setUserId(userId); order.setProductId(id); order.setOrderOn(orderNo); order.setProductName(productName); order.setProductPrice(productPrice); order.setState(state); Date date = new Date(); order.setCreateTime(date); orderService.saveOrder(order); //4.向支付宝获取支付信息 request.setAttribute("orderNo",orderNo); AliPayServer aliPayServer = new AliPayServer(); String pay = aliPayServer.pay(orderNo, productPrice, productName); JSONObject jsonObject = JSON.parseObject(pay); String body = jsonObject.getString("body"); result.setData(body); return result; }
同步异步返回:
package com.zhetian.www.controller; import com.alipay.api.internal.util.AlipaySignature; import com.zhetian.www.alibaba.AlipayConfig; import com.zhetian.www.model.Order; import com.zhetian.www.service.impl.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static com.zhetian.www.alibaba.AlipayConfig.alipay_public_key; @Controller @RequestMapping("/callback") public class PayCallBackController { @Autowired private OrderService orderService; /** * 同步回调 * * @param request * @throws Exception */ @ResponseBody @RequestMapping("/returnUrl") public ModelAndView returnUrl(HttpServletRequest request) throws Exception { ModelAndView mav = new ModelAndView(); System.out.println("前往支付成功页面"); mav.setViewName("/tick/list"); return mav; } /** * 支付宝服务器异步通知 * * @param request * @throws Exception */ @RequestMapping("/notifyUrl") @ResponseBody public String notifyUrl(HttpServletRequest request) throws Exception { // 获取支付宝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] + ","; } params.put(name, valueStr); } boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名 if (signVerified) { // 验证成功 更新订单信息 System.out.println("异步通知成功"); // 1.商户订单号 String orderOn = request.getParameter("out_trade_no"); // // 2.交易状态 String trade_status = request.getParameter("trade_status"); if (trade_status.equals("TRADE_SUCCESS")){ //3.订单号和支付状态修改订单 // 修改数据库 Order order = new Order(); order.setState("3"); Date date = new Date(); order.setUpdateTime(date); order.setOrderOn(orderOn); orderService.updaetOrder(order); return "success"; } return "fail"; } else { System.out.println("异步通知失败"); return "fail"; } }
@注:本博客仅为个人学习笔记。 所属人:Yuan
原文地址:https://www.cnblogs.com/zhetiankj/p/12661534.html
时间: 2024-11-05 14:55:31