(20241228) Payments module revamped!
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Saturday, 28th Dec., 2024
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To handle all common actions related to payments from one place. This includes cases where you don't yet know
|
||||
the third-party client or it doesn't matter who the third-party client is. For example, take those cases when
|
||||
you just need to fetch one record about a payment.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
N/A
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# My async utils:
|
||||
from utils_v2.database.async_mysql_v2 import AsyncMySQL
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
from utils_v2.cache.async_redis_cache_v2 import AsyncRedisCache
|
||||
|
||||
# Controllers:
|
||||
from controllers_v2.finstitutions.payments.base import PaymentsController
|
||||
|
||||
# Models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.core.auth_token import CoreAuthTokenModel
|
||||
from models.api.finstitutions.payments.request import PGPaymentRequestData, PaymentRequestOneResult
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import List, Any
|
||||
|
||||
# To make HTTP requests:
|
||||
import httpx
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** CLASSES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class AllPaymentsController(PaymentsController):
|
||||
|
||||
# ┏┓
|
||||
# ┃ ┏┓┏┓┏╋┏┓┓┏┏╋┏┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┛ ┗┻┗┗┗┛┛
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache: AsyncRedisCache = None,
|
||||
http_client: httpx.AsyncClient = None,
|
||||
alert_url: str = None,
|
||||
debug: bool = True,
|
||||
debug_prefix: str = "All Payments (C) | ",
|
||||
debug_only_errors: bool = True
|
||||
):
|
||||
|
||||
"""
|
||||
This is the foundational controller for all trading services. Use this for any smaller common tasks where you
|
||||
may not know the exact client beforehand.
|
||||
:param cache: The object to use for caching results from database calls.
|
||||
:param http_client: The HTTP client
|
||||
:param debug: Whether, or not, you would like to print debugging messages:
|
||||
:param debug_prefix: The prefix to print with the debugging messages.
|
||||
:param debug_only_errors: Whether you would like to print only error messages or all messages.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
# Invoke the parent's constructor:
|
||||
super().__init__(
|
||||
cache = cache,
|
||||
alert_url = alert_url,
|
||||
http_client = http_client,
|
||||
base_filter = None,
|
||||
debug = debug,
|
||||
debug_prefix = debug_prefix,
|
||||
debug_only_errors = debug_only_errors
|
||||
)
|
||||
|
||||
# ┳┓ ┏┓
|
||||
# ┣┫┏┓┏┓┓┏┏┓┏╋ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
# ┛┗┗ ┗┫┗┻┗ ┛┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┗ ┛
|
||||
|
||||
async def request_payment(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
user_info: CoreUserInfoModel,
|
||||
payment_request: PGPaymentRequestData,
|
||||
) -> PaymentRequestOneResult:
|
||||
|
||||
"""
|
||||
To request payment from someone through a payment gateway.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param auth_token: The token that has to be used to fetch the data.
|
||||
:param user_info: The info. of your user, so that you can identify who requested the payment.
|
||||
:param payment_request: The data that came in with the APi call.
|
||||
:return: The structured response form the payment gateway.
|
||||
"""
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
async def handle_payment_callback(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
inbound_data: dict
|
||||
):
|
||||
|
||||
"""
|
||||
Whenever the payment gateway sends an update about a requested payment, we use this method to update our records
|
||||
as per the specification of the third-party payment gateway.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param inbound_data: The data sent by the payment gateway in their update.
|
||||
|
||||
:return: ??
|
||||
"""
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pass
|
||||
@@ -0,0 +1,515 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Saturday, 28th Dec., 2024
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To handle all payments-related behaviour from one place.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
N/A
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# My async utils:
|
||||
from utils_v2.database.async_mysql_v2 import AsyncMySQL
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
from utils_v2.cache.async_redis_cache_v2 import AsyncRedisCache
|
||||
|
||||
# Controllers:
|
||||
from controllers_v2.core.auth_token import CoreAuthTokenController
|
||||
|
||||
# Models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.core.auth_token import CoreAuthTokenModel
|
||||
from models.core.payment import CorePaymentModel, PaymentEvent, CustomerDetails
|
||||
from models.api.finstitutions.payments.request import PGPaymentRequestData, PaymentRequestOneResult
|
||||
|
||||
# To work with MongoDB:
|
||||
from bson import ObjectId
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import List, Any
|
||||
|
||||
# To make HTTP requests:
|
||||
import httpx
|
||||
|
||||
# To make abstract classes:
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** CLASSES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class PaymentsController(CoreAuthTokenController, ABC):
|
||||
|
||||
# ┏┓┓ ┓┏
|
||||
# ┃ ┃┏┓┏┏ ┃┃┏┓┏┓┏
|
||||
# ┗┛┗┗┻┛┛ ┗┛┗┻┛ ┛
|
||||
|
||||
# For MongoDB:
|
||||
PAYMENTS_COLLECTION = "_payments"
|
||||
|
||||
# ┏┓
|
||||
# ┃ ┏┓┏┓┏╋┏┓┓┏┏╋┏┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┛ ┗┻┗┗┗┛┛
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache: AsyncRedisCache = None,
|
||||
http_client: httpx.AsyncClient = None,
|
||||
alert_url: str = None,
|
||||
base_filter: dict = None,
|
||||
debug: bool = True,
|
||||
debug_prefix: str = "Payments (C) | ",
|
||||
debug_only_errors: bool = True
|
||||
):
|
||||
|
||||
"""
|
||||
This is the foundational controller for all trading/stockbroking services. This is built on top of the
|
||||
authorization model, and, in turn, the individual stockbroking clients should be built on top of this.
|
||||
:param cache: The object to use for caching results from database calls.
|
||||
:param http_client: The HTTP client
|
||||
:param base_filter: The basic filter that will be applied to all fetching/updating queries. WARNING: THE BASE
|
||||
FILTER WILL ALWAYS BE APPLIED AUTOMATICALLY. SET THIS UP WISELY.
|
||||
:param debug: Whether, or not, you would like to print debugging messages:
|
||||
:param debug_prefix: The prefix to print with the debugging messages.
|
||||
:param debug_only_errors: Whether you would like to print only error messages or all messages.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
# Declare the service type:
|
||||
this_service_type = "paymentGateway"
|
||||
|
||||
# Prepare base filter:
|
||||
this_filter = {}
|
||||
for k, v in (base_filter or {}).items(): this_filter[k] = v
|
||||
this_filter["serviceType"] = this_service_type
|
||||
|
||||
# Invoke the parent's constructor:
|
||||
CoreAuthTokenController.__init__(
|
||||
self,
|
||||
cache = cache,
|
||||
alert_url = alert_url,
|
||||
http_client = http_client,
|
||||
base_filter = this_filter,
|
||||
debug = debug,
|
||||
debug_prefix = debug_prefix,
|
||||
debug_only_errors = debug_only_errors
|
||||
)
|
||||
|
||||
# Init a variable in a parent:
|
||||
self._service_type = this_service_type
|
||||
|
||||
# ┓ • ┏┓
|
||||
# ┃ ┓┏╋ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
# ┗┛┗┛┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┛
|
||||
|
||||
# These are simply for retrieving payment records.
|
||||
# You need to already have them saved to the database.
|
||||
|
||||
async def count_payments(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
token_ids: List[ObjectId | str],
|
||||
additional_filter: dict = None
|
||||
) -> int:
|
||||
|
||||
"""
|
||||
Just counts the no. of payment records that match a given set of conditions.
|
||||
:param mongo_data_conn: The instance of the database connector to use for the operation.
|
||||
:param token_ids: The token ids of the accounts from which these payment details must be fetched.
|
||||
:param additional_filter: Any addition filters to use.
|
||||
:return: The no. of payment records that match the given conditions.
|
||||
"""
|
||||
|
||||
# Prepare the filter:
|
||||
if not isinstance(token_ids, list): token_ids = [token_ids]
|
||||
token_ids = [ObjectId(t) for t in token_ids]
|
||||
filter_json = {"tokenId": {"$in": token_ids}}
|
||||
if additional_filter:
|
||||
for k, v in additional_filter.items():
|
||||
filter_json[k] = v
|
||||
|
||||
# Get the count of the documents that match the criteria:
|
||||
count = await mongo_data_conn.count(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = filter_json,
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
# Done here:
|
||||
return count
|
||||
|
||||
async def list_payments(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
token_ids: List[ObjectId | str],
|
||||
limit: int = 100,
|
||||
skip: int = 0,
|
||||
additional_filter: dict = None
|
||||
) -> List[CorePaymentModel] | None:
|
||||
|
||||
"""
|
||||
Fetches many payment details in one call, but just their previews.
|
||||
:param mongo_data_conn: The instance of the database connector to use for the operation.
|
||||
:param token_ids: The token ids of the accounts from which these messages must be fetched.
|
||||
:param limit: The max. no. of payment details to retrieve in this call.
|
||||
:param skip: The no. of initial payment details to skip. Useful for pagination.
|
||||
:param additional_filter: Any addition filters to use.
|
||||
:return: The list of payments (as the payments model). This list can be empty.
|
||||
"""
|
||||
|
||||
# Prepare the filter:
|
||||
if not isinstance(token_ids, list): token_ids = [token_ids]
|
||||
token_ids = [ObjectId(t) for t in token_ids]
|
||||
filter_json = {"tokenId": {"$in": token_ids}}
|
||||
if additional_filter:
|
||||
for k, v in additional_filter.items():
|
||||
filter_json[k] = v
|
||||
|
||||
# We fetch the messages that are identified by a specific token id,
|
||||
# with the specified fetching limits, while enforcing the sorting condition:
|
||||
records = await mongo_data_conn.find_many(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = filter_json,
|
||||
projection = {"events": False},
|
||||
limit = limit,
|
||||
skip = skip,
|
||||
sort = {"ts": -1},
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
# Convert the fetched records to instances of the data model and return:
|
||||
for record in records: record["events"] = []
|
||||
return [CorePaymentModel(**record) for record in records]
|
||||
|
||||
async def get_payment(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
payment_id: ObjectId | str
|
||||
) -> CorePaymentModel | None:
|
||||
|
||||
"""
|
||||
Gets one payment detail if you know its payment id.
|
||||
:param mongo_data_conn: The instance of the database connector to use for the operation.
|
||||
:param payment_id: The id of the payment detail that needs to be read.
|
||||
:return: The contents of that one payment detail in a structured format.
|
||||
"""
|
||||
|
||||
# We fetch the whole payload of that one message:
|
||||
record = await mongo_data_conn.find_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = {"_id": ObjectId(payment_id)},
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
# If no such message was found:
|
||||
if record is None: return None
|
||||
|
||||
# If a record was found,
|
||||
# we return it as our data model:
|
||||
return CorePaymentModel(**record)
|
||||
|
||||
# ┳┳ ┓ ┏┓
|
||||
# ┃┃┏┓┏┫┏┓╋┏┓ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
# ┗┛┣┛┗┻┗┻┗┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┛ ┛
|
||||
|
||||
# We don't support updating payments themselves,
|
||||
# but we will allow updating fields like tags, adding events, etc.
|
||||
|
||||
async def add_event_by_payment_id(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
payment_id: ObjectId | str,
|
||||
event: PaymentEvent,
|
||||
client_reference_id: str = None
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Add an event to an existing record of a payment detail.
|
||||
:param mongo_data_conn: The instance of the database connector to use for the operation.
|
||||
:param payment_id: The id of the payment detail that needs to be read.
|
||||
:param event: The event that occurred. This will typically be generated by the third-party client.
|
||||
:param client_reference_id: The way the client identifies this payment. You need to pass this only on the first
|
||||
event. Typically, when you initiate the payment request.
|
||||
:return: True if successfully noted, else False.
|
||||
"""
|
||||
|
||||
# Prepare the update document:
|
||||
update_json = {
|
||||
"$push": {
|
||||
"events": event.model_dump()
|
||||
},
|
||||
"$set": {
|
||||
"lastEventTs": event.eventTs,
|
||||
"lastEventMessage": event.message,
|
||||
"lastPaymentStatus": event.paymentStatus,
|
||||
}
|
||||
}
|
||||
if client_reference_id: update_json["$set"]["clientPaymentReferenceId"] = client_reference_id
|
||||
|
||||
# Try to update the existing record:
|
||||
return await mongo_data_conn.update_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = {"_id": ObjectId(payment_id)},
|
||||
update = update_json,
|
||||
upsert = False,
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
async def add_event_by_client_reference_id(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
client_reference_id: str,
|
||||
event: PaymentEvent,
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Add an event to an existing record of a payment detail.
|
||||
:param mongo_data_conn: The instance of the database connector to use for the operation.
|
||||
:param event: The event that occurred. This will typically be generated by the third-party client.
|
||||
:param client_reference_id: The way the client identifies this payment. You need to pass this only on the first
|
||||
event. Typically, when you initiate the payment request.
|
||||
:return: True if successfully noted, else False.
|
||||
"""
|
||||
|
||||
# Prepare the update document:
|
||||
update_json = {
|
||||
"$push": {
|
||||
"events": event.model_dump()
|
||||
},
|
||||
"$set": {
|
||||
"lastEventTs": event.eventTs,
|
||||
"lastEventMessage": event.message,
|
||||
"lastPaymentStatus": event.paymentStatus
|
||||
}
|
||||
}
|
||||
if client_reference_id: update_json["$set"]["clientPaymentReferenceId"] = client_reference_id
|
||||
|
||||
# Try to update the existing record:
|
||||
return await mongo_data_conn.update_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = {"clientPaymentReferenceId": client_reference_id},
|
||||
update = update_json,
|
||||
upsert = False,
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
async def update_tags(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
payment_id: ObjectId | str,
|
||||
unset_tags: List[str] = None,
|
||||
set_tags: List[str] = None
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Updates the tags on one payment. The tags to remove are processed first, the ones to add are processed later.
|
||||
:param mongo_data_conn: The instance of the database connector to use for the operation.
|
||||
:param payment_id: The id of the payment detail that needs to be read.
|
||||
:param unset_tags: The tags to remove from the payment record.
|
||||
:param set_tags: The tags to add to the payment record.
|
||||
:return: True if the update was successful, else False.
|
||||
"""
|
||||
|
||||
# Update the tags:
|
||||
return await mongo_data_conn.update_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = {"_id": ObjectId(payment_id)},
|
||||
update = [{
|
||||
"$set": {
|
||||
"tags": {
|
||||
"$let": {
|
||||
"vars": {
|
||||
"removed_tags": {
|
||||
"$setDifference": [
|
||||
"$tags",
|
||||
unset_tags
|
||||
]
|
||||
}
|
||||
},
|
||||
"in": {
|
||||
"$setUnion": [
|
||||
"$$removed_tags",
|
||||
set_tags
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}],
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
# ┳┓ ┓ ┏┓
|
||||
# ┃┃┏┓┃┏┓╋┏┓ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
# ┻┛┗ ┗┗ ┗┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┛
|
||||
|
||||
# No support whatsoever for deleting payment records!
|
||||
|
||||
# ┳┓ ┏┓
|
||||
# ┣┫┏┓┏┓┓┏┏┓┏╋ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
# ┛┗┗ ┗┫┗┻┗ ┛┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┗ ┛
|
||||
|
||||
async def init_payment(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
user_info: CoreUserInfoModel,
|
||||
payment_request: PGPaymentRequestData,
|
||||
tags: List[Any]
|
||||
) -> ObjectId | None:
|
||||
|
||||
"""
|
||||
Do this before you hit the third-party client's service when requesting payments. This creates a validated
|
||||
payment record in the database which can then be used as reference for successive updates.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param auth_token: The token that has to be used to fetch the data.
|
||||
:param user_info: The user of your platform, NOT THE PAYING PARTY.
|
||||
:param payment_request: The payment request that came in through the API call.
|
||||
:param tags: And initial tags to apply to this payment's records that you know you will need for filtering.
|
||||
:return: The id of the MongoDB document that will hold the full record of this payment.
|
||||
"""
|
||||
|
||||
# Model the payment's request. This ensures we're validating the inputs.
|
||||
payment_model = CorePaymentModel(
|
||||
user = user_info,
|
||||
customer = CustomerDetails(
|
||||
name = payment_request.customerName,
|
||||
contactNo = payment_request.customerNo,
|
||||
payerNo = payment_request.payerNo,
|
||||
email = payment_request.email
|
||||
),
|
||||
lastEventMessage = "Payment Request Queued",
|
||||
lastPaymentStatus = "queued",
|
||||
tokenId = auth_token.authTokenId,
|
||||
amount = payment_request.amount,
|
||||
currencyCode = payment_request.currencyCode,
|
||||
metadata = payment_request.metadata.model_dump(),
|
||||
tags = list(set(payment_request.tags + (tags or []))),
|
||||
serviceType = "paymentGateway",
|
||||
client = auth_token.client,
|
||||
clientPaymentReferenceId = None,
|
||||
events = []
|
||||
)
|
||||
|
||||
# Simply insert the document and return the id:
|
||||
return await mongo_data_conn.insert_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
document = payment_model.model_dump(),
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
@abstractmethod
|
||||
async def request_payment(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
user_info: CoreUserInfoModel,
|
||||
payment_request: PGPaymentRequestData,
|
||||
) -> PaymentRequestOneResult:
|
||||
|
||||
"""
|
||||
To request payment from someone through a payment gateway.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param auth_token: The token that has to be used to fetch the data.
|
||||
:param user_info: The info. of your user, so that you can identify who requested the payment.
|
||||
:param payment_request: The data that came in with the APi call.
|
||||
:return: The structured response form the payment gateway.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def handle_payment_callback(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
inbound_data: dict,
|
||||
inbound_headers: dict
|
||||
) -> None:
|
||||
|
||||
"""
|
||||
Whenever the payment gateway sends an update about a requested payment, we use this method to update our records
|
||||
as per the specification of the third-party payment gateway.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param inbound_data: The data sent by the payment gateway in their update.
|
||||
:param inbound_headers: The headers sent by the payment gateway in their update.
|
||||
:return: ??
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pass
|
||||
@@ -0,0 +1,356 @@
|
||||
"""
|
||||
|
||||
AUTHOR:
|
||||
|
||||
Khushal P Soonderji
|
||||
|
||||
DATE:
|
||||
|
||||
Saturday, 28th Dec., 2024
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To handle all interactions with Safaricom's M-Pesa Express payment gateway from one place.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
01. Official Documentation: https://developer.safaricom.co.ke/APIs/MpesaExpressSimulate
|
||||
|
||||
DOWNLOADS:
|
||||
|
||||
N/A
|
||||
|
||||
"""
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** IMPORT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# To make sibling directories accessible for imports:
|
||||
import sys
|
||||
sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# My async utils:
|
||||
from utils_v2.string import json
|
||||
from utils_v2.string import regex
|
||||
from utils_v2.database.async_mysql_v2 import AsyncMySQL
|
||||
from utils_v2.database.async_mongo_v2 import AsyncMongo
|
||||
from utils_v2.cache.async_redis_cache_v2 import AsyncRedisCache
|
||||
|
||||
# Controllers:
|
||||
from controllers_v2.finstitutions.payments.base import PaymentsController
|
||||
|
||||
# Models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.core.auth_token import CoreAuthTokenModel
|
||||
from models.core.payment import CorePaymentModel, PaymentEvent, CustomerDetails
|
||||
from models.api.finstitutions.payments.request import (
|
||||
PGPaymentRequestData,
|
||||
PaymentRequestOneResult,
|
||||
PaymentCallbackResult
|
||||
)
|
||||
|
||||
# Payment Client:
|
||||
from utils_v2.payments.safaricom.models.auth import MPesaExpressAuthorization
|
||||
from utils_v2.payments.safaricom.controllers.m_pesa_express import SafaricomMPesaExpress
|
||||
|
||||
# To work with datatypes:
|
||||
from typing import List, Any
|
||||
|
||||
# To make HTTP requests:
|
||||
import httpx
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MACROS / ONE-TIME INIT ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** VARIABLES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** FUNCTIONS ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
# --- Nothing Yet
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** CLASSES ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class SafaricomMPesaExpressPaymentsController(PaymentsController):
|
||||
|
||||
# ┏┓
|
||||
# ┃ ┏┓┏┓┏╋┏┓┓┏┏╋┏┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┛ ┗┻┗┗┗┛┛
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache: AsyncRedisCache = None,
|
||||
http_client: httpx.AsyncClient = None,
|
||||
alert_url: str = None,
|
||||
debug: bool = True,
|
||||
debug_prefix: str = "Sfrcm. M-Pesa Exp. (C) | ",
|
||||
debug_only_errors: bool = True
|
||||
):
|
||||
|
||||
"""
|
||||
This is the foundational controller for all trading services. Use this for any smaller common tasks where you
|
||||
may not know the exact client beforehand.
|
||||
:param cache: The object to use for caching results from database calls.
|
||||
:param http_client: The HTTP client
|
||||
:param debug: Whether, or not, you would like to print debugging messages:
|
||||
:param debug_prefix: The prefix to print with the debugging messages.
|
||||
:param debug_only_errors: Whether you would like to print only error messages or all messages.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
# Invoke the parent's constructor:
|
||||
super().__init__(
|
||||
cache = cache,
|
||||
alert_url = alert_url,
|
||||
http_client = http_client,
|
||||
base_filter = None,
|
||||
debug = debug,
|
||||
debug_prefix = debug_prefix,
|
||||
debug_only_errors = debug_only_errors
|
||||
)
|
||||
|
||||
# ┓┏ ┓
|
||||
# ┣┫┏┓┃┏┓┏┓┏┓┏
|
||||
# ┛┗┗ ┗┣┛┗ ┛ ┛
|
||||
# ┛
|
||||
|
||||
@staticmethod
|
||||
def clean_phone_no(value: str) -> str:
|
||||
|
||||
"""
|
||||
To clean-up input Kenyan phone nos.
|
||||
:param value: The phone no. to clean, provided as a string.
|
||||
:return: The cleaned phone no.
|
||||
"""
|
||||
|
||||
return regex.replace(
|
||||
text = value,
|
||||
pattern = r"[^0-9]",
|
||||
substitute_text = ""
|
||||
)
|
||||
|
||||
# ┳┓ ┏┓
|
||||
# ┣┫┏┓┏┓┓┏┏┓┏╋ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
# ┛┗┗ ┗┫┗┻┗ ┛┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┗ ┛
|
||||
|
||||
async def request_payment(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
user_info: CoreUserInfoModel,
|
||||
payment_request: PGPaymentRequestData
|
||||
) -> PaymentRequestOneResult:
|
||||
|
||||
"""
|
||||
To request payment from someone through a payment gateway.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param auth_token: The token that has to be used to fetch the data.
|
||||
:param user_info: The info. of your user, so that you can identify who requested the payment.
|
||||
:param payment_request: The data that came in with the APi call.
|
||||
:return: The structured response form the payment gateway.
|
||||
"""
|
||||
|
||||
# Start by assuming failure:
|
||||
result = PaymentRequestOneResult()
|
||||
|
||||
# Initialize the payment request by creating a placeholder record in the database:
|
||||
payment_id = await self.init_payment(
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
auth_token = auth_token,
|
||||
user_info = user_info,
|
||||
payment_request = payment_request,
|
||||
tags = ["Payment", "Safaricom", "M-Pesa Express", "Kenya"]
|
||||
)
|
||||
|
||||
# Initialize the third-party client:
|
||||
client = SafaricomMPesaExpress(
|
||||
auth = MPesaExpressAuthorization(
|
||||
consumerKey = auth_token.auth["consumerKey"],
|
||||
consumerSecret = auth_token.auth["consumerSecret"],
|
||||
businessShortCode = auth_token.auth["businessShortCode"],
|
||||
appPasskey = auth_token.auth["appPasskey"]
|
||||
),
|
||||
http_client = self._http_client
|
||||
)
|
||||
|
||||
# Make the payment request:
|
||||
client_response = await client.request_payment(
|
||||
amount = payment_request.amount,
|
||||
party_a = self.clean_phone_no(
|
||||
payment_request.customerNo
|
||||
) if isinstance(payment_request.customerNo, str) else payment_request.customerNo,
|
||||
type = "CustomerPayBillOnline",
|
||||
reference = str(payment_id),
|
||||
description = payment_request.description,
|
||||
callback_url = f"https://api.thecaoffice.com/finstitutions/payments/callback/safaricom/mpesaexpress",
|
||||
payer_no = self.clean_phone_no(
|
||||
payment_request.payerNo
|
||||
) if isinstance(payment_request.payerNo, str) else payment_request.payerNo,
|
||||
party_b = auth_token.auth["businessShortCode"]
|
||||
)
|
||||
|
||||
# Add this event to the payment's document:
|
||||
event_note_success = await self.add_event_by_payment_id(
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
payment_id = payment_id,
|
||||
event = PaymentEvent(
|
||||
paymentStatus = "initiated" if client_response.success else "initFailed",
|
||||
message = f"PG: {client_response.message}",
|
||||
initByPG = False,
|
||||
httpCode = client_response.httpCode,
|
||||
headers = await client_response.get_headers(),
|
||||
payload = await client_response.get_json()
|
||||
),
|
||||
client_reference_id = client_response.referenceId
|
||||
)
|
||||
|
||||
# Done here:
|
||||
result.success = client_response.success and event_note_success
|
||||
result.message = " ".join([
|
||||
"Payment requested successfully." if client_response.success
|
||||
else f"Payment request FAILED (PG: '{client_response.message}').",
|
||||
" " if event_note_success
|
||||
else "Event noting FAILED.",
|
||||
]).strip()
|
||||
return result
|
||||
|
||||
async def handle_payment_callback(
|
||||
self,
|
||||
mongo_data_conn: AsyncMongo,
|
||||
inbound_data: dict,
|
||||
inbound_headers: dict
|
||||
) -> PaymentCallbackResult:
|
||||
|
||||
"""
|
||||
Whenever the payment gateway sends an update about a requested payment, we use this method to update our records
|
||||
as per the specification of the third-party payment gateway.
|
||||
:param mongo_data_conn: The database connection to use to perform this activity.
|
||||
:param inbound_data: The data sent by the payment gateway in their update.
|
||||
:param inbound_headers: The headers sent by the payment gateway in their update.
|
||||
:return: A structured response about the process of updating the payment event.
|
||||
"""
|
||||
|
||||
# Start by assuming failure:
|
||||
result = PaymentCallbackResult()
|
||||
|
||||
# Map out the documented codes provided by the payment gateway.
|
||||
# URL: https://developer.safaricom.co.ke/APIs/MpesaExpressSimulate
|
||||
code_map = {
|
||||
0: {
|
||||
"status": "settled",
|
||||
"message": "Payment successful :)"
|
||||
}, # ... Success
|
||||
1037: {
|
||||
"status": "failed",
|
||||
"message": "The payment gateway could not reach your customer."
|
||||
}, # ... DS Timeout. User could not be reached.
|
||||
1025: {
|
||||
"status": "failed",
|
||||
"message": "There was a system error in the payment gateway (1025)."
|
||||
}, # ... System error while trying to send the push request.
|
||||
9999: {
|
||||
"status": "failed",
|
||||
"message": "There was a system error in the payment gateway (9999)."
|
||||
}, # ... System error while trying to send the push request.
|
||||
1032: {
|
||||
"status": "rejected",
|
||||
"message": "Your customer declined the payment request."
|
||||
}, # ... Request Cancelled by the user.
|
||||
1: {
|
||||
"status": "failed",
|
||||
"message": "Your customer has insufficient balance."
|
||||
}, # ... The user has insufficient balance.
|
||||
2001: {
|
||||
"status": "failed",
|
||||
"message": "The payment gateway says your credentials are invalid."
|
||||
}, # ... Invalid credentials of the initiator.
|
||||
1019: {
|
||||
"status": "failed",
|
||||
"message": "The transaction expired before your customer processed it."
|
||||
}, # ... Transaction expired.
|
||||
1001: {
|
||||
"status": "failed",
|
||||
"message": "Your customer is already in the middle of some transaction on the payment gateway."
|
||||
}, # ... The payer is already making some transaction.
|
||||
}
|
||||
|
||||
# Figure out which of the above codes is relevant to you:
|
||||
pg_reference_id = inbound_data["Body"]["stkCallback"]["CheckoutRequestID"]
|
||||
pg_result_code = int(inbound_data["Body"]["stkCallback"]["ResultCode"])
|
||||
pg_result_desc = inbound_data["Body"]["stkCallback"]["ResultDesc"]
|
||||
relevant_code = code_map.get(
|
||||
pg_result_code,
|
||||
{
|
||||
"status": "unknown",
|
||||
"message": f"Unknown code '{pg_result_code}' from the payment gateway. PG: '{pg_result_desc}'"
|
||||
}
|
||||
)
|
||||
|
||||
# For now, we just insert the event into the record:
|
||||
event_note_success = await self.add_event_by_client_reference_id(
|
||||
mongo_data_conn = mongo_data_conn,
|
||||
event = PaymentEvent(
|
||||
paymentStatus = relevant_code["status"],
|
||||
message = relevant_code["message"],
|
||||
initByPG = True,
|
||||
ipAddr = inbound_headers["Remote-IP"],
|
||||
httpCode = None,
|
||||
headers = inbound_headers,
|
||||
payload = inbound_data
|
||||
),
|
||||
client_reference_id = pg_reference_id
|
||||
)
|
||||
|
||||
# Done here:
|
||||
if event_note_success:
|
||||
result.success = True
|
||||
result.message = f"Payment event noted."
|
||||
else:
|
||||
result.success = False
|
||||
result.message = f"Payment event NOT noted."
|
||||
return result
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
# *** MAIN PROGRAM ***
|
||||
# ***** ****
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pass
|
||||
Reference in New Issue
Block a user