dependencies {
implementation('com.google.zxing:core:3.4.0')
implementation('com.google.zxing:javase:3.4.0')
}
Generate UPI QR Code in Java
Upasana | September 12, 2020 | 3 min read | 1,106 views
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)
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.
https://www.npci.org.in/sites/default/files/UPI%20Linking%20Specs_ver%201.6.pdf
We can use Spring’s UriComponentsBuilder
class to generate the encoded 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://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.
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));
}
}
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.
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:
<img src="data:image/png;base64, <base64 QR Code String>" alt="UPI QR Code" />
References
Top articles in this category:
- Table backed global counter in spring hibernate
- Custom banner in spring boot
- Redis rate limiter in Spring Boot
- Java 8 date time JSON formatting with Jackson
- Prevent Lost Updates in Database Transaction using Spring Hibernate
- N+1 problem in Hibernate & Spring Data JPA
- Spring RestTemplate Basic Authentication