major claude changes

This commit is contained in:
2026-01-28 21:54:54 -05:00
parent 76e881d939
commit 1832c8ab62
15 changed files with 423 additions and 296 deletions

View File

@@ -1,9 +1,11 @@
## File: your_app/services/payment_service.py
import pprint
import logging
import traceback
import re
from authorizenet import apicontractsv1
logger = logging.getLogger(__name__)
from authorizenet.apicontrollers import (
createTransactionController,
createCustomerProfileController,
@@ -55,19 +57,19 @@ def _is_e00121_response(response):
if isinstance(message, list):
for msg in message:
if getattr(msg, 'code', '') == 'E00121':
print("E00121 detected in message list")
logger.debug("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')}'")
logger.debug(f"E00121 detected: '{getattr(message, 'text', 'No details')}'")
return True
else:
print(f"Message code: '{message.code}' (not E00121)")
logger.debug(f"Message code: '{message.code}' (not E00121)")
return False
except Exception as e:
print(f"Error checking for E00121: {str(e)}")
logger.debug(f"Error checking for E00121: {str(e)}")
return False
def _get_authnet_error_message(response):
@@ -91,7 +93,7 @@ def _get_authnet_error_message(response):
text = msg.text if hasattr(msg, 'text') else 'No details provided.'
return f"Error {code}: {text}"
except Exception as e:
print(f"Error while parsing Auth.Net error message: {e}")
logger.debug(f"Error while parsing Auth.Net error message: {e}")
return "An unparsable error occurred with the payment gateway."
return "An unknown error occurred with the payment gateway."
@@ -101,13 +103,11 @@ def create_customer_profile(customer: schemas.Customer, card_info: schemas.CardC
Creates a new customer profile in Authorize.Net (payment profiles added separately).
This version sanitizes and trims customer data before sending.
"""
print(f"Attempting to create Auth.Net profile for customer ID: {customer.id}")
print(API_LOGIN_ID)
print(TRANSACTION_KEY)
# Note: Never log API credentials
try:
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)
except Exception as e:
print(e)
pass # Will be handled by request failure below
# API max lengths: email=255
email = (customer.customer_email or f"no-email-{customer.id}@example.com")[:255]
@@ -138,26 +138,25 @@ def create_customer_profile(customer: schemas.Customer, card_info: schemas.CardC
# Check if response is None (API call failed)
if response is None:
print("ERROR: Authorize.net API call returned None - likely a network/connectivity issue")
logger.debug("ERROR: Authorize.net API call returned None - likely a network/connectivity issue")
raise ValueError("Could not connect to the payment gateway. Please check network connectivity.")
try:
if response.messages.resultCode == "Ok":
profile_id = response.customerProfileId
print(profile_id)
logger.debug(profile_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)")
logger.debug(f"SUCCESS: Created customer profile: {profile_id} (payment profiles added separately)")
# Add detailed logging
print(f"API Response - Profile ID: {profile_id}")
print(f"Returning: profile_id='{str(profile_id)}', payment_id=''")
logger.debug(f"API Response - Profile ID: {profile_id}")
logger.debug(f"Returning: profile_id='{str(profile_id)}', payment_id=''")
return str(profile_id), ""
else:
error_msg = _get_authnet_error_message(response)
print(f"Failed to create customer profile (API Error): {error_msg}")
print(f"Full API Response: {pprint.pformat(vars(response))}")
logger.debug(f"Failed to create customer profile (API Error): {error_msg}")
raise ValueError(error_msg)
except ValueError:
@@ -165,7 +164,7 @@ def create_customer_profile(customer: schemas.Customer, card_info: schemas.CardC
# Re-raise specific ValueError messages we already set above (like E00039)
raise
except Exception as e:
print(f"A critical exception occurred during the API call: {traceback.format_exc()}")
logger.debug(f"A critical exception occurred during the API call: {traceback.format_exc()}")
raise ValueError("Could not connect to the payment gateway.")
@@ -175,24 +174,24 @@ def authorize_customer_profile(customer_profile_id: str, payment_profile_id: str
Creates an AUTH_ONLY transaction against a customer profile with automatic E00121 recovery.
This holds funds but doesn't capture them, and automatically recovers from invalid payment profiles.
"""
print(f"Authorizing profile {customer_profile_id} / payment {payment_profile_id} for ${transaction_req.preauthorize_amount}")
logger.debug(f"Authorizing profile {customer_profile_id} / payment {payment_profile_id} for ${transaction_req.preauthorize_amount}")
# Validate inputs
if not customer_profile_id or customer_profile_id.strip() == "":
print("INVALID: customer_profile_id is None or empty")
logger.debug("INVALID: customer_profile_id is None or empty")
if not payment_profile_id or payment_profile_id.strip() == "":
print("INVALID: payment_profile_id is None or empty")
print("Payment profile ID must be a valid, non-empty string")
logger.debug("INVALID: payment_profile_id is None or empty")
logger.debug("Payment profile ID must be a valid, non-empty string")
# FIRST ATTEMPT - Normal authorization
print("TRANSACTION ATTEMPT 1: Standard authorization")
logger.debug("TRANSACTION ATTEMPT 1: Standard authorization")
response = _perform_authorization(customer_profile_id, payment_profile_id, transaction_req)
# CHECK FOR E00121 ERROR - "invalid payment profile ID"
if db_session and customer_id and card_id and _is_e00121_response(response):
print(f"E00121 DETECTED! Invalid payment profile {payment_profile_id}")
print("POOOP")
print(f"AUTO-RECOVERING: Starting payment profile refresh for customer {customer_id}")
logger.debug(f"E00121 DETECTED! Invalid payment profile {payment_profile_id}")
logger.debug("POOOP")
logger.debug(f"AUTO-RECOVERING: Starting payment profile refresh for customer {customer_id}")
try:
# GET CUSTOMER PROFILE ID (since we have customer_id but need profile_id)
@@ -200,7 +199,7 @@ def authorize_customer_profile(customer_profile_id: str, payment_profile_id: str
customer = crud.get_customer(db_session, customer_id)
if customer:
# REFRESH ALL PAYMENT PROFILES FOR THIS CUSTOMER
print(f"CALLING REFRESH: customer_id={customer_id}, profile_id={customer.auth_net_profile_id}")
logger.debug(f"CALLING REFRESH: customer_id={customer_id}, profile_id={customer.auth_net_profile_id}")
from .user_create import refresh_customer_payment_profiles
refresh_customer_payment_profiles(db_session, customer_id, customer.auth_net_profile_id)
@@ -208,25 +207,25 @@ def authorize_customer_profile(customer_profile_id: str, payment_profile_id: str
updated_card = crud.get_card_by_id(db_session, card_id)
if updated_card and updated_card.auth_net_payment_profile_id != payment_profile_id:
new_payment_profile_id = updated_card.auth_net_payment_profile_id
print(f"RECOVERY SUCCESS: Old ID '{payment_profile_id}' → New ID '{new_payment_profile_id}'")
logger.debug(f"RECOVERY SUCCESS: Old ID '{payment_profile_id}' → New ID '{new_payment_profile_id}'")
# SECOND ATTEMPT - With refreshed payment profile ID
print("TRANSACTION ATTEMPT 2: Retry with refreshed payment profile")
logger.debug("TRANSACTION ATTEMPT 2: Retry with refreshed payment profile")
response = _perform_authorization(customer_profile_id, new_payment_profile_id, transaction_req)
if _is_e00121_response(response):
print("E00121 STILL PERSISTS after refresh - manual intervention may be needed")
print(f"Payment profile {new_payment_profile_id} also rejected by Authorize.Net")
logger.debug("E00121 STILL PERSISTS after refresh - manual intervention may be needed")
logger.debug(f"Payment profile {new_payment_profile_id} also rejected by Authorize.Net")
else:
print(f"SUCCESS! E00121 RESOLVED - Transaction succeeded with refreshed payment profile {new_payment_profile_id}")
logger.debug(f"SUCCESS! E00121 RESOLVED - Transaction succeeded with refreshed payment profile {new_payment_profile_id}")
else:
print(f"RECOVERY FAILED: No updated payment profile ID found for card {card_id}")
print("Database refresh did not provide new payment profile ID")
logger.debug(f"RECOVERY FAILED: No updated payment profile ID found for card {card_id}")
logger.debug("Database refresh did not provide new payment profile ID")
else:
print(f"RECOVERY FAILED: Customer {customer_id} not found in database")
logger.debug(f"RECOVERY FAILED: Customer {customer_id} not found in database")
except Exception as e:
print(f"AUTO-RECOVERY FAILED: {str(e)}")
print("Exception during payment profile refresh process")
logger.debug(f"AUTO-RECOVERY FAILED: {str(e)}")
logger.debug("Exception during payment profile refresh process")
return response
@@ -271,9 +270,9 @@ def _perform_authorization(customer_profile_id: str, payment_profile_id: str, tr
# Log response details
if response is not None and hasattr(response, 'messages'):
result_code = getattr(response.messages, 'resultCode', 'Unknown')
print(f"✅ Authorize response: resultCode='{result_code}'")
logger.debug(f"✅ Authorize response: resultCode='{result_code}'")
else:
print("✅ Authorize response: No standard response structure")
logger.debug("✅ Authorize response: No standard response structure")
return response
@@ -283,7 +282,7 @@ def _perform_authorization(customer_profile_id: str, payment_profile_id: str, tr
def capture_authorized_transaction(transaction_req: schemas.TransactionCapture):
"""Captures a previously authorized transaction."""
print(f"Capturing transaction {transaction_req.auth_net_transaction_id} for {transaction_req.charge_amount}")
logger.debug(f"Capturing transaction {transaction_req.auth_net_transaction_id} for {transaction_req.charge_amount}")
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)
@@ -312,7 +311,7 @@ def capture_authorized_transaction(transaction_req: schemas.TransactionCapture):
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}")
logger.debug(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)
@@ -348,7 +347,7 @@ def add_payment_profile_to_customer(customer_profile_id: str, customer: schemas.
else:
expiration_date = "0325"
print(f"Parsed expiration date for card: {card_info.expiration_date} -> {expiration_date}")
# Expiration date parsed successfully
creditCard = apicontractsv1.creditCardType(
cardNumber=card_info.card_number,
@@ -396,7 +395,7 @@ def add_payment_profile_to_customer(customer_profile_id: str, customer: schemas.
# Check if response is None (API call failed)
if response is None:
print("ERROR: Authorize.net API call returned None - likely a network/connectivity issue")
logger.debug("ERROR: Authorize.net API call returned None - likely a network/connectivity issue")
raise ValueError("Could not connect to the payment gateway. Please check network connectivity.")
if response.messages.resultCode == "Ok":
@@ -404,20 +403,15 @@ def add_payment_profile_to_customer(customer_profile_id: str, customer: schemas.
if hasattr(response, 'customerPaymentProfileId') and response.customerPaymentProfileId:
return str(response.customerPaymentProfileId)
else:
print("WARNING: Added payment profile but no ID returned")
logger.debug("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)))
logger.debug(f"Failed to add payment profile: {error_msg}")
raise ValueError(error_msg)
except Exception as e:
print(f"A critical exception occurred during the API call: {traceback.format_exc()}")
logger.debug(f"A critical exception occurred during the API call: {traceback.format_exc()}")
raise ValueError("Could not connect to the payment gateway.")
@@ -426,7 +420,7 @@ def get_customer_payment_profiles(customer_profile_id: str):
Retrieves all payment profile IDs for a given customer profile from Authorize.net.
Returns a list of payment profile IDs in the order they were created.
"""
print(f"Retrieving payment profiles for customer profile ID: {customer_profile_id}")
logger.debug(f"Retrieving payment profiles for customer profile ID: {customer_profile_id}")
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)
@@ -452,7 +446,7 @@ def get_customer_payment_profiles(customer_profile_id: str):
# Check if response is None (API call failed)
if response is None:
print("ERROR: Authorize.net API call returned None - likely a network/connectivity issue")
logger.debug("ERROR: Authorize.net API call returned None - likely a network/connectivity issue")
raise ValueError("Could not connect to the payment gateway. Please check network connectivity.")
if response.messages.resultCode == "Ok":
@@ -461,15 +455,15 @@ def get_customer_payment_profiles(customer_profile_id: str):
for profile in response.profile.paymentProfiles:
payment_profile_ids.append(str(profile.customerPaymentProfileId))
print(f"Retrieved {len(payment_profile_ids)} payment profile IDs for profile {customer_profile_id}")
logger.debug(f"Retrieved {len(payment_profile_ids)} payment profile IDs for profile {customer_profile_id}")
return payment_profile_ids
else:
error_msg = _get_authnet_error_message(response)
print(f"Failed to retrieve customer profile {customer_profile_id}: {error_msg}")
logger.debug(f"Failed to retrieve customer profile {customer_profile_id}: {error_msg}")
raise ValueError(f"Could not retrieve customer profile: {error_msg}")
except Exception as e:
print(f"Critical exception while retrieving customer profile {customer_profile_id}: {traceback.format_exc()}")
logger.debug(f"Critical exception while retrieving customer profile {customer_profile_id}: {traceback.format_exc()}")
raise ValueError("Could not connect to the payment gateway.")
@@ -478,7 +472,7 @@ def charge_customer_profile(customer_profile_id: str, payment_profile_id: str, t
Creates an AUTH_CAPTURE transaction (charge now) against a customer profile.
This charges the customer immediately for the full amount.
"""
print(f"Charging profile {customer_profile_id} / payment {payment_profile_id} for ${transaction_req.charge_amount}")
logger.debug(f"Charging profile {customer_profile_id} / payment {payment_profile_id} for ${transaction_req.charge_amount}")
merchantAuth = apicontractsv1.merchantAuthenticationType(name=API_LOGIN_ID, transactionKey=TRANSACTION_KEY)