(20241216) Payment auth bug fix.
This commit is contained in:
+16
-1
@@ -36,7 +36,7 @@ sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# For making data behaviour_models:
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime, model_validator
|
||||
from typing import Optional, Literal, Union
|
||||
|
||||
# My utils:
|
||||
@@ -132,6 +132,21 @@ class ChatAuthRequestData(BaseModel):
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
|
||||
@model_validator(mode = "after")
|
||||
def ensure_harmony(cls, values):
|
||||
client = values.client
|
||||
auth = values.auth
|
||||
harmony_map = {
|
||||
"telegram": TelegramAuth
|
||||
}
|
||||
if not isinstance(auth, harmony_map[client]):
|
||||
raise ValueError(f"incorrect 'auth' for selected client '{client}'")
|
||||
return values
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
|
||||
@@ -36,7 +36,7 @@ sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# For making data behaviour_models:
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime, model_validator
|
||||
from typing import Optional, Literal, Union
|
||||
|
||||
# My utils:
|
||||
@@ -146,6 +146,21 @@ class PGAuthRequestData(BaseModel):
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
|
||||
@model_validator(mode = "after")
|
||||
def ensure_harmony(cls, values):
|
||||
client = values.client
|
||||
auth = values.auth
|
||||
harmony_map = {
|
||||
"safaricomMPesaExpress": SafaricomMPesaExpressAuth
|
||||
}
|
||||
if not isinstance(auth, harmony_map[client]):
|
||||
raise ValueError(f"incorrect 'auth' for selected client '{client}'")
|
||||
return values
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
DATE:
|
||||
|
||||
Friday, 13th Dec., 2024.
|
||||
Monday, 16th Dec., 2024.
|
||||
|
||||
OBJECTIVE:
|
||||
|
||||
To provide a structure to receive auth details of various software.
|
||||
To provide a structure to receive payment request details.
|
||||
|
||||
REFERENCES:
|
||||
|
||||
@@ -43,9 +43,18 @@ from typing import Optional, Literal, Union
|
||||
from utils_v2.string import regex
|
||||
from utils_v2.date_time import date_time
|
||||
|
||||
# Models:
|
||||
from models.core.payment import CorePaymentModel
|
||||
|
||||
# To work with date and time:
|
||||
import datetime
|
||||
|
||||
# To work with MongoDB:
|
||||
from bson.objectid import ObjectId
|
||||
|
||||
# To work with currencies:
|
||||
import pycountry
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
@@ -75,41 +84,7 @@ REGEX_SESSION_TOKEN = r"^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class SafaricomMPesaExpressAuth(BaseModel):
|
||||
|
||||
consumerKey: str = Field(
|
||||
description = "the app's consumer key given by safaricom; found in 'my apps'",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
consumerSecret: str = Field(
|
||||
description = "the app's consumer secret given by safaricom; found in 'my apps'",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
businessShortCode: str = Field(
|
||||
description = "your app's business short code; found in 'my apps'",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
appPasskey: str = Field(
|
||||
description = "your app's passkey; taken from human representative",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
# ┏┓ ┏•
|
||||
# ┃ ┏┓┏┓╋┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PGAuthRequestHeaders(BaseModel):
|
||||
class PGPaymentRequestHeaders(BaseModel):
|
||||
|
||||
sessionToken: str = Field(
|
||||
description = "the session token of the user who is requesting the service",
|
||||
@@ -133,10 +108,112 @@ class PGAuthRequestHeaders(BaseModel):
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PGAuthRequestData(BaseModel):
|
||||
class PGPaymentRequestData(BaseModel):
|
||||
|
||||
client: Literal["safaricomMPesaExpress"] = Field(alias = "client")
|
||||
auth: Union[SafaricomMPesaExpressAuth]
|
||||
# {
|
||||
# "customerMobileNumber": "",
|
||||
# "tokenId": "",
|
||||
# "description": "",
|
||||
# "payerNumber": "",
|
||||
# "amount": "",
|
||||
# "currency": "",
|
||||
# "emailAddress": "",
|
||||
# "reference": "",
|
||||
# }
|
||||
|
||||
tokenKey: ObjectId = Field(
|
||||
description = "the auth token to use to send this message",
|
||||
frozen = True,
|
||||
)
|
||||
|
||||
customerName: str | None = Field(
|
||||
description = "the name of the registered customer who must make the payment",
|
||||
frozen = True,
|
||||
default = None
|
||||
)
|
||||
|
||||
customerNo: str = Field(
|
||||
description = "the contact no. of the registered customer who must make the payment",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
payerNo: str | None = Field(
|
||||
description = (
|
||||
"the phone no. to which the payment request will go;"
|
||||
"if not specified, the value of 'customerNo' should be used"
|
||||
),
|
||||
frozen = True,
|
||||
default = None
|
||||
)
|
||||
|
||||
email: str | None = Field(
|
||||
description = "the e-mail id of the registered customer",
|
||||
pattern = regex.REGEX_EMAIL_ID,
|
||||
frozen = True,
|
||||
default = None
|
||||
)
|
||||
|
||||
amount: float | int = Field(
|
||||
description = "the amount of money to be requested",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
currencyCode: str = Field(
|
||||
description = "the three-letter iso 4217 code to identify the currency",
|
||||
frozen = True,
|
||||
examples = ["INR", "USD", "KES"]
|
||||
)
|
||||
|
||||
metadata: dict = Field(
|
||||
description = "any extra information about this payment",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
# ┏┓ ┏•
|
||||
# ┃ ┏┓┏┓╋┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
|
||||
@field_validator("tokenKey", mode = "before")
|
||||
def parse_oid(cls, value):
|
||||
try: value = ObjectId(value)
|
||||
except: pass
|
||||
return value
|
||||
|
||||
@field_validator("currencyCode", mode = "before")
|
||||
def validate_currency(cls, value):
|
||||
currency = pycountry.currencies.get(alpha_3 = value)
|
||||
if currency is None: raise ValueError("invalid currency code, please use iso 4217 standard")
|
||||
return value
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PaymentRequestOneResult(BaseModel):
|
||||
|
||||
success: bool = Field(
|
||||
description = "whether, or not, the sms was successfully sent",
|
||||
default = False
|
||||
)
|
||||
|
||||
message: str | None = Field(
|
||||
description = "a brief message to summarize the result of the process",
|
||||
default = None
|
||||
)
|
||||
|
||||
paymentDetails: CorePaymentModel = Field(
|
||||
description = "the actual data of the payment",
|
||||
default = None
|
||||
)
|
||||
|
||||
# ┏┓ ┏•
|
||||
# ┃ ┏┓┏┓╋┓┏┓
|
||||
|
||||
+17
-1
@@ -36,7 +36,7 @@ sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# For making data behaviour_models:
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime, model_validator
|
||||
from typing import Optional, Literal, Union
|
||||
|
||||
# My utils:
|
||||
@@ -183,6 +183,22 @@ class SMSAuthRequestData(BaseModel):
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
|
||||
@model_validator(mode = "after")
|
||||
def ensure_harmony(cls, values):
|
||||
client = values.smsClient
|
||||
auth = values.auth
|
||||
harmony_map = {
|
||||
"nimbusSmsIndia": NimbusSMSIndiaAuth,
|
||||
"savvyBulkSmsKenya": SavvyBulkSMSKenyaAuth
|
||||
}
|
||||
if not isinstance(auth, harmony_map[client]):
|
||||
raise ValueError(f"incorrect 'auth' for selected client '{client}'")
|
||||
return values
|
||||
|
||||
|
||||
# *****************************************************************************************************************
|
||||
# ***** ****
|
||||
|
||||
@@ -45,7 +45,7 @@ from utils_v2.date_time import date_time
|
||||
|
||||
# Data models:
|
||||
from models.core.message import CoreMessageModel
|
||||
from utils_v2.sms.models.data.sms_message import SentSMSMessageModel
|
||||
from utils_v2.sms.models.sms_message import SentSMSMessageModel
|
||||
|
||||
# To work with date and time:
|
||||
import datetime
|
||||
|
||||
+163
-19
@@ -36,13 +36,16 @@ sys.path.append(".")
|
||||
sys.path.append("..")
|
||||
|
||||
# For making data behaviour_models:
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime, AwareDatetime
|
||||
from pydantic import BaseModel, Field, field_validator, PastDatetime, AwareDatetime, model_validator
|
||||
from typing import Optional, Literal, Union, List, Any
|
||||
|
||||
# My utils:
|
||||
from utils_v2.string import regex
|
||||
from utils_v2.date_time import date_time
|
||||
|
||||
# Other core models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
|
||||
# To work with MongoDB:
|
||||
from bson.objectid import ObjectId
|
||||
|
||||
@@ -80,6 +83,57 @@ import pycountry
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class CustomerDetails(BaseModel):
|
||||
|
||||
name: str | None = Field(
|
||||
description = "the name of the registered customer who must make the payment",
|
||||
frozen = True,
|
||||
default = None
|
||||
)
|
||||
|
||||
contactNo: str = Field(
|
||||
description = "the contact no. of the registered customer who must make the payment",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
payerNo: str | None = Field(
|
||||
description = (
|
||||
"the phone no. to which the payment request will go;"
|
||||
"if not specified, the value of 'contactNo' will be used"
|
||||
),
|
||||
frozen = False,
|
||||
default = None
|
||||
)
|
||||
|
||||
email: str | None = Field(
|
||||
description = "the e-mail id of the registered customer",
|
||||
pattern = regex.REGEX_EMAIL_ID,
|
||||
frozen = True,
|
||||
default = None
|
||||
)
|
||||
|
||||
# ┏┓ ┏•
|
||||
# ┃ ┏┓┏┓╋┓┏┓
|
||||
# ┗┛┗┛┛┗┛┗┗┫
|
||||
# ┛
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
|
||||
@model_validator(mode = "after")
|
||||
def validate_model(cls, values):
|
||||
if values.payerNo is None: values.payerNo = values.contactNo
|
||||
return values
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PaymentEvent(BaseModel):
|
||||
|
||||
eventTs: AwareDatetime = Field(
|
||||
@@ -87,6 +141,19 @@ class PaymentEvent(BaseModel):
|
||||
frozen = True
|
||||
)
|
||||
|
||||
paymentStatus: Literal[
|
||||
"initFailed", # ... When we tried to initiate the request, but the payment gateway (PG) rejected it.
|
||||
"initiated", # .... When we made a successful payment request, or the customer initiated one from the PG.
|
||||
"failed", # ....... When the customer tried paying, but it failed (e.g.: because of an incorrect pin).
|
||||
"rejected", # ..... When the customer explicitly rejected the payment.
|
||||
"authorized", # ... When the customer made the payment (but it hasn't been settled in your account yet).
|
||||
"settled", # ...... When the PG sends the money to your account.
|
||||
"refunded", # ..... When the money was refunded to the client.
|
||||
] = Field(
|
||||
description = "the status of the payment request to see what stage of the process we are in",
|
||||
frozen = False
|
||||
)
|
||||
|
||||
initByPG: bool = Field(
|
||||
description = "to figure out whether the payment gateway initiated this event or we did",
|
||||
frozen = True
|
||||
@@ -98,6 +165,10 @@ class PaymentEvent(BaseModel):
|
||||
examples = [200, 400, 401]
|
||||
)
|
||||
|
||||
headers: dict = Field(
|
||||
description = "the headers that came in with the event; useful when trying to decode who generated the event"
|
||||
)
|
||||
|
||||
payload: dict = Field(
|
||||
description = "the json payload or set of query params received from an event from the payment gateway",
|
||||
frozen = True
|
||||
@@ -133,35 +204,44 @@ class CorePaymentModel(BaseModel):
|
||||
alias = "_id"
|
||||
)
|
||||
|
||||
paymentStatus: Literal[
|
||||
"initFailed", # ... When we tried to initiate the request, but the payment gateway (PG) rejected it.
|
||||
"initiated", # .... When we made a successful payment request, or the customer initiated one from the PG.
|
||||
"failed", # ....... When the customer tried paying, but it failed (e.g.: because of an incorrect pin).
|
||||
"rejected", # ..... When the customer explicitly rejected the payment.
|
||||
"authorized", # ... When the customer made the payment (but it hasn't been settled in your account yet).
|
||||
"settled", # ...... When the PG sends the money to your account.
|
||||
"refunded", # ..... When the money was refunded to the client.
|
||||
] = Field(
|
||||
description = "the status of the payment request to see what stage of the process we are in",
|
||||
frozen = False
|
||||
user: CoreUserInfoModel = Field(
|
||||
description = "how you identify your user",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
customer: CustomerDetails = Field(
|
||||
description = "how you identify your user's customer",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
ts: AwareDatetime = Field(
|
||||
description = "the time (utc) at which the payment was first initiated",
|
||||
frozen = True,
|
||||
default_factory = lambda: date_time.get_current_utc_date_time(as_string = False)
|
||||
)
|
||||
|
||||
lastEventTs: AwareDatetime = Field(
|
||||
description = "the time (utc) at which the latest payment event occurred",
|
||||
description = "the time (utc) at which the last event occurred",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
lastPaymentStatus: str = Field(
|
||||
description = "the status of the payment request to see what stage of the process we are in",
|
||||
frozen = False
|
||||
)
|
||||
|
||||
tokenId: ObjectId = Field(
|
||||
description = "the id of the auth token that is associated with this payment",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
amount: float | int = Field(
|
||||
description = "the amount of money being requested"
|
||||
description = "the amount of money being requested",
|
||||
frozen = True
|
||||
)
|
||||
|
||||
currencyCode: str = Field(
|
||||
description = "the three-letter ISO 4217 code to identify the currency",
|
||||
description = "the three-letter iso 4217 code to identify the currency",
|
||||
frozen = True,
|
||||
examples = ["INR", "USD", "KES"]
|
||||
)
|
||||
@@ -206,6 +286,51 @@ class CorePaymentModel(BaseModel):
|
||||
def model_dump(self, *args, **kwargs):
|
||||
return super().model_dump(*args, by_alias = True, **kwargs)
|
||||
|
||||
# ┏┓ •
|
||||
# ┃┃┏┓┏┓┏┓┏┓┏┓╋┓┏┓┏
|
||||
# ┣┛┛ ┗┛┣┛┗ ┛ ┗┗┗ ┛
|
||||
# ┛
|
||||
|
||||
@property
|
||||
def full(self):
|
||||
payment_json = {
|
||||
"paymentId": str(self.messageId),
|
||||
"user": self.user,
|
||||
"ts": self.ts.isoformat(),
|
||||
"lastEventTs": self.lastEventTs,
|
||||
"lastPaymentStatus": self.lastPaymentStatus,
|
||||
"amount": self.amount,
|
||||
"currencyCode": self.currencyCode,
|
||||
"client": self.client,
|
||||
"clientPaymentReferenceId": self.clientPaymentReferenceId,
|
||||
"tags": self.tags,
|
||||
"metadata": self.metadata,
|
||||
"events": []
|
||||
}
|
||||
for e in self.events:
|
||||
payment_json["events"].append({
|
||||
"eventTs": e.eventTs,
|
||||
"paymentStatus": e.paymentStatus,
|
||||
"initByPG": e.initByPG
|
||||
})
|
||||
return payment_json
|
||||
|
||||
@property
|
||||
def preview(self):
|
||||
return {
|
||||
"paymentId": str(self.messageId),
|
||||
"user": self.user,
|
||||
"ts": self.ts.isoformat(),
|
||||
"lastEventTs": self.lastEventTs,
|
||||
"lastPaymentStatus": self.lastPaymentStatus,
|
||||
"amount": self.amount,
|
||||
"currencyCode": self.currencyCode,
|
||||
"client": self.client,
|
||||
"clientPaymentReferenceId": self.clientPaymentReferenceId,
|
||||
"tags": self.tags,
|
||||
"metadata": self.metadata
|
||||
}
|
||||
|
||||
# ┓┏ ┓• ┓ •
|
||||
# ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
|
||||
# ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗
|
||||
@@ -248,22 +373,37 @@ if __name__ == "__main__":
|
||||
now = date_time.get_current_utc_date_time(as_string = False)
|
||||
|
||||
payment = CorePaymentModel(
|
||||
paymentStatus = "authorized",
|
||||
tokenId = "67519cf3a7804fcbc6f12452",
|
||||
user = CoreUserInfoModel(
|
||||
userId = 1
|
||||
),
|
||||
customer = CustomerDetails(
|
||||
name = "Bhopli Narangi",
|
||||
contactNo = "9876543210",
|
||||
email = "bhopli@orange.com"
|
||||
),
|
||||
amount = 1.00,
|
||||
currencyCode = "INR",
|
||||
metadata = {
|
||||
"userId": 1,
|
||||
"name": "Bhopli"
|
||||
"key": "value"
|
||||
},
|
||||
tags = [
|
||||
"some",
|
||||
"tags"
|
||||
],
|
||||
client = "razorpay",
|
||||
clientPaymentReferenceId = "txn_123_abc",
|
||||
lastPaymentStatus = "settled",
|
||||
lastEventTs = now,
|
||||
events = [
|
||||
PaymentEvent(
|
||||
eventTs = now - datetime.timedelta(minutes = 1, seconds = 12),
|
||||
initByPG = True,
|
||||
paymentStatus = "initiated",
|
||||
initByPG = False,
|
||||
httpCode = None,
|
||||
headers = {
|
||||
"some": "header"
|
||||
},
|
||||
payload = {
|
||||
"status": "captured",
|
||||
"from": "Barfi",
|
||||
@@ -271,8 +411,12 @@ if __name__ == "__main__":
|
||||
),
|
||||
PaymentEvent(
|
||||
eventTs = now,
|
||||
paymentStatus = "settled",
|
||||
initByPG = True,
|
||||
httpCode = None,
|
||||
headers = {
|
||||
"some": "header"
|
||||
},
|
||||
payload = {
|
||||
"status": "authorized",
|
||||
"from": "Barfi",
|
||||
|
||||
Reference in New Issue
Block a user