qrpix

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 16, 2023 License: MIT Imports: 8 Imported by: 0

README

qrpix

Lib para gerar qrcode estático de cobrança do pix em Go, além fazer encode e decode de BRCodes.

TODOs

  1. Criar consts com os IDs dos campos;
  2. Criar decoder;
  3. Completar a especificação (Unreserved Templates).

Exemplos

qr := NewStatic(
    "123e4567-e12b-12d1-a456-426655440000", // Chave Pix
    "Fulano de Tal", // Nome
    "BRASILIA", // Cidade
    "***", // ID Transação
)

// Gerando Imagem
if err := qr.SaveFile("example.png"); err != nil {
    return err
}

// Servindo via HTTP
http.HandleFunc("/", func(w http.ResponseWrite, r *http.Request) {
    if err := qr.Serve(w); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
})
  • Campos Opcionais
qr := NewStatic(
    "123e4567-e12b-12d1-a456-426655440000", // Chave Pix
    "Fulano de Tal", // Nome
    "BRASILIA", // Cidade
    "***", // ID Transação
    WithTransactionAmount(1000), // Valor da transação em centavos (10 reais)
)
  • Decode
code := "00020126580014br.gov.bcb.pix0136123e4567-e12b-12d1-a456-4266554400005204000053039865802BR5913Fulano de Tal6008BRASILIA62070503***63041D3D"
p := NewParser()
static, _ := p.ParseStatic(code)
fmt.Printf("%+v", static)

Documentation

Index

Constants

View Source
const (
	FieldPrimitive = "primitive"
	FieldTemplate  = "template"
)
View Source
const (
	PIXGui                 = "br.gov.bcb.pix"
	PayloadFormatIndicator = "01"
)

Variables

View Source
var (
	ErrInvalidCRC              = errors.New("crc is not valid")
	ErrCRCNotPresent           = errors.New("crc is not present")
	ErrRequiredFieldNotPresent = errors.New("required field not present")
)
View Source
var (
	ErrFieldIsRequired       = errors.New("field is required")
	ErrFieldMetadataNotFound = errors.New("field metadata for provided id not found")
)
View Source
var (
	ErrEmptyCode = errors.New("cannot parse empty code")
)
View Source
var (
	IDMetadata = map[string]Metadata{
		"00": {
			Name:     "Payload Format Indicator",
			MaxSize:  2,
			MinSize:  2,
			Type:     FieldPrimitive,
			Required: true,
		},
		"26": {
			Name:     "Merchant Account Information",
			MinSize:  5,
			MaxSize:  99,
			Type:     FieldTemplate,
			Required: true,
		},
		"26-00": {
			Name:     "GUI",
			MaxSize:  14,
			Required: true,
			Type:     FieldPrimitive,
		},
		"26-01": {
			Name:     "Chave",
			MaxSize:  77,
			Required: true,
			Type:     FieldPrimitive,
		},
		"26-02": {
			Name:     "Info Adicional",
			MaxSize:  72,
			Required: false,
			Type:     FieldPrimitive,
		},
		"26-03": {
			Name:     "FSS",
			MaxSize:  8,
			Required: false,
			Type:     FieldPrimitive,
		},
		"52": {
			Name:     "Merchant Category Code",
			MinSize:  4,
			MaxSize:  4,
			Required: true,
			Type:     FieldPrimitive,
		},
		"53": {
			Name:     "Transaction Currency",
			MinSize:  3,
			MaxSize:  3,
			Required: true,
			Type:     FieldPrimitive,
		},
		"54": {
			Name:     "Transaction Amount",
			MinSize:  1,
			MaxSize:  13,
			Required: false,
			Type:     FieldPrimitive,
		},
		"58": {
			Name:     "Country Code",
			MaxSize:  2,
			MinSize:  2,
			Required: true,
			Type:     FieldPrimitive,
		},
		"59": {
			Name:     "Merchant Name",
			MinSize:  1,
			MaxSize:  25,
			Required: true,
			Type:     FieldPrimitive,
		},
		"60": {
			Name:     "Merchant City",
			MinSize:  1,
			MaxSize:  25,
			Required: true,
			Type:     FieldPrimitive,
		},
		"61": {
			Name:     "Postal Code",
			MinSize:  1,
			MaxSize:  99,
			Type:     FieldPrimitive,
			Required: false,
		},
		"62": {
			Name:     "Addional Data Field Template",
			MinSize:  5,
			MaxSize:  29,
			Type:     FieldTemplate,
			Required: false,
		},
		"62-05": {
			Name:     "Reference Label",
			MinSize:  1,
			MaxSize:  25,
			Required: false,
			Type:     FieldPrimitive,
		},
		"63": {
			Name:     "CRC16",
			MaxSize:  4,
			MinSize:  4,
			Required: true,
			Type:     FieldPrimitive,
		},
	}
)

Functions

func ValidateField

func ValidateField(id, value string) error

Validates a field value based on the provided id metadata

Types

type Builder

type Builder map[string]TLV

Used to build the BRCode

func (Builder) Add

func (b Builder) Add(tlv TLV) Builder

func (Builder) AddAdditionalDataField

func (b Builder) AddAdditionalDataField(transactionId string)

func (Builder) AddCountryCode

func (b Builder) AddCountryCode(code string)

func (Builder) AddMerchantAccountInformation

func (b Builder) AddMerchantAccountInformation(gui, chave string)

func (Builder) AddMerchantCategoryCode

func (b Builder) AddMerchantCategoryCode(code string)

func (Builder) AddMerchantCity

func (b Builder) AddMerchantCity(city string)

func (Builder) AddMerchantName

func (b Builder) AddMerchantName(name string)

func (Builder) AddPayloadFormatIndicator

func (b Builder) AddPayloadFormatIndicator(value string)

func (Builder) AddPostalCode

func (b Builder) AddPostalCode(postalCode string)

func (Builder) AddTransactionAmount

func (b Builder) AddTransactionAmount(amount int)

Adds the transaction amount in cents. Ex: 100 == 1 real

func (Builder) AddTransactionCurrency

func (b Builder) AddTransactionCurrency(code string)

func (Builder) Build

func (b Builder) Build() (string, error)

Build and validates the BRCode. CRC16 is added automatically.

func (Builder) CheckCRC added in v0.2.0

func (b Builder) CheckCRC() error

Removes crc and then builds without adding it and checks if hashes matches

func (*Builder) Clear

func (b *Builder) Clear()

Clears the builder TLV items

func (Builder) GetCountryCode added in v0.3.0

func (b Builder) GetCountryCode() (string, error)

func (Builder) GetMerchanName added in v0.3.0

func (b Builder) GetMerchanName() (string, error)

func (Builder) GetMerchantAccountInformationChave added in v0.3.0

func (b Builder) GetMerchantAccountInformationChave() (string, error)

func (Builder) GetMerchantAccountInformationGui added in v0.3.0

func (b Builder) GetMerchantAccountInformationGui() (string, error)

func (Builder) GetMerchantCategoryCode added in v0.3.0

func (b Builder) GetMerchantCategoryCode() (string, error)

func (Builder) GetMerchantCity added in v0.3.0

func (b Builder) GetMerchantCity() (string, error)

func (Builder) GetPayloadFormatIndicator added in v0.3.0

func (b Builder) GetPayloadFormatIndicator() (string, error)

func (Builder) GetPostalCode added in v0.3.0

func (b Builder) GetPostalCode() (string, error)

func (Builder) GetPrimitiveField added in v0.3.0

func (b Builder) GetPrimitiveField(id string) (string, error)

func (Builder) GetTemplateField added in v0.3.0

func (b Builder) GetTemplateField(id string, fieldId string) (string, error)

func (Builder) GetTransactionAmount added in v0.3.0

func (b Builder) GetTransactionAmount() (int, error)

func (Builder) GetTransactionCurrency added in v0.3.0

func (b Builder) GetTransactionCurrency() (string, error)

func (Builder) GetTransactionId added in v0.3.0

func (b Builder) GetTransactionId() (string, error)

func (Builder) Sorted added in v0.2.0

func (b Builder) Sorted() []TLV

type Metadata

type Metadata struct {
	Name     string
	MaxSize  int
	MinSize  int
	Type     string
	Required bool
}

func GetFieldMetadata added in v0.2.0

func GetFieldMetadata(id string) (Metadata, error)

type Parser added in v0.2.0

type Parser struct {
	Code string
	// contains filtered or unexported fields
}

func NewParser added in v0.2.0

func NewParser() *Parser

func (*Parser) Parse added in v0.2.0

func (p *Parser) Parse(brCode string) (Builder, error)

Parses the BRCode into TLVs and returns a builder

func (*Parser) ParseStatic added in v0.3.0

func (p *Parser) ParseStatic(brCode string) (*Static, error)

type Primitive

type Primitive struct {
	ID    string
	Value string
	// contains filtered or unexported fields
}

Represents a primitive object, which only contains one value

func (Primitive) Code added in v0.2.0

func (p Primitive) Code() (string, error)

func (Primitive) FieldID

func (p Primitive) FieldID() string

func (Primitive) TLV

func (p Primitive) TLV() (string, string, string, error)

func (Primitive) Unwrap added in v0.3.0

func (p Primitive) Unwrap() map[string]Primitive

type Static

type Static struct {
	Chave                string `json:"chave"`
	MerchantCategoryCode string `json:"mechantCategoryCode"`
	TransactionCurrency  string `json:"transactionCurrency"`
	CountryCode          string `json:"countryCode"`
	MerchantName         string `json:"merchantName"`
	MerchantCity         string `json:"merchantCity"`
	PostalCode           string `json:"postalCode"`
	TransactionId        string `json:"transactionId"`
	// Transaction amount in cents
	TransactionAmount int `json:"transactionAmount"`
	// contains filtered or unexported fields
}

func NewStatic

func NewStatic(chave, merchantName, merchantCity, txId string, fns ...StaticOptFn) *Static

func (*Static) BRCode

func (s *Static) BRCode() (string, error)

func (Static) Encode

func (s Static) Encode() ([]byte, error)

TODO: Add options as params

func (Static) SaveFile

func (s Static) SaveFile(path string) error

Creates and saves a QRCode in the specified path. Image format is PNG.

func (Static) Serve

func (s Static) Serve(w http.ResponseWriter) error

Encodes and serves the QRCode image TODO: Add options as params

type StaticOptFn

type StaticOptFn func(*Static)

func WithCountryCode

func WithCountryCode(code string) StaticOptFn

func WithMerchantCategoryCode

func WithMerchantCategoryCode(code string) StaticOptFn

func WithPostalCode

func WithPostalCode(postalCode string) StaticOptFn

func WithTransactionAmount

func WithTransactionAmount(value int) StaticOptFn

type TLV

type TLV interface {
	// Returns the (id, length, value) of a given field
	TLV() (id string, length string, value string, err error)
	// Returns the field id
	FieldID() string
	// Return id + length + value
	Code() (string, error)
	Unwrap() map[string]Primitive
}

Represents a Type, Value, Lenght (TLV) object. TODO: Add a struct representing the data

type Template

type Template struct {
	ID string
	// contains filtered or unexported fields
}

Represets a template object, which contains multiple values. Template values also implement the TLV interface

func (*Template) AddValue

func (t *Template) AddValue(id, value string)

func (Template) Code added in v0.2.0

func (t Template) Code() (string, error)

func (Template) FieldID

func (t Template) FieldID() string

func (Template) Sorted added in v0.3.0

func (t Template) Sorted() []Primitive

Ensures consistency

func (Template) TLV

func (t Template) TLV() (string, string, string, error)

func (Template) Unwrap added in v0.3.0

func (t Template) Unwrap() map[string]Primitive

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL