Generate UPI QR Code in Java

Upasana | September 12, 2020 | 3 min read | 1,106 views


Generate UPI QR Code in Java
We will generate UPI Payments compliant (BHIM, GPay, PayTM) QR Code in PNG/JPG/Base64 format using zxing library in Java & Spring based application.

Gradle setup

You can use https://start.spring.io/ to create a new project template for Spring Boot based project and then add the below dependencies for using zxing library (QR Code generation)

build.gradle
dependencies {
    implementation('com.google.zxing:core:3.4.0')
    implementation('com.google.zxing:javase:3.4.0')
}
Latest version of zxing library can be found at:

https://mvnrepository.com/artifact/com.google.zxing/javase

Generate QR Code URL

We will develop a service component that will take the payload and generate the QR code that is compliant with UPI specifications.

You can refer to the version 1.6 of UPI specifications published on npci website.

upi specs parameters url
UPI Specs Parameters

We can use Spring’s UriComponentsBuilder class to generate the encoded URL for UPI payments:

Generating the URL for UPI Payments
class Scratch {
    private static final Logger logger = LoggerFactory.getLogger(QRCodeService.class);

    public void createUpiQrCode(String payeeAddress, String payeeName, String trxNo, String amount, String purpose, String trxRef) throws IOException, WriterException {
        final String qrCode = UriComponentsBuilder.fromUriString("upi://pay")
                .queryParam("pa", payeeAddress) (1)
                .queryParam("pn", payeeName)
                .queryParam("tn", trxNo)
                .queryParam("tr", trxRef)
                .queryParam("am", amount)
                .queryParam("cu", "INR")
                .queryParam("purpose", purpose)
                .build().encode().toUriString();
        logger.info("UPI QR Code = " + qrCode);
        createQRCode(qrCode, "qrcode-3.png");
    }
}
1 UPI address in the form of mobile@upi or any other format as per bank.

The final QR Code shall look like the following:

UPI Payment URL for QR Code
upi://pay?pa=<upi address>&pn=<Name>&tn=<trxNo>&tr=<trxRef>&am=<trxAmount>&cu=INR&purpose=<purpose>

Generate QR Code Image (png/jpg/base64)

We have got the URL that we need to embed inside QR Code, in this step we will create the QR code image in png format using zxing library.

Generating QR Code in PNG over JPEG has many benefits, as the size of output is greatly reduced and its better for network requests.

Generate QR Code image in PNG
class Scratch {
    private static final Logger logger = LoggerFactory.getLogger(QRCodeService.class);

    private final Map hintMap = new HashMap<>();
    private final String charset = StandardCharsets.UTF_8.name(); // or "ISO-8859-1"
    private final int size = 350;

    public QRCodeService() {
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hintMap.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
        hintMap.put(EncodeHintType.MARGIN, 1);

        hintMap.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
        hintMap.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        hintMap.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
    }

    public void createQRCode(String qrCodeData, String filePath) throws WriterException, IOException {
        BitMatrix matrix = new MultiFormatWriter().encode(qrCodeData, BarcodeFormat.QR_CODE, size, size, hintMap);
        MatrixToImageWriter.writeToPath(matrix, "png", Paths.get(filePath));
    }
}
upi qr code
UPI Payment QR Code sample image

Generate Base64 format for QR Code

Many a times, we need to embed this QR Code image inside html content, base64 may be a good option for this as everything will happen inline.

Generate Base64 version of image
class Scratch {
       public String createQRCode(String qrCodeData) throws WriterException, IOException {
        BitMatrix matrix = new MultiFormatWriter().encode(qrCodeData, BarcodeFormat.QR_CODE, size, size, hintMap);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(matrix, "png", baos);
        return Base64.getEncoder().encodeToString(baos.toByteArray());
    }
}

Embedding this Base64 QR Code inside HTML

We can create an image element in HTML using embedded base64 version of QR Code as shown in below code snippet:

Embedded base64 in IMG tag in HTML
<img src="data:image/png;base64, <base64 QR Code String>" alt="UPI QR Code" />

Top articles in this category:
  1. Table backed global counter in spring hibernate
  2. Custom banner in spring boot
  3. Redis rate limiter in Spring Boot
  4. Java 8 date time JSON formatting with Jackson
  5. Prevent Lost Updates in Database Transaction using Spring Hibernate
  6. N+1 problem in Hibernate & Spring Data JPA
  7. Spring RestTemplate Basic Authentication

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.