cleaned up code
This commit is contained in:
@@ -20,20 +20,48 @@ ApplicationConfig = load_config()
|
||||
# Set Authorize.net environment based on configuration
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
constants.environment = constants.PRODUCTION
|
||||
print("Payment Service Production")
|
||||
VALIDATION_MODE = "liveMode"
|
||||
API_LOGIN_ID = '4d2Mn6H23R'
|
||||
TRANSACTION_KEY = '7B94d8xfTQXv37WS'
|
||||
API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID
|
||||
TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY
|
||||
else:
|
||||
constants.environment = constants.SANDBOX
|
||||
VALIDATION_MODE = "testMode"
|
||||
print("Payment Service Sandbox")
|
||||
API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID
|
||||
TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY
|
||||
|
||||
constants.show_url_on_request = True # Very useful for debugging
|
||||
|
||||
def _is_e00121_response(response):
|
||||
"""
|
||||
Check if the Authorize.Net response contains E00121 error (invalid payment profile ID).
|
||||
"""
|
||||
if response is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
if hasattr(response, 'messages') and response.messages is not None:
|
||||
# Check for E00121 in different response message structures
|
||||
if hasattr(response.messages, 'message'):
|
||||
message = response.messages.message
|
||||
|
||||
# Handle list of messages
|
||||
if isinstance(message, list):
|
||||
for msg in message:
|
||||
if getattr(msg, 'code', '') == 'E00121':
|
||||
print("E00121 detected in message list")
|
||||
return True
|
||||
# Handle single message
|
||||
elif hasattr(message, 'code'):
|
||||
if message.code == 'E00121':
|
||||
print(f"E00121 detected: '{getattr(message, 'text', 'No details')}'")
|
||||
return True
|
||||
else:
|
||||
print(f"Message code: '{message.code}' (not E00121)")
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Error checking for E00121: {str(e)}")
|
||||
return False
|
||||
|
||||
def _get_authnet_error_message(response):
|
||||
"""
|
||||
@@ -67,24 +95,11 @@ def create_customer_profile(customer: schemas.Customer, card_info: schemas.CardC
|
||||
This version sanitizes and trims customer data before sending.
|
||||
"""
|
||||
print(f"Attempting to create Auth.Net profile for customer ID: {customer.id}")
|
||||
print("dogpoop")
|
||||
print(ApplicationConfig.API_LOGIN_ID)
|
||||
print(ApplicationConfig.TRANSACTION_KEY)
|
||||
|
||||
try:
|
||||
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print("here1234")
|
||||
# --- DATA SANITIZATION LOGIC ---
|
||||
def sanitize(text, max_len, allow_spaces=False, is_zip=False):
|
||||
if not text:
|
||||
return ""
|
||||
if is_zip:
|
||||
pattern = r'[^a-zA-Z0-9-]'
|
||||
else:
|
||||
pattern = r'[^a-zA-Z0-9]' if not allow_spaces else r'[^a-zA-Z0-9\s]'
|
||||
sanitized = re.sub(pattern, '', str(text))
|
||||
return sanitized.strip()[:max_len]
|
||||
|
||||
# API max lengths: email=255
|
||||
email = (customer.customer_email or f"no-email-{customer.id}@example.com")[:255]
|
||||
@@ -102,30 +117,21 @@ def create_customer_profile(customer: schemas.Customer, card_info: schemas.CardC
|
||||
|
||||
controller = createCustomerProfileController(request)
|
||||
|
||||
try:
|
||||
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
|
||||
response = controller.getresponse()
|
||||
print("************")
|
||||
print(response)
|
||||
print(response.messages)
|
||||
print(response.messages.resultCode)
|
||||
print("************")
|
||||
except Exception as e:
|
||||
print("^^^")
|
||||
print(response)
|
||||
print(response.messages)
|
||||
print(response.messages.resultCode)
|
||||
print("^^^")
|
||||
print(f"API execution failed: {traceback.format_exc()}")
|
||||
raise ValueError("API call execution error")
|
||||
else:
|
||||
controller.execute()
|
||||
response = controller.getresponse()
|
||||
|
||||
|
||||
try:
|
||||
if response.messages.resultCode == "Ok":
|
||||
profile_id = response.customerProfileId
|
||||
print(profile_id)
|
||||
# Payment profile ID is not available since profiles are added separately
|
||||
payment_id = ""
|
||||
# # Payment profile ID is not available since profiles are added separately
|
||||
# payment_id = ""
|
||||
print(f"SUCCESS: Created customer profile: {profile_id} (payment profiles added separately)")
|
||||
|
||||
# Add detailed logging
|
||||
@@ -149,102 +155,6 @@ def create_customer_profile(customer: schemas.Customer, card_info: schemas.CardC
|
||||
|
||||
|
||||
|
||||
def add_payment_profile_to_customer(customer_profile_id: str, customer: schemas.Customer, card_info: schemas.CardCreate, is_default: bool = False):
|
||||
print(f"Adding {'default ' if is_default else ''}payment profile to Auth.Net customer profile ID: {customer_profile_id}")
|
||||
|
||||
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)
|
||||
|
||||
def sanitize(text, max_len, allow_spaces=False, is_zip=False):
|
||||
if not text:
|
||||
return ""
|
||||
if is_zip:
|
||||
pattern = r'[^a-zA-Z0-9-]'
|
||||
else:
|
||||
pattern = r'[^a-zA-Z0-9]' if not allow_spaces else r'[^a-zA-Z0-9\s]'
|
||||
sanitized = re.sub(pattern, '', str(text))
|
||||
return sanitized.strip()[:max_len]
|
||||
|
||||
first_name = sanitize(customer.customer_first_name, 50) or "N/A"
|
||||
last_name = sanitize(customer.customer_last_name, 50) or "N/A"
|
||||
address = sanitize(customer.customer_address, 60, allow_spaces=True) or "N/A"
|
||||
city = sanitize(customer.customer_town, 40) or "N/A"
|
||||
|
||||
# ========= CHANGE 1.B: ADD STATE HERE =========
|
||||
state = sanitize(customer.customer_state, 40) or "MA" # Defaulting to MA for safety
|
||||
|
||||
zip_code = sanitize(customer.customer_zip, 20, is_zip=True)
|
||||
|
||||
# Fix expiration date format for cards
|
||||
try:
|
||||
expiration_year = int(card_info.expiration_date.split('-')[0])
|
||||
expiration_month = int(card_info.expiration_date.split('-')[1])
|
||||
expiration_date = f"{expiration_month:02d}{expiration_year % 100:02d}"
|
||||
except (ValueError, IndexError):
|
||||
sanitized_exp = card_info.expiration_date.replace('/', '').replace('-', '')
|
||||
if len(sanitized_exp) == 4:
|
||||
expiration_date = sanitized_exp
|
||||
else:
|
||||
expiration_date = "0325"
|
||||
|
||||
print(f"Parsed expiration date for card: {card_info.expiration_date} -> {expiration_date}")
|
||||
|
||||
creditCard = apicontractsv1.creditCardType(
|
||||
cardNumber=card_info.card_number,
|
||||
expirationDate=expiration_date,
|
||||
cardCode=card_info.cvv
|
||||
)
|
||||
|
||||
billTo = apicontractsv1.customerAddressType(
|
||||
firstName=first_name,
|
||||
lastName=last_name,
|
||||
address=address,
|
||||
city=city,
|
||||
state=state,
|
||||
zip=zip_code,
|
||||
country="USA"
|
||||
)
|
||||
|
||||
paymentProfile = apicontractsv1.customerPaymentProfileType(
|
||||
billTo=billTo,
|
||||
payment=apicontractsv1.paymentType(creditCard=creditCard),
|
||||
defaultPaymentProfile=is_default
|
||||
)
|
||||
|
||||
request = apicontractsv1.createCustomerPaymentProfileRequest(
|
||||
merchantAuthentication=merchantAuth,
|
||||
customerProfileId=customer_profile_id,
|
||||
paymentProfile=paymentProfile,
|
||||
# ========= CHANGE 2.B: USE liveMode =========
|
||||
validationMode=VALIDATION_MODE
|
||||
)
|
||||
|
||||
controller = createCustomerPaymentProfileController(request)
|
||||
|
||||
try:
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
response = controller.getresponse()
|
||||
if response.messages.resultCode == "Ok":
|
||||
# Fix: Proper payment profile ID extraction (same bug fix as above)
|
||||
if hasattr(response, 'customerPaymentProfileId') and response.customerPaymentProfileId:
|
||||
return str(response.customerPaymentProfileId)
|
||||
else:
|
||||
print("WARNING: Added payment profile but no ID returned")
|
||||
raise ValueError("Payment profile created but ID not found in response")
|
||||
else:
|
||||
error_msg = _get_authnet_error_message(response)
|
||||
print(f"Failed to add payment profile: {error_msg}")
|
||||
print(f"SANITIZED DATA SENT FOR ADD PROFILE: FirstName='{first_name}', LastName='{last_name}', Address='{address}', City='{city}', State='{state}', Zip='{zip_code}'")
|
||||
|
||||
print(f"Card info: number='{card_info.card_number}', exp='{card_info.expiration_date}', cvv='{card_info.cvv}'") # Mask if sensitive
|
||||
print(pprint.pformat(vars(billTo)))
|
||||
print(pprint.pformat(vars(request)))
|
||||
|
||||
raise ValueError(error_msg)
|
||||
except Exception as e:
|
||||
print(f"A critical exception occurred during the API call: {traceback.format_exc()}")
|
||||
raise ValueError("Could not connect to the payment gateway.")
|
||||
|
||||
def authorize_customer_profile(customer_profile_id: str, payment_profile_id: str, transaction_req: schemas.TransactionAuthorizeByCardID, db_session=None, customer_id=None, card_id=None):
|
||||
"""
|
||||
Creates an AUTH_ONLY transaction against a customer profile with automatic E00121 recovery.
|
||||
@@ -331,8 +241,13 @@ def _perform_authorization(customer_profile_id: str, payment_profile_id: str, tr
|
||||
)
|
||||
|
||||
controller = createTransactionController(createtransactionrequest)
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
else:
|
||||
controller.execute()
|
||||
|
||||
response = controller.getresponse()
|
||||
|
||||
# Log response details
|
||||
@@ -345,37 +260,7 @@ def _perform_authorization(customer_profile_id: str, payment_profile_id: str, tr
|
||||
return response
|
||||
|
||||
|
||||
def _is_e00121_response(response):
|
||||
"""
|
||||
Check if the Authorize.Net response contains E00121 error (invalid payment profile ID).
|
||||
"""
|
||||
if response is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
if hasattr(response, 'messages') and response.messages is not None:
|
||||
# Check for E00121 in different response message structures
|
||||
if hasattr(response.messages, 'message'):
|
||||
message = response.messages.message
|
||||
|
||||
# Handle list of messages
|
||||
if isinstance(message, list):
|
||||
for msg in message:
|
||||
if getattr(msg, 'code', '') == 'E00121':
|
||||
print("E00121 detected in message list")
|
||||
return True
|
||||
# Handle single message
|
||||
elif hasattr(message, 'code'):
|
||||
if message.code == 'E00121':
|
||||
print(f"E00121 detected: '{getattr(message, 'text', 'No details')}'")
|
||||
return True
|
||||
else:
|
||||
print(f"Message code: '{message.code}' (not E00121)")
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Error checking for E00121: {str(e)}")
|
||||
return False
|
||||
|
||||
|
||||
def capture_authorized_transaction(transaction_req: schemas.TransactionCapture):
|
||||
@@ -396,11 +281,115 @@ def capture_authorized_transaction(transaction_req: schemas.TransactionCapture):
|
||||
)
|
||||
|
||||
controller = createTransactionController(createtransactionrequest)
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
else:
|
||||
controller.execute()
|
||||
|
||||
return controller.getresponse()
|
||||
|
||||
|
||||
def add_payment_profile_to_customer(customer_profile_id: str, customer: schemas.Customer, card_info: schemas.CardCreate, is_default: bool = False):
|
||||
print(f"Adding {'default ' if is_default else ''}payment profile to Auth.Net customer profile ID: {customer_profile_id}")
|
||||
|
||||
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)
|
||||
|
||||
def sanitize(text, max_len, allow_spaces=False, is_zip=False):
|
||||
if not text:
|
||||
return ""
|
||||
if is_zip:
|
||||
pattern = r'[^a-zA-Z0-9-]'
|
||||
else:
|
||||
pattern = r'[^a-zA-Z0-9]' if not allow_spaces else r'[^a-zA-Z0-9\s]'
|
||||
sanitized = re.sub(pattern, '', str(text))
|
||||
return sanitized.strip()[:max_len]
|
||||
|
||||
first_name = sanitize(customer.customer_first_name, 50) or "N/A"
|
||||
last_name = sanitize(customer.customer_last_name, 50) or "N/A"
|
||||
address = sanitize(customer.customer_address, 60, allow_spaces=True) or "N/A"
|
||||
city = sanitize(customer.customer_town, 40) or "N/A"
|
||||
|
||||
# ========= CHANGE 1.B: ADD STATE HERE =========
|
||||
state = sanitize(customer.customer_state, 40) or "MA" # Defaulting to MA for safety
|
||||
|
||||
zip_code = sanitize(customer.customer_zip, 20, is_zip=True)
|
||||
|
||||
# Fix expiration date format for cards
|
||||
try:
|
||||
expiration_year = int(card_info.expiration_date.split('-')[0])
|
||||
expiration_month = int(card_info.expiration_date.split('-')[1])
|
||||
expiration_date = f"{expiration_month:02d}{expiration_year % 100:02d}"
|
||||
except (ValueError, IndexError):
|
||||
sanitized_exp = card_info.expiration_date.replace('/', '').replace('-', '')
|
||||
if len(sanitized_exp) == 4:
|
||||
expiration_date = sanitized_exp
|
||||
else:
|
||||
expiration_date = "0325"
|
||||
|
||||
print(f"Parsed expiration date for card: {card_info.expiration_date} -> {expiration_date}")
|
||||
|
||||
creditCard = apicontractsv1.creditCardType(
|
||||
cardNumber=card_info.card_number,
|
||||
expirationDate=expiration_date,
|
||||
cardCode=card_info.cvv
|
||||
)
|
||||
|
||||
billTo = apicontractsv1.customerAddressType(
|
||||
firstName=first_name,
|
||||
lastName=last_name,
|
||||
address=address,
|
||||
city=city,
|
||||
state=state,
|
||||
zip=zip_code,
|
||||
country="USA"
|
||||
)
|
||||
|
||||
paymentProfile = apicontractsv1.customerPaymentProfileType(
|
||||
billTo=billTo,
|
||||
payment=apicontractsv1.paymentType(creditCard=creditCard),
|
||||
defaultPaymentProfile=is_default
|
||||
)
|
||||
|
||||
request = apicontractsv1.createCustomerPaymentProfileRequest(
|
||||
merchantAuthentication=merchantAuth,
|
||||
customerProfileId=customer_profile_id,
|
||||
paymentProfile=paymentProfile,
|
||||
# ========= CHANGE 2.B: USE liveMode =========
|
||||
validationMode=VALIDATION_MODE
|
||||
)
|
||||
|
||||
controller = createCustomerPaymentProfileController(request)
|
||||
|
||||
try:
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
else:
|
||||
controller.execute()
|
||||
|
||||
response = controller.getresponse()
|
||||
if response.messages.resultCode == "Ok":
|
||||
# Fix: Proper payment profile ID extraction (same bug fix as above)
|
||||
if hasattr(response, 'customerPaymentProfileId') and response.customerPaymentProfileId:
|
||||
return str(response.customerPaymentProfileId)
|
||||
else:
|
||||
print("WARNING: Added payment profile but no ID returned")
|
||||
raise ValueError("Payment profile created but ID not found in response")
|
||||
else:
|
||||
error_msg = _get_authnet_error_message(response)
|
||||
print(f"Failed to add payment profile: {error_msg}")
|
||||
print(f"SANITIZED DATA SENT FOR ADD PROFILE: FirstName='{first_name}', LastName='{last_name}', Address='{address}', City='{city}', State='{state}', Zip='{zip_code}'")
|
||||
|
||||
print(f"Card info: number='{card_info.card_number}', exp='{card_info.expiration_date}', cvv='{card_info.cvv}'") # Mask if sensitive
|
||||
print(pprint.pformat(vars(billTo)))
|
||||
print(pprint.pformat(vars(request)))
|
||||
|
||||
raise ValueError(error_msg)
|
||||
except Exception as e:
|
||||
print(f"A critical exception occurred during the API call: {traceback.format_exc()}")
|
||||
raise ValueError("Could not connect to the payment gateway.")
|
||||
|
||||
|
||||
def get_customer_payment_profiles(customer_profile_id: str):
|
||||
"""
|
||||
@@ -420,8 +409,12 @@ def get_customer_payment_profiles(customer_profile_id: str):
|
||||
controller = getCustomerProfileController(request)
|
||||
|
||||
try:
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
else:
|
||||
controller.execute()
|
||||
|
||||
response = controller.getresponse()
|
||||
|
||||
if response.messages.resultCode == "Ok":
|
||||
@@ -467,7 +460,11 @@ def charge_customer_profile(customer_profile_id: str, payment_profile_id: str, t
|
||||
)
|
||||
|
||||
controller = createTransactionController(createtransactionrequest)
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
|
||||
controller.setenvironment(constants.PRODUCTION)
|
||||
controller.execute()
|
||||
else:
|
||||
controller.execute()
|
||||
|
||||
# The response is returned directly to the router to be parsed there
|
||||
return controller.getresponse()
|
||||
|
||||
Reference in New Issue
Block a user