java支付宝生成二维码

java支付宝生成二维码

在对接支付宝面对面支付的开发中,商户系统会向支付宝发起预下单请求,预下单请求成功后支付宝会返回给商户系统一个支付二维码的链接地址,因此需要用户把该二维码生成一个二维码图片到前端展示给用户扫码支付使用。

image-20210722153341622

调用支付宝预下单接口alipay.trade.precreate请求生成二维码链接

image-20210722153428765

搭建步骤

1.导入依赖

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>

2.创建工具类QRCodeUtil

package com.sean.alipayf2f.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

/**
 * @author : sean
 * @version V1.0
 * @Project: alipayf2f
 * @Package com.sean.alipayf2f.utils
 * @date Date : 2021年07月22日 14:54
 */

public class QrCodeUtil {
    private static Log log = LogFactory.getLog(QrCodeUtil.class);

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    /** 将内容contents生成长宽均为width的图片,图片路径由imgPath指定
     */
    public static File getQRCodeImge(String contents, int width, String imgPath) {
        return getQRCodeImge(contents, width, width, imgPath);
    }

    /** 将内容contents生成长为width,宽为width的图片,图片路径由imgPath指定
     */
    public static File getQRCodeImge(String contents, int width, int height, String imgPath) {
        try {
            Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF8");

            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

            File imageFile = new File(imgPath);
            writeToFile(bitMatrix, "png", imageFile);

            return imageFile;

        } catch (Exception e) {
            log.error("create QR code error!", e);
            return null;
        }
    }
}


3.测试

 @Test
    void qrcodeTest()
    {
        // 需要修改为运行机器上的路径
        String path = "C:\Users\sean\Desktop\F2FPay_Demo_Java";

        String qrPath = String.format(path + "\qr-%s.png", "111111111111111");
        String qrFileName = String.format("qr-%s.png", "111111111111111");
        QrCodeUtil.getQRCodeImge("https:\/\/qr.alipay.com\/bax014525dld1hiylvni0051", 256, qrPath);

        File targetFile = new File(path, qrFileName);
        
    }

image-20210722152942323

以上方法是将生成的二维码保存到本地,如果需要将二维码图片返回到前端展示,可以用如下方法

//向支付宝发送预下单请求
AlipayTradePrecreateResponse payResponse =alipayClient.execute(payRequest);
//二维码链接生成二维码图片
String qrPath = String.format("\qr-%s.png", payResponse.getOutTradeNo());
String qrFileName = String.format("qr-%s.png", payResponse.getOutTradeNo());
QrCodeUtil.getQRCodeImge(payResponse.getQrCode(), 256, qrPath);
File targetFile = new File(path, qrFileName);
//通过流的方式将二维码图片返回
ServletOutputStream  out = response.getOutputStream();
ImageIO.write(ImageIO.read(targetFile),"jpg",out);		
out.flush();

image-20210722165241897
java response 图片流:
https://blog.csdn.net/weixin_34169503/article/details/114110548

原文地址:https://www.cnblogs.com/seanRay/p/15045035.html