天天看點

Java 微信當面付生成二維碼支付實作1. maven依賴2. 準備工作3. 代碼

Java 微信當面付生成二維碼支付實作

  • 1. maven依賴
  • 2. 準備工作
    • a. WxPayConfig 配置類
    • b. 二維碼圖檔本地存儲位置
    • c. 配置虛拟路徑
  • 3. 代碼
    • a. QrCodeUtil
    • b. controller

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是在配置檔案裡寫到的二維碼圖檔本地存儲位置,

Java 微信當面付生成二維碼支付實作1. maven依賴2. 準備工作3. 代碼

c. 配置虛拟路徑

需要在項目裡配置虛拟路徑,

參考SpringBoot檔案虛拟路徑配置,

以及圖檔開放通路,有權限限制的項目需要這一步,項目不同開放的方式也不同,舉例:

Java 微信當面付生成二維碼支付實作1. maven依賴2. 準備工作3. 代碼

如果是分布式項目的話,內建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"));
        }
    }