Java 微信当面付生成二维码支付实现
1. maven依赖
<!-- 微信支付sdk -->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</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>
2. 准备工作
a. WxPayConfig 配置类
在第一篇关于微信支付文章里有写到:
Java 微信支付统一下单、支付回调、订单查询实现
这里直接用了
b. 二维码图片本地存储位置
file.qrCode是在配置文件里写到的二维码图片本地存储位置,
c. 配置虚拟路径
需要在项目里配置虚拟路径,
参考SpringBoot文件虚拟路径配置,
以及图片开放访问,有权限限制的项目需要这一步,项目不同开放的方式也不同,举例:
如果是分布式项目的话,集成MinIO来存储图片会更好,参考
Java MinIO文件上传返回访问路径及访问配置
3. 代码
a. 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);
}
}
b. controller
@Value("${file.qrCode}")
private String qrCode;
@PreAuthorize("@el.check('anonymous')")
@PostMapping("/wxpayPrecreate")
public ResponseEntity wxPrecreate(HttpServletRequest request, @RequestBody Map params) throws Exception {
// 保存未支付订单
ShopOrderDTO shopOrderDTO = createOrder(params, 0);
// 处理请求参数
WxPayConfig wxPayConfig = new WxPayConfig(shopDeviceService);
WXPay wxPay = new WXPay(wxPayConfig);
Map<String,String> data = new HashMap<>();
data.put("out_trade_no", shopOrderDTO.getId()+""); //订单编号
data.put("total_fee",shopOrderDTO.getAmount().toString()); //金额(单位为分) int
data.put("spbill_create_ip", IPUtil.getIPAddress(request));
data.put("nonce_str", WXPayUtil.generateNonceStr()); // 随机字符串小于32位
data.put("mch_id",wxPayConfig.getMchID());
data.put("appid",wxPayConfig.getAppID());
// 这里二维码支付是区别于手机网站支付的地方
data.put("trade_type","NATIVE");
data.put("product_id", shopOrderDTO.getId().toString());
data.put("device_info",wxPayConfig.getDeviceInfo());
data.put("notify_url",wxPayConfig.getNotifyUrl());
data.put("fee_type",wxPayConfig.getFeeType());
data.put("body",wxPayConfig.getBody());
data.put("scene_info", wxPayConfig.getSceneInfo());
// 生成签名
String s = WXPayUtil.generateSignature(data, wxPayConfig.getKey());
data.put("sign",s);
// 发起下单请求
logger.info("发起 WxPay 下单请求");
Map<String, String> respData = wxPay.unifiedOrder(data);
// 处理下单结果
if ("SUCCESS".equals(respData.get("return_code"))){
if ("SUCCESS".equals(respData.get("result_code"))) {
String path = qrCode + shopOrderDTO.getId() + "WXPay.jpg";
String httpPath = "/qrCode/" + shopOrderDTO.getId() + "WXPay.jpg";
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
QrCodeUtil.createQrCode(new FileOutputStream(file), respData.get("code_url"));
respData.put("qrcode", httpPath);
respData.put("out_trade_no", shopOrderDTO.getId()+"");
shopLogService.anonymousCreate(shopLogService.getShopLog(shopOrderDTO.getStoreId(), shopOrderDTO.getDeviceId(), "生成WxPay订单","订单编号 : " + shopOrderDTO.getId()));
return new ResponseEntity<>(respData, HttpStatus.OK);
} else {
shopLogService.anonymousCreate(shopLogService.getShopLog(shopOrderDTO.getStoreId(), shopOrderDTO.getDeviceId(), "WxPay下单失败","err_code_des : " + respData.get("err_code_des")));
throw new Exception(respData.get("err_code_des"));
}
} else {
shopLogService.anonymousCreate(shopLogService.getShopLog(shopOrderDTO.getStoreId(), shopOrderDTO.getDeviceId(), "WxPay下单失败","return_msg : " + respData.get("err_code_des")));
throw new Exception(respData.get("return_msg"));
}
}