Last Updated: February 25, 2016
· welblaud

Sinatra & QR code payment (complete example)

The example below demonstrates using of QR codes for payments in Sinatra. It uses two possible solutions at once (described in comments). The first (using the QR code image) is probably more universal, the second one (using QR code in a shape of a table) is probably lighter (just a feeling). In the second case it is needed to pass the QR code variable into the template view (harder when using the modular design). This could sometimes make problems and needs more invention.


#!/usr/bin/env ruby

require 'sinatra'
require 'sinatra/reloader' if development? # sinatra-contrib gem for reloading
require 'rspayd'  # for generating the SPAYD string
require 'rqrcode' # for generating the QR code from string
require 'rqrcode_png' # for saving the code as img file

# setting the public folder location
set :public_folder, 'public'

get '/' do
# generating the string of SPAYD (Short Payment Descriptor) with rspayd gem
  @payment =  Rspayd::CzechPayment.generate_string( 
    :accountPrefix => '6607', # typical for Czech banks
    :accountNumber => '112336511',
    :bankCode => '0800',
    :amount => 130.00,
    :vs => "323232",
    :message => "Global domain payment"
# QR code generated with rqrcode gem, using the SPAYD code generated above 
# for longer string it is needed to use bigger QR code sizes! default is 4
  @qr =, size: 10) 
# using the code for generating png with rqrcode_png gem
  png = @qr.to_img                              
# resizing and saving the image file
  png.resize(200, 200).save("./public/qr-test.png")
  img = @qr.to_img
    erb :index


Template (here the inline one):

<!doctype html>
  <title>QR code test</title>
<p>QR code test (image form via rqrcode_png)</p>

<img src="qr-test.png">

<!-- When needing to recolorize that, it is possible via rewriting
values in the rqrcode_png/lib/rqrcode_png/image.rb and qrcode_extensions.rb,
(not sure the exact relationship between the bg_color included in both of them; 
however, replacing the values works perfectly) -->

<!-- Here we can do another thing, it is possible to
generate the code like a table. Nice solution ready for
recoloring the code! Custom resizing possible via td width/height values -->

<style type="text/css">

table {
  border-width: 0;
  border-style: none;
  border-color: #0000ff;
  border-collapse: collapse;

td {
  border-width: 0;
  border-style: none;
  border-color: #0000ff;
  border-collapse: collapse;
  padding: 0;
  margin: 0;
  width: 3px;
  height: 3px;
} { background-color: #73033D; }
td.white { background-color: #ffffff; }


<p>QR code test (simple table)

  <% @qr.modules.each_index do |x| %>
    <% @qr.modules.each_index do |y| %>
      <% if @qr.dark?(x,y) %>
      <td class="black" />
      <% else %>
      <td class="white" />
      <% end %>
    <% end %>
  <% end %>