參考官方APIalipay.trade.precreate(統一收單線下交易預創建)
- maven依賴:
<!-- 支付寶支付sdk -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.9.124.ALL</version>
</dependency>
<!-- 二維碼工具 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
- 準備工作:
AlipayConfig 配置類在第一篇關於支付寶支付文章裏有寫到:
Java 支付寶手機網站支付下單 支付回調 及訂單查詢實現
這裏直接用了
file.qrCode是在配置文件裏寫到的二維碼圖片本地存儲位置,
需要在項目裏配置虛擬路徑,參考SpringBoot文件虛擬路徑配置,
以及圖片開放訪問,有權限限制的項目需要這一步,項目不同開放的方式也不同,舉例:
如果是分佈式項目的話,集成MinIO來存儲圖片會更好,參考
Java MinIO文件上傳返回訪問路徑及訪問配置
- 代碼:
QrCodeUtil
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
public class QrCodeUtil {
/**
* 生成包含字符串信息的二維碼圖片
* @param outputStream 文件輸出流路徑
* @param content 二維碼攜帶信息
*/
public static boolean createQrCode(OutputStream outputStream, String content) throws WriterException, IOException{
//設置二維碼糾錯級別MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矯錯級別
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//創建比特矩陣(位矩陣)的QR碼編碼的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 900, 900, hintMap);
// 使BufferedImage勾畫QRCode (matrixWidth 是行二維碼像素點)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩陣畫並保存圖像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++){
for (int j = 0; j < matrixWidth; j++){
if (byteMatrix.get(i, j)){
graphics.fillRect(i-100, j-100, 1, 1);
}
}
}
return ImageIO.write(image, "JPEG", outputStream);
}
}
controller
@Value("${file.qrCode}")
private String qrCode;
@PreAuthorize("@el.check('anonymous')") // 匿名訪問
@PostMapping("/alipayPrecreate")
public ResponseEntity alipayPrecreate(@RequestBody Map params) throws Exception {
// 創建訂單並返回訂單id
ShopOrderDTO shopOrderDTO = createOrder(params);
// 支付請求參數準備
AlipayConfig alipayConfig = new AlipayConfig(shopDeviceService);
AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getAppId(),
alipayConfig.getRSAPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
alipayConfig.getAliPayPublicKey(), alipayConfig.getSignType());
AlipayTradePrecreateRequest req = new AlipayTradePrecreateRequest();
AlipayTradePrecreateModel model=new AlipayTradePrecreateModel();
model.setOutTradeNo(shopOrderDTO.getId().toString());
model.setSubject(alipayConfig.getSubject());
String amount = String.valueOf(shopOrderDTO.getAmount().floatValue() / 100);
model.setTotalAmount(amount);
req.setBizModel(model);
req.setNotifyUrl(alipayConfig.getNotifyUrl());
logger.info("發起AliPay下單請求");
AlipayTradePrecreateResponse execute = alipayClient.execute(req);
String result = execute.getBody();
JSONObject res = JSON.parseObject(result);
Map response = (Map) res.get("alipay_trade_precreate_response");
if (response.get("code").toString().equals("10000") && response.get("qr_code") != null) {
// 將返回的二維碼存儲至本地
String path = qrCode + shopOrderDTO.getId() + "AliPay.jpg";
String httpPath = "/qrCode/" + shopOrderDTO.getId() + "AliPay.jpg";
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
QrCodeUtil.createQrCode(new FileOutputStream(file), response.get("qr_code").toString());
// 將圖片可訪問的url返回給前端
response.put("qrcode", httpPath);
return new ResponseEntity<>(response, HttpStatus.OK);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}