Skip to content

Instantly share code, notes, and snippets.

@enriquesaid
Last active November 2, 2023 21:15
Show Gist options
  • Save enriquesaid/9e914d084143a48ea813b5a5394d80ce to your computer and use it in GitHub Desktop.
Save enriquesaid/9e914d084143a48ea813b5a5394d80ce to your computer and use it in GitHub Desktop.
Dart BR Code PIX Estático
import 'dart:convert';
import 'package:crclib/catalog.dart';
// const test_pix = '00020126360014BR.GOV.BCB.PIX0114+55119647714305204000053039865406986.005802BR5913Fulano de Tal6008BRASILIA62070503***63047E91';
// const test_pix2 = '00020126360014BR.GOV.BCB.PIX0114+55119647714305204000053039865406100.005802BR5907Enrique6009Sao Paulo62070503***630402D3';
class Data {
const Data({
required this.amout,
required this.pixKey,
required this.merchantName,
this.merchantCity = '',
});
final String pixKey;
final double amout;
final String merchantName;
final String merchantCity;
}
class BRCodeValue {
const BRCodeValue(this.id, this.value);
final int id;
final String value;
String get formattedId => id.toString().padLeft(2, "0");
String get formattedLength => value.length.toString().padLeft(2, "0");
@override
toString() {
return '$formattedId$formattedLength$value';
}
}
class BRCode {
BRCode(this.data);
final Data data;
final _crc = Crc16CcittFalse();
final _crcLength = 4;
final _crcId = 63;
String generate() {
final result = _buildValues({
00: "01",
26: _buildValues({
00: "br.gov.bcb.pix".toUpperCase(),
01: data.pixKey,
}),
52: "0000",
53: "986",
54: data.amout.toStringAsFixed(2),
58: "BR",
59: data.merchantName,
60: data.merchantCity,
62: _buildValues({05: "***"}),
});
return '$result${_buildCrcValue(result)}';
}
String _buildValues(Map<int, String> map) {
final values = List.from(
map.entries.map(
(e) => BRCodeValue(e.key, e.value).toString(),
),
);
return values.join("");
}
String _buildCrcValue(String value) {
final length = _crcLength.toString().padLeft(2, "0");
return BRCodeValue(_crcId, _toCrc('$value$_crcId$length')).toString();
}
String _toCrc(String result) {
return _crc
.convert(utf8.encode(result))
.toRadixString(16)
.padLeft(_crcLength, '0')
.toUpperCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment