package org.lpy.handler; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.request.AlipayTradePrecreateRequest; import com.alipay.api.response.AlipayTradePrecreateResponse; import lombok.extern.slf4j.Slf4j; import org.lpy.config.PayConfig; import org.lpy.pojo.AliReturnPayBean; import org.lpy.util.WebSocket; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; /** * 支付交易控制中心 * @author 林草莓233 * @since 2022/04/08 */ @Controller @Slf4j public class AliPayHandler { @Resource private AlipayClient alipayClient; @Resource private WebSocket webSocket; @Value("${company}") private String company; @Value("${timeout}") private String timeout; @RequestMapping("/createQR") @ResponseBody public String send(BigDecimal money,String title) throws AlipayApiException { AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); //創(chuàng)建API對應的request類 request.setNotifyUrl("http://127.0.0.1:8081/call"); //同步回調地址 // request.setReturnUrl(""); request.setBizContent( "{" + "\"out_trade_no\":\""+ System.currentTimeMillis()/1000 + Math.round((Math.random()+1) * 1000) + "\"," + // 商戶訂單號 "\"total_amount\":\""+ money +"\"," +// 商品價格 "\"subject\":\""+ title +"\"," +// 商品標題 "\"store_id\":\"" + company + "\"," + // 組織或公司名 "\"timeout_express\":\"" + timeout + "\"}" ); //支付超時時間 AlipayTradePrecreateResponse response = alipayClient.execute(request); if (response.isSuccess()) { log.info("支付API調用成功"); return response.getQrCode(); } else { log.info("支付API調用失敗"); } return ""; } // 支付寶回調函數(shù) @RequestMapping("/call") public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPayBean returnPay) throws IOException { response.setContentType("type=text/html;charset=UTF-8"); log.info("支付寶的的回調函數(shù)被調用"); if (!PayConfig.checkSign(request)) { log.info("驗簽失敗"); response.getWriter().write("failture"); return; } if (returnPay == null) { log.info("支付寶的returnPay返回為空"); response.getWriter().write("success"); return; } log.info("支付寶的returnPay" + returnPay); //表示支付成功狀態(tài)下的操作 if (returnPay.getTrade_status().equals("TRADE_SUCCESS")) { log.info("支付寶的支付狀態(tài)為TRADE_SUCCESS"); //業(yè)務邏輯處理 ,webSocket在下面會有介紹配置 webSocket.sendMessage("true"); } response.getWriter().write("success"); } } |