(20241207) Worked on telegram Bot and Safaricom's M-Pesa payments.

This commit is contained in:
2024-12-07 17:52:51 +05:30
parent 8b26baa29a
commit 9d5fb6805b
10 changed files with 983 additions and 47 deletions
@@ -0,0 +1,130 @@
"""
AUTHOR:
Khushal P Soonderji
DATE:
Saturday, 7th Dec., 2024.
OBJECTIVE:
To provide a data model for describing the API response from Safaricom's M-Pesa Express APIs.
REFERENCES:
N/A
DOWNLOADS:
N/A
"""
# *****************************************************************************************************************
# ***** ****
# *** IMPORT ***
# ***** ****
# *****************************************************************************************************************
# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")
# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, model_validator
from typing import Optional, Literal, Union, Dict, List, Any
# My utils:
from utils_v2.string import json
from utils_v2.string import regex
# *****************************************************************************************************************
# ***** ****
# *** MACROS / ONE-TIME INIT ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** VARIABLES ***
# ***** ****
# *****************************************************************************************************************
# --- Nothing Yet
# *****************************************************************************************************************
# ***** ****
# *** FUNCTIONS ***
# ***** ****
# *****************************************************************************************************************
class MPesaExpressApiResponse(BaseModel):
action: str = Field(frozen = True, default = None)
url: str = Field(frozen = True)
method: str = Field(frozen = True)
response: Any = None
httpCode: int = None
success: bool = False
message: str = None
data: Any = None
exception: Any = None
# ┏┓ ┏•
# ┃ ┏┓┏┓╋┓┏┓
# ┗┛┗┛┛┗┛┗┗┫
# ┛
class Config:
extra = "forbid"
# ┏┓ ┏┓
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
def to_markdown(self):
if self.exception: message = "❌ *M-PESA API EXCEPTION:* ❌\n\n"
else: message = "*M-PESA API RESPONSE:*\n\n"
message += f"*ACTION:*\n`{self.action}`\n\n"
message += f"*URL:*\n`{self.url}`\n\n"
message += f"*METHOD:*\n`{self.method}`\n\n"
message += f"*RESPONSE:*\n`{self.response}`\n\n"
message += f"*SUCCESS:*\n`{self.success}`\n\n"
message += f"*MESSAGE:*\n`{self.message}`\n\n"
message += f"*EXCEPTION:*\n`{self.exception.__class__.__name__}: {str(self.exception)}`\n\n"
return message
async def get_json(self):
try: return self.response.json()
except: return {}
async def get_content(self):
try: return self.response.content
except: return b""
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***
# ***** ****
# *****************************************************************************************************************
if __name__ == "__main__":
pass
@@ -101,7 +101,7 @@ class MPesaExpressAuthorization(BaseModel):
frozen = True
)
shortCode: str = Field(
businessShortCode: str = Field(
description = "your app's business short code; found in 'my apps'",
frozen = True
)
@@ -111,10 +111,11 @@ class MPesaExpressAuthorization(BaseModel):
frozen = True
)
callbackUrl: str = Field(
callbackUrl: str | None = Field(
description = "the url for m-pesa to inform you about a successful or failed payment",
frozen = True,
pattern = regex.REGEX_HTTPS_URL
pattern = regex.REGEX_HTTPS_URL,
default = None
)
# Don't pass these values from outside,
@@ -170,22 +171,17 @@ class MPesaExpressAuthorization(BaseModel):
# ┃ ┓┏┏╋┏┓┏┳┓ ┣ ┓┏┏┓┏┏
# ┗┛┗┻┛┗┗┛┛┗┗ ┻ ┗┻┛┗┗┛
async def get_access_token(
async def refresh(
self,
http_client: httpx.AsyncClient = None
) -> str | None:
http_client: httpx.AsyncClient = None,
force_refresh: bool = False
) -> bool:
"""
If you just pick the 'accessToken' variable, you may get a stale token. Using this method will ensure that the
token is refreshed, if needed, before being handed to you.
:param http_client: A preset HTTP client to use. If not given, one will be created inside and used to make the
API call. Giving it from outside could save time in setting up a new client. You may start passing this when
you notice delays.
:return: Either a valid access token or None if the refreshing fails.
"""
# Start by assuming failure:
token_refreshed = False
# If the token is stale:
if self.expired:
# If the token is stale or a refresh is being forced:
if self.expired or force_refresh:
# Prepare the inputs:
url = M_PESA_EXPRESS_AUTH_API_URL
@@ -193,7 +189,7 @@ class MPesaExpressAuthorization(BaseModel):
input_headers = {"Authorization": "Basic " + key}
input_params = {"grant_type": "client_credentials"}
# make the API call:
# Make the API call:
if http_client:
api_response = await http_client.get(
url = url,
@@ -214,9 +210,29 @@ class MPesaExpressAuthorization(BaseModel):
self.accessToken = api_json.get("access_token")
self.lastRefresh = date_time.get_current_utc_date_time()
self.expiresAt = self.lastRefresh + datetime.timedelta(seconds = int(0.95 * float(api_json.get("expires_in"))))
token_refreshed = True
# Now that refreshing attempt is done:
return None if self.expired else self.accessToken
# Done here:
return token_refreshed
async def get_access_token(
self,
http_client: httpx.AsyncClient = None,
force_refresh: bool = False
) -> str | None:
"""
If you just pick the 'accessToken' variable, you may get a stale token. Using this method will ensure that the
token is refreshed, if needed, before being handed to you.
:param http_client: A preset HTTP client to use. If not given, one will be created inside and used to make the
API call. Giving it from outside could save time in setting up a new client. You may start passing this when
you notice delays.
:param force_refresh: Use this to force a token refresh even if it hasn't expired yet.
:return: Either a valid access token or None if the refreshing fails.
"""
await self.refresh(http_client = http_client, force_refresh = force_refresh)
return self.accessToken
# *****************************************************************************************************************
@@ -233,9 +249,9 @@ if __name__ == "__main__":
auth = MPesaExpressAuthorization(
consumerKey = "kFiHZ3G1vCqxkQfHgMZzPvkPd5ilsJD3",
consumerSecret = "NIp2mp1V0cSEQ63G",
shortCode = "4092041",
businessShortCode = "4092041",
appPasskey = "cf5c0f05298e63b4039c60e3fd12c2f72e1adac840d3dbd68c88a33b43dbef82",
callbackUrl = "https://www.something.otherthing.com/my/callback/path?with=params"
# callbackUrl = "https://www.something.otherthing.com/my/callback/path?with=params"
)
print("AUTH:", auth.model_dump_json(indent = 4))