|
| 1 | +"""mpesa_sdk.dynamic_qr_code.schemas. |
| 2 | +
|
| 3 | +This module defines the schemas for generating a dynamic M-Pesa QR code. |
| 4 | +It includes request and response models using Pydantic for validation and serialization. |
| 5 | +""" |
| 6 | + |
| 7 | +from enum import Enum |
| 8 | +from typing import Optional |
| 9 | +from pydantic import BaseModel, Field, ConfigDict |
| 10 | +from pydantic import model_validator |
| 11 | +from mpesa_sdk.utils.phone import normalize_phone_number |
| 12 | + |
| 13 | + |
| 14 | +class DynamicQRTransactionType(str, Enum): |
| 15 | + """Enum representing the supported transaction types for Dynamic QR.""" |
| 16 | + |
| 17 | + BUY_GOODS = "BG" # Pay Merchant (Buy Goods) |
| 18 | + WITHDRAW_CASH = "WA" # Withdraw Cash at Agent Till |
| 19 | + PAYBILL = "PB" # Paybill or Business number |
| 20 | + SEND_MONEY = "SM" # Send Money (Mobile number) |
| 21 | + SEND_TO_BUSINESS = "SB" # Sent to Business (Bu.siness number CPI in MSISDN format) |
| 22 | + |
| 23 | + |
| 24 | +class DynamicQRGenerateRequest(BaseModel): |
| 25 | + """Represents the request payload for generating a Dynamic QR code. |
| 26 | +
|
| 27 | + https://developer.safaricom.co.ke/APIs/DynamicQRCode |
| 28 | +
|
| 29 | + Attributes: |
| 30 | + MerchantName (str): Name of the Company/M-Pesa Merchant Name. |
| 31 | + RefNo (str): Transaction Reference. For Paybill, Withdraw Cash, and similar transactions, this is where you enter your account number. |
| 32 | + Amount (float): The total amount for the sale/transaction. |
| 33 | + TrxCode (DynamicQRTransactionType): Transaction Type. |
| 34 | + CPI (str): Credit Party Identifier (Mobile Number, Business Number, Agent Till, Paybill, etc.). |
| 35 | + Size (str): Size of the QR code image in pixels (always a square image). |
| 36 | + """ |
| 37 | + |
| 38 | + MerchantName: str = Field( |
| 39 | + ..., |
| 40 | + description="Name of the Company/M-Pesa Merchant Name.", |
| 41 | + examples=["TEST SUPERMARKET"], |
| 42 | + ) |
| 43 | + RefNo: str = Field( |
| 44 | + ..., |
| 45 | + description="Transaction Reference. For Paybill, Withdraw Cash, and similar transactions, this is where you enter your account number.", |
| 46 | + examples=["Invoice Test", "xewr34fer4t", "ACC12345"], |
| 47 | + ) |
| 48 | + Amount: int = Field( |
| 49 | + ..., |
| 50 | + description="The total amount for the sale/transaction.", |
| 51 | + examples=[1, 2000], |
| 52 | + gt=0, |
| 53 | + ) |
| 54 | + TrxCode: str = Field( |
| 55 | + ..., |
| 56 | + description="Transaction Type. Supported: BG, WA, PB, SM, SB.", |
| 57 | + examples=["BG"], |
| 58 | + ) |
| 59 | + |
| 60 | + CPI: str = Field( |
| 61 | + ..., |
| 62 | + description="Credit Party Identifier. Can be a Mobile Number, Business Number, Agent Till, Paybill or Business number, or Merchant Buy Goods.", |
| 63 | + examples=["373132", "174379"], |
| 64 | + ) |
| 65 | + Size: str = Field( |
| 66 | + ..., |
| 67 | + description="Size of the QR code image in pixels. QR code image will always be a square image.", |
| 68 | + examples=["300"], |
| 69 | + ) |
| 70 | + |
| 71 | + model_config = ConfigDict( |
| 72 | + json_schema_extra={ |
| 73 | + "example": { |
| 74 | + "MerchantName": "TEST SUPERMARKET", |
| 75 | + "RefNo": "Invoice Test", |
| 76 | + "Amount": 1, |
| 77 | + "TrxCode": "BG", |
| 78 | + "CPI": "373132", |
| 79 | + "Size": "300", |
| 80 | + } |
| 81 | + } |
| 82 | + ) |
| 83 | + |
| 84 | + @classmethod |
| 85 | + def validate_trx_code(cls, value): |
| 86 | + """Validates the transaction code against the DynamicQRTransactionType enum.""" |
| 87 | + try: |
| 88 | + DynamicQRTransactionType(value) |
| 89 | + except ValueError: |
| 90 | + raise ValueError( |
| 91 | + f"TrxCode must be one of: {[e.value for e in DynamicQRTransactionType]}" |
| 92 | + ) |
| 93 | + return value |
| 94 | + |
| 95 | + @classmethod |
| 96 | + def normalize_cpi_for_send_money(cls, values): |
| 97 | + """If TrxCode is SEND_MONEY, normalize the CPI (mobile number). |
| 98 | +
|
| 99 | + - If it starts with '0', replace with '254' |
| 100 | + - If it starts with '+254', replace with '254' |
| 101 | + - If it can't be normalized, raise ValueError |
| 102 | + """ |
| 103 | + trx_code = values.get("TrxCode") |
| 104 | + cpi = values.get("CPI") |
| 105 | + if trx_code == DynamicQRTransactionType.SEND_MONEY.value and isinstance( |
| 106 | + cpi, str |
| 107 | + ): |
| 108 | + normalized = normalize_phone_number(cpi) |
| 109 | + if normalized is None: |
| 110 | + raise ValueError( |
| 111 | + "CPI for SEND_MONEY must be a valid Kenyan phone number starting with '0', '+254', or '254'." |
| 112 | + ) |
| 113 | + values["CPI"] = normalized |
| 114 | + return values |
| 115 | + |
| 116 | + @model_validator(mode="before") |
| 117 | + def validate(cls, values): |
| 118 | + """Validates the TrxCode field before model validation.""" |
| 119 | + # Validate the TrxCode field |
| 120 | + trx_code = values.get("TrxCode") |
| 121 | + if trx_code is not None: |
| 122 | + cls.validate_trx_code(trx_code) |
| 123 | + |
| 124 | + # Normalize CPI for SEND_MONEY transaction type |
| 125 | + values = cls.normalize_cpi_for_send_money(values) |
| 126 | + |
| 127 | + return values |
| 128 | + |
| 129 | + |
| 130 | +class DynamicQRGenerateResponse(BaseModel): |
| 131 | + """Represents the response returned after generating a Dynamic QR code. |
| 132 | +
|
| 133 | + https://developer.safaricom.co.ke/APIs/DynamicQRCode |
| 134 | +
|
| 135 | + Attributes: |
| 136 | + ResponseCode (str): Used to return the Transaction Type (alpha-numeric string). |
| 137 | + RequestID (str): Unique identifier for the request. |
| 138 | + ResponseDescription (str): Description of the transaction status. |
| 139 | + QRCode (str): QR Code Image/Data/String (base64 or similar). |
| 140 | + """ |
| 141 | + |
| 142 | + ResponseCode: str = Field( |
| 143 | + ..., |
| 144 | + description="Used to show if the transaction was successful or not. 00 indicates success.", |
| 145 | + examples=["00"], |
| 146 | + ) |
| 147 | + ResponseDescription: str = Field( |
| 148 | + ..., |
| 149 | + description="This is a response describing the status of the transaction.", |
| 150 | + examples=["QR Code Successfully Generated."], |
| 151 | + ) |
| 152 | + QRCode: str = Field( |
| 153 | + ..., |
| 154 | + description="QR Code Image/Data/String.", |
| 155 | + examples=["iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAIAAAD2HxkiAAAHtElEQVR42..."], |
| 156 | + ) |
| 157 | + |
| 158 | + model_config = ConfigDict( |
| 159 | + json_schema_extra={ |
| 160 | + "example": { |
| 161 | + "ResponseCode": "00", |
| 162 | + "RequestID": "16738-27456357-1", |
| 163 | + "ResponseDescription": "QR Code Successfully Generated.", |
| 164 | + "QRCode": "iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAIAAAD2HxkiAAAHtElEQVR42...", |
| 165 | + } |
| 166 | + } |
| 167 | + ) |
0 commit comments