Skip to content

Demo API Reference

Auto-generated API documentation for the demo module.

iso8583sim.demo

Interactive demo helpers for notebooks and exploration.

demo

Demo module with helper functions for notebooks and interactive use.

This module provides convenient functions for: - Pretty-printing ISO 8583 messages - Generating sample messages for different scenarios - Explaining message components

pretty_print

pretty_print(message: ISO8583Message | str, show_raw: bool = False) -> None

Pretty print an ISO 8583 message.

Parameters:

Name Type Description Default
message ISO8583Message | str

ISO8583Message object or raw message string

required
show_raw bool

Whether to show the raw message bytes

False
Source code in iso8583sim/demo.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def pretty_print(message: ISO8583Message | str, show_raw: bool = False) -> None:
    """Pretty print an ISO 8583 message.

    Args:
        message: ISO8583Message object or raw message string
        show_raw: Whether to show the raw message bytes
    """
    if isinstance(message, str):
        message = _parser.parse(message)

    print("=" * 60)
    print(f"ISO 8583 Message - MTI: {message.mti}")
    print("=" * 60)

    # MTI breakdown
    mti = message.mti
    version_map = {"0": "1987", "1": "1993", "2": "2003"}
    class_map = {
        "1": "Authorization",
        "2": "Financial",
        "3": "File Action",
        "4": "Reversal",
        "5": "Reconciliation",
        "6": "Administrative",
        "7": "Fee Collection",
        "8": "Network Mgmt",
        "9": "Reserved",
    }
    function_map = {
        "0": "Request",
        "1": "Response",
        "2": "Advice",
        "3": "Advice Response",
        "4": "Notification",
        "5": "Notification Ack",
    }
    origin_map = {"0": "Acquirer", "1": "Acquirer Repeat", "2": "Issuer", "3": "Issuer Repeat", "4": "Other"}

    print("\nMTI Breakdown:")
    print(f"  Version:  {mti[0]} ({version_map.get(mti[0], 'Unknown')})")
    print(f"  Class:    {mti[1]} ({class_map.get(mti[1], 'Unknown')})")
    print(f"  Function: {mti[2]} ({function_map.get(mti[2], 'Unknown')})")
    print(f"  Origin:   {mti[3]} ({origin_map.get(mti[3], 'Unknown')})")

    if message.bitmap:
        print(f"\nBitmap: {message.bitmap}")

    print(f"\nFields ({len(message.fields) - 1} data elements):")
    print("-" * 60)

    for field_num in sorted(message.fields.keys()):
        if field_num == 0:
            continue  # Skip MTI

        value = message.fields[field_num]
        try:
            field_def = get_field_definition(field_num)
            desc = field_def.description[:35]
            ftype = field_def.field_type.name
        except (KeyError, AttributeError):
            desc = "Unknown"
            ftype = "?"

        # Mask PAN if present
        display_value = value
        if field_num == 2 and len(value) > 8:
            display_value = value[:6] + "*" * (len(value) - 10) + value[-4:]

        print(f"  F{field_num:03d} [{ftype:5s}] {desc:35s} = {display_value}")

    if show_raw and message.raw_message:
        print(f"\nRaw Message ({len(message.raw_message)} bytes):")
        print(message.raw_message)

    print("=" * 60)

explain_field

explain_field(field_number: int, value: str | None = None) -> None

Explain a specific field's definition and optionally its value.

Parameters:

Name Type Description Default
field_number int

The field number to explain

required
value str | None

Optional field value to interpret

None
Source code in iso8583sim/demo.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def explain_field(field_number: int, value: str | None = None) -> None:
    """Explain a specific field's definition and optionally its value.

    Args:
        field_number: The field number to explain
        value: Optional field value to interpret
    """
    field_def = get_field_definition(field_number)
    if field_def is None:
        print(f"Field {field_number}: Unknown field")
        return

    print(f"Field {field_number}: {field_def.description}")
    print("-" * 50)
    print(f"  Type: {field_def.field_type.name}")
    print(f"  Max Length: {field_def.max_length}")

    # Special field interpretations
    if value:
        print(f"  Value: {value}")

        if field_number == 3:  # Processing code
            proc_type = PROCESSING_CODES.get(value[:2], "Unknown")
            print(f"  Interpretation: {proc_type}")

        elif field_number == 39:  # Response code
            resp_desc = RESPONSE_CODES.get(value, "Unknown")
            print(f"  Interpretation: {resp_desc}")

        elif field_number == 22:  # POS entry mode
            entry_modes = {
                "00": "Unknown",
                "01": "Manual",
                "02": "Mag stripe",
                "05": "Chip",
                "07": "Contactless chip",
                "09": "E-commerce",
                "91": "Contactless mag stripe",
            }
            entry = entry_modes.get(value[:2], "Unknown")
            pin_cap = {"0": "Unknown", "1": "Can accept PIN", "2": "Cannot accept PIN"}.get(value[2:3], "?")
            print(f"  Entry Mode: {entry}")
            print(f"  PIN Capability: {pin_cap}")

        elif field_number == 49:  # Currency
            currencies = {"840": "USD", "978": "EUR", "826": "GBP", "124": "CAD", "036": "AUD"}
            curr = currencies.get(value, "Unknown")
            print(f"  Currency: {curr}")

generate_auth_request

generate_auth_request(pan: str = '4111111111111111', amount: int = 1000, stan: str = '123456', terminal_id: str = 'TERM0001', merchant_id: str = 'MERCHANT123456 ', network: CardNetwork | None = None) -> ISO8583Message

Generate a sample authorization request.

Parameters:

Name Type Description Default
pan str

Primary Account Number

'4111111111111111'
amount int

Transaction amount in cents

1000
stan str

System Trace Audit Number

'123456'
terminal_id str

Terminal ID (8 chars)

'TERM0001'
merchant_id str

Merchant ID (15 chars)

'MERCHANT123456 '
network CardNetwork | None

Optional network type

None

Returns:

Type Description
ISO8583Message

ISO8583Message object

Source code in iso8583sim/demo.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def generate_auth_request(
    pan: str = "4111111111111111",
    amount: int = 1000,
    stan: str = "123456",
    terminal_id: str = "TERM0001",
    merchant_id: str = "MERCHANT123456 ",
    network: CardNetwork | None = None,
) -> ISO8583Message:
    """Generate a sample authorization request.

    Args:
        pan: Primary Account Number
        amount: Transaction amount in cents
        stan: System Trace Audit Number
        terminal_id: Terminal ID (8 chars)
        merchant_id: Merchant ID (15 chars)
        network: Optional network type

    Returns:
        ISO8583Message object
    """
    return ISO8583Message(
        mti="0100",
        network=network,
        fields={
            0: "0100",
            2: pan,
            3: "000000",
            4: f"{amount:012d}",
            11: stan,
            14: "2612",
            22: "051",
            41: terminal_id,
            42: merchant_id,
            49: "840",
        },
    )

generate_financial_request

generate_financial_request(pan: str = '4111111111111111', amount: int = 5000, stan: str = '654321', processing_code: str = '000000') -> ISO8583Message

Generate a sample financial request (0200).

Parameters:

Name Type Description Default
pan str

Primary Account Number

'4111111111111111'
amount int

Transaction amount in cents

5000
stan str

System Trace Audit Number

'654321'
processing_code str

Processing code (default: purchase)

'000000'

Returns:

Type Description
ISO8583Message

ISO8583Message object

Source code in iso8583sim/demo.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def generate_financial_request(
    pan: str = "4111111111111111",
    amount: int = 5000,
    stan: str = "654321",
    processing_code: str = "000000",
) -> ISO8583Message:
    """Generate a sample financial request (0200).

    Args:
        pan: Primary Account Number
        amount: Transaction amount in cents
        stan: System Trace Audit Number
        processing_code: Processing code (default: purchase)

    Returns:
        ISO8583Message object
    """
    return ISO8583Message(
        mti="0200",
        fields={
            0: "0200",
            2: pan,
            3: processing_code,
            4: f"{amount:012d}",
            11: stan,
            12: "143022",
            13: "1215",
            14: "2612",
            22: "051",
            41: "TERM0001",
            42: "MERCHANT123456 ",
            49: "840",
        },
    )

generate_reversal

generate_reversal(original: ISO8583Message, new_stan: str = '999999') -> ISO8583Message

Generate a reversal message for an original transaction.

Parameters:

Name Type Description Default
original ISO8583Message

The original transaction message

required
new_stan str

New STAN for the reversal

'999999'

Returns:

Type Description
ISO8583Message

ISO8583Message reversal

Source code in iso8583sim/demo.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def generate_reversal(original: ISO8583Message, new_stan: str = "999999") -> ISO8583Message:
    """Generate a reversal message for an original transaction.

    Args:
        original: The original transaction message
        new_stan: New STAN for the reversal

    Returns:
        ISO8583Message reversal
    """
    return ISO8583Message(
        mti="0400",
        fields={
            0: "0400",
            2: original.fields.get(2, ""),
            3: original.fields.get(3, "000000"),
            4: original.fields.get(4, "000000000000"),
            11: new_stan,
            37: original.fields.get(37, ""),
            38: original.fields.get(38, ""),
            41: original.fields.get(41, ""),
            42: original.fields.get(42, ""),
        },
    )

generate_network_message

generate_network_message(message_type: str = 'echo') -> ISO8583Message

Generate a network management message.

Parameters:

Name Type Description Default
message_type str

Type of message - 'echo', 'signon', 'signoff', 'key_exchange'

'echo'

Returns:

Type Description
ISO8583Message

ISO8583Message object

Source code in iso8583sim/demo.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def generate_network_message(message_type: str = "echo") -> ISO8583Message:
    """Generate a network management message.

    Args:
        message_type: Type of message - 'echo', 'signon', 'signoff', 'key_exchange'

    Returns:
        ISO8583Message object
    """
    codes = {
        "echo": "301",
        "signon": "001",
        "signoff": "002",
        "key_exchange": "161",
    }

    return ISO8583Message(
        mti="0800",
        fields={
            0: "0800",
            7: "1215143022",
            11: "000001",
            70: codes.get(message_type, "301"),
        },
    )

generate_emv_auth

generate_emv_auth(pan: str = '4111111111111111', amount: int = 10000, cryptogram: str = 'AABBCCDD11223344') -> ISO8583Message

Generate an EMV chip card authorization.

Parameters:

Name Type Description Default
pan str

Primary Account Number

'4111111111111111'
amount int

Transaction amount in cents

10000
cryptogram str

Application cryptogram (8 bytes hex)

'AABBCCDD11223344'

Returns:

Type Description
ISO8583Message

ISO8583Message with EMV data

Source code in iso8583sim/demo.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def generate_emv_auth(
    pan: str = "4111111111111111",
    amount: int = 10000,
    cryptogram: str = "AABBCCDD11223344",
) -> ISO8583Message:
    """Generate an EMV chip card authorization.

    Args:
        pan: Primary Account Number
        amount: Transaction amount in cents
        cryptogram: Application cryptogram (8 bytes hex)

    Returns:
        ISO8583Message with EMV data
    """
    emv_data = build_emv_data(
        {
            "9F26": cryptogram,
            "9F27": "80",  # ARQC
            "9F10": "06010A03A4B800",
            "9F37": "12345678",
            "9F36": "0001",
            "95": "0000000000",
            "9A": "251215",
            "9C": "00",
            "5F2A": "0840",
            "82": "1980",
            "9F1A": "0840",
        }
    )

    return ISO8583Message(
        mti="0100",
        fields={
            0: "0100",
            2: pan,
            3: "000000",
            4: f"{amount:012d}",
            11: "123456",
            14: "2612",
            22: "051",
            23: "001",
            35: f"{pan}=26125010000000000000",
            41: "TERM0001",
            42: "MERCHANT123456 ",
            49: "840",
            55: emv_data,
        },
    )

build_and_parse

build_and_parse(message: ISO8583Message) -> ISO8583Message

Build a message to raw format and parse it back.

Useful for testing roundtrip.

Parameters:

Name Type Description Default
message ISO8583Message

ISO8583Message to process

required

Returns:

Type Description
ISO8583Message

Parsed message

Source code in iso8583sim/demo.py
371
372
373
374
375
376
377
378
379
380
381
382
383
def build_and_parse(message: ISO8583Message) -> ISO8583Message:
    """Build a message to raw format and parse it back.

    Useful for testing roundtrip.

    Args:
        message: ISO8583Message to process

    Returns:
        Parsed message
    """
    raw = _builder.build(message)
    return _parser.parse(raw)

validate

validate(message: ISO8583Message | str) -> None

Validate a message and print results.

Parameters:

Name Type Description Default
message ISO8583Message | str

ISO8583Message or raw message string

required
Source code in iso8583sim/demo.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def validate(message: ISO8583Message | str) -> None:
    """Validate a message and print results.

    Args:
        message: ISO8583Message or raw message string
    """
    if isinstance(message, str):
        message = _parser.parse(message)

    errors = _validator.validate_message(message)

    print("Validation Result:")
    print("-" * 40)
    print(f"Valid: {'YES' if not errors else 'NO'}")

    if errors:
        print("\nErrors:")
        for error in errors:
            print(f"  - {error}")

explain_emv

explain_emv(emv_hex: str) -> None

Parse and explain EMV data.

Parameters:

Name Type Description Default
emv_hex str

Hex-encoded EMV TLV data

required
Source code in iso8583sim/demo.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def explain_emv(emv_hex: str) -> None:
    """Parse and explain EMV data.

    Args:
        emv_hex: Hex-encoded EMV TLV data
    """
    parsed = parse_emv_data(emv_hex)

    print("EMV Data Analysis:")
    print("=" * 60)

    for tag, value in parsed.items():
        tag_name = EMV_TAGS.get(tag, "Unknown")
        print(f"\nTag {tag}: {tag_name}")
        print(f"  Value: {value}")
        print(f"  Length: {len(value) // 2} bytes")

        # Special interpretations
        if tag == "9F27":  # CID
            cid_types = {"00": "AAC (Decline)", "40": "TC (Offline Approved)", "80": "ARQC (Go Online)"}
            print(f"  Meaning: {cid_types.get(value, 'Unknown')}")

        elif tag == "9C":  # Transaction type
            txn_types = {"00": "Purchase", "01": "Cash", "09": "Cashback", "20": "Refund"}
            print(f"  Meaning: {txn_types.get(value, 'Unknown')}")

        elif tag == "5F2A":  # Currency
            currencies = {"0840": "USD", "0978": "EUR", "0826": "GBP"}
            print(f"  Currency: {currencies.get(value, 'Unknown')}")