small fixes working great

This commit is contained in:
2025-10-06 21:14:18 -04:00
parent 23a11a7009
commit f0096add0a
7 changed files with 28 additions and 565 deletions

View File

@@ -59,16 +59,16 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
print("DEBUG: No messages attribute") print("DEBUG: No messages attribute")
if response.messages.resultCode == "Ok": if response.messages.resultCode == "Ok":
print("DEBUG: Taking APPROVED path") print("✅✅ DEBUG: Taking APPROVED path")
status = TransactionStatus.APPROVED status = TransactionStatus.APPROVED
auth_net_transaction_id = None auth_net_transaction_id = None
# Extract transaction ID with proper error handling # Extract transaction ID with proper error handling
try: try:
if hasattr(response, 'transactionResponse') and response.transactionResponse: if hasattr(response, 'transactionResponse') and response.transactionResponse is not None:
if hasattr(response.transactionResponse, 'transId') and response.transactionResponse.transId: if hasattr(response.transactionResponse, 'transId') and response.transactionResponse.transId:
auth_net_transaction_id = str(response.transactionResponse.transId) auth_net_transaction_id = str(response.transactionResponse.transId)
print(f"DEBUG: FOUND transaction ID: {auth_net_transaction_id}") print(f"✅✅ DEBUG: FOUND transaction ID: {auth_net_transaction_id}")
else: else:
print("DEBUG: transactionResponse exists but no transId") print("DEBUG: transactionResponse exists but no transId")
else: else:
@@ -82,7 +82,7 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
print(dir(response.transactionResponse)) print(dir(response.transactionResponse))
rejection_reason = None rejection_reason = None
print(f"DEBUG: APPROVED - ID: {auth_net_transaction_id}, rejection: {rejection_reason}") print(f"✅✅✅ DEBUG: APPROVED - ID: {auth_net_transaction_id}, rejection: {rejection_reason}")
else: else:
print("DEBUG: Taking DECLINED path") print("DEBUG: Taking DECLINED path")
@@ -92,7 +92,7 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
if response is not None: if response is not None:
# Handle transaction response errors # Handle transaction response errors
if hasattr(response, 'transactionResponse') and response.transactionResponse: if hasattr(response, 'transactionResponse') and response.transactionResponse is not None:
if hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors: if hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors:
print("DEBUG: Using transactionResponse.errors") print("DEBUG: Using transactionResponse.errors")
try: try:
@@ -123,7 +123,7 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
print(f"DEBUG: Exception parsing message error: {e}") print(f"DEBUG: Exception parsing message error: {e}")
rejection_reason = "Failed to parse message error" rejection_reason = "Failed to parse message error"
print(f"DEBUG: FINAL RESULT - Status: {status}, ID: {auth_net_transaction_id}, Reason: {rejection_reason}") print(f"✅✅✅ DEBUG: FINAL RESULT - Status: {status}, ID: {auth_net_transaction_id}, Reason: {rejection_reason}")
return status, auth_net_transaction_id, rejection_reason return status, auth_net_transaction_id, rejection_reason
@router.post("/customers/{customer_id}/cards", summary="Add a new payment card for a customer") @router.post("/customers/{customer_id}/cards", summary="Add a new payment card for a customer")

View File

@@ -1,536 +0,0 @@
## File: your_app/views.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Tuple, Optional
import enum
import logging
from .. import crud, models, schemas, database
from ..services import payment_service
logger = logging.getLogger(__name__)
AuthNetResponse = object
router = APIRouter(
prefix="/payments",
tags=["Payments & Transactions"],
)
class TransactionStatus(enum.IntEnum):
APPROVED = 0
DECLINED = 1
class TransactionType(enum.IntEnum):
CHARGE = 0
AUTHORIZE = 1
CAPTURE = 3
# --- NEW CIM CORE FUNCTIONS ---
STATE_ID_TO_ABBREVIATION = {
0: "MA",
1: "RI",
2: "NH",
3: "ME",
4: "VT",
5: "CT",
6: "NY"
}
def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[TransactionStatus, Optional[str], Optional[str]]:
"""
Parse Authorize.net response with proper attribute access for SDK objects.
Authorize.net response objects don't have .text properties, they're direct attributes.
"""
print(f"DEBUG: Parsing response, type: {type(response)}")
print(f"DEBUG: Response exists: {response is not None}")
if response is not None:
print("DEBUG: Checking for messages attribute...")
if hasattr(response, 'messages'):
print(f"DEBUG: Messages exist, resultCode: {getattr(response.messages, 'resultCode', 'NO resultCode')}")
else:
print("DEBUG: No messages attribute")
if response.messages.resultCode == "Ok":
print("DEBUG: Taking APPROVED path")
status = TransactionStatus.APPROVED
auth_net_transaction_id = None
# Extract transaction ID with proper error handling
try:
if hasattr(response, 'transactionResponse') and response.transactionResponse:
if hasattr(response.transactionResponse, 'transId') and response.transactionResponse.transId:
auth_net_transaction_id = str(response.transactionResponse.transId)
print(f"DEBUG: FOUND transaction ID: {auth_net_transaction_id}")
else:
print("DEBUG: transactionResponse exists but no transId")
else:
print("DEBUG: No transactionResponse in approved response")
except Exception as e:
print(f"DEBUG: Exception extracting transaction ID: {e}")
print(f"DEBUG: Response object inspection:")
print(type(response))
if hasattr(response, 'transactionResponse'):
print(f"TransactionResponse type: {type(response.transactionResponse)}")
print(dir(response.transactionResponse))
rejection_reason = None
print(f"DEBUG: APPROVED - ID: {auth_net_transaction_id}, rejection: {rejection_reason}")
else:
print("DEBUG: Taking DECLINED path")
status = TransactionStatus.DECLINED
auth_net_transaction_id = None
rejection_reason = "Payment declined by gateway."
if response is not None:
# Handle transaction response errors
if hasattr(response, 'transactionResponse') and response.transactionResponse:
if hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors:
print("DEBUG: Using transactionResponse.errors")
try:
error = response.transactionResponse.errors[0]
# Remove the .text access - use direct attributes
error_code = getattr(error, 'errorCode', 'Unknown')
error_text = getattr(error, 'errorText', 'Unknown error')
rejection_reason = f"{error_code}: {error_text}"
print(f"DEBUG: Transaction error: {rejection_reason}")
except Exception as e:
print(f"DEBUG: Exception parsing transaction error: {e}")
rejection_reason = "Failed to parse transaction error"
# Handle message-level errors
elif hasattr(response, 'messages') and response.messages:
if hasattr(response.messages, 'message') and response.messages.message:
print("DEBUG: Using response.messages.message")
try:
msg = response.messages.message
if isinstance(msg, list):
msg = msg[0] if msg else None
if msg:
code = getattr(msg, 'code', 'Unknown')
text = getattr(msg, 'text', 'Unknown error')
rejection_reason = f"{code}: {text}"
print(f"DEBUG: Message error: {rejection_reason}")
except Exception as e:
print(f"DEBUG: Exception parsing message error: {e}")
rejection_reason = "Failed to parse message error"
print(f"DEBUG: FINAL RESULT - Status: {status}, ID: {auth_net_transaction_id}, Reason: {rejection_reason}")
return status, auth_net_transaction_id, rejection_reason
@router.post("/customers/{customer_id}/cards", summary="Add a new payment card for a customer")
def add_card_to_customer(customer_id: int, card_info: schemas.CardCreate, db: Session = Depends(database.get_db)):
"""
Adds a new credit card to a customer.
- If the customer doesn't have an Authorize.Net profile, it creates one.
- If they do, it adds a new payment method to their existing profile.
Returns the payment_profile_id from Authorize.Net.
"""
db_customer = crud.get_customer(db, customer_id=customer_id)
if not db_customer:
raise HTTPException(status_code=404, detail="Customer not found")
# We still need this schema for the payment service call
customer_schema = schemas.Customer.from_orm(db_customer)
payment_profile_id = None
try:
# This part now works because the service hard-codes the state to "MA"
if not db_customer.auth_net_profile_id:
profile_id, payment_id = payment_service.create_customer_profile(
customer=customer_schema, card_info=card_info
)
crud.update_customer_auth_net_profile_id(db, customer_id=customer_id, profile_id=profile_id)
payment_profile_id = payment_id
else:
payment_profile_id = payment_service.add_payment_profile_to_customer(
customer_profile_id=db_customer.auth_net_profile_id,
customer=customer_schema,
card_info=card_info
)
# Return the payment_profile_id
return {"payment_profile_id": payment_profile_id}
except ValueError as e:
# This will catch errors from the payment service
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
# This will catch any other unexpected errors, like from the database
raise HTTPException(status_code=500, detail="An internal server error occurred.")
@router.put("/customers/{customer_id}/cards/{card_id}", summary="Update an existing payment card for a customer")
def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.CardCreate, db: Session = Depends(database.get_db)):
"""
Updates an existing credit card for a customer.
- If the card has an existing Authorize.Net payment profile, deletes it first.
- Creates a new payment profile with updated card information.
- Updates the database card record with the new payment_profile_id.
Returns the new payment_profile_id from Authorize.Net.
"""
db_customer = crud.get_customer(db, customer_id=customer_id)
if not db_customer:
raise HTTPException(status_code=404, detail="Customer not found")
db_card = crud.get_card_by_id(db, card_id=card_id)
if not db_card or db_card.user_id != customer_id:
raise HTTPException(status_code=404, detail="Card not found for this customer")
if not db_customer.auth_net_profile_id:
raise HTTPException(status_code=400, detail="Customer does not have an Authorize.Net profile")
customer_schema = schemas.Customer.from_orm(db_customer)
try:
# If payment profile ID is null, refresh from Authorize.Net to sync
if not db_card.auth_net_payment_profile_id:
logger.info(f"Payment profile ID is null for card {card_id}, refreshing from Authorize.Net")
from ..services import user_create
user_create.refresh_customer_payment_profiles(db, customer_id, db_customer.auth_net_profile_id)
# Re-fetch the card to get the updated payment profile ID
db.refresh(db_card)
logger.info(f"After refresh, card {card_id} has payment_profile_id: {db_card.auth_net_payment_profile_id}")
# Delete existing payment profile if it exists
if db_card.auth_net_payment_profile_id:
from ..services import user_delete
delete_success = user_delete._delete_payment_profile(
db_customer.auth_net_profile_id, db_card.auth_net_payment_profile_id
)
if delete_success:
logger.info(f"Successfully deleted old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
# Clear the payment profile ID since it was deleted
db_card.auth_net_payment_profile_id = None
db.add(db_card)
db.commit()
else:
logger.warning(f"Failed to delete old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
# Create new payment profile with updated card information
new_payment_profile_id = payment_service.add_payment_profile_to_customer(
customer_profile_id=db_customer.auth_net_profile_id,
customer=customer_schema,
card_info=card_info
)
# Update the database card with the new payment profile ID
db_card.auth_net_payment_profile_id = new_payment_profile_id
db.add(db_card)
db.commit()
logger.info(f"Successfully updated card {card_id} with new payment profile {new_payment_profile_id}")
# Return the new payment_profile_id
return {"payment_profile_id": new_payment_profile_id}
except ValueError as e:
db.rollback()
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
db.rollback()
print(f"Failed to update card {card_id}: {str(e)}")
raise HTTPException(status_code=500, detail="An internal server error occurred.")
@router.post("/charge/saved-card/{customer_id}", response_model=schemas.Transaction, summary="Charge a customer using a saved card")
def charge_saved_card(customer_id: int, transaction_req: schemas.TransactionCreateByCardID, db: Session = Depends(database.get_db)):
db_customer = crud.get_customer(db, customer_id=customer_id)
db_card = crud.get_card_by_id(db, card_id=transaction_req.card_id)
if not db_customer or not db_card or db_card.user_id != customer_id:
raise HTTPException(status_code=404, detail="Customer or card not found for this account")
if not db_customer.auth_net_profile_id or not db_card.auth_net_payment_profile_id:
raise HTTPException(status_code=400, detail="Payment profile is not set up correctly for this customer/card")
auth_net_response = payment_service.charge_customer_profile(
customer_profile_id=db_customer.auth_net_profile_id,
payment_profile_id=db_card.auth_net_payment_profile_id,
transaction_req=transaction_req
)
status, auth_net_transaction_id, rejection_reason = _parse_authnet_response(auth_net_response)
transaction_data = schemas.TransactionBase(
charge_amount=transaction_req.charge_amount,
transaction_type=TransactionType.CHARGE,
service_id=transaction_req.service_id,
delivery_id=transaction_req.delivery_id,
card_id=transaction_req.card_id,
rejection_reason=rejection_reason
)
return crud.create_transaction(db=db, transaction=transaction_data, customer_id=customer_id, status=status, auth_net_transaction_id=auth_net_transaction_id)
@router.post("/authorize/saved-card/{customer_id}", response_model=schemas.Transaction, summary="Authorize a payment on a saved card")
def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionAuthorizeByCardID, db: Session = Depends(database.get_db)):
"""
Creates a pre-authorization on a customer's saved card.
This validates the card and reserves the funds.
"""
print("🐛 DEBUG: ENTERING authorize_saved_card ROUTER FUNCTION")
db_customer = crud.get_customer(db, customer_id=customer_id)
db_card = crud.get_card_by_id(db, card_id=transaction_req.card_id)
if not db_customer or not db_card or db_card.user_id != customer_id:
raise HTTPException(status_code=404, detail="Customer or card not found for this account")
print("🐛 DEBUG: CUSTOMER AND CARD FOUND, STARTING PRE-VALIDATION")
# 🚨 ENHANCED PRE-TRANSACTION VALIDATION 🚨
# Proactively check and fix payment profile issues before attempting transaction
print(f"🐛 DEBUG: Starting enhanced pre-validation for customer {customer_id}, card {db_card.id}")
logger.info(f"🔍 PRE-TRANSACTION CHECK: Customer {customer_id}, Card {db_card.id}")
logger.info(f"🔍 Current auth_net_profile_id: '{db_customer.auth_net_profile_id}'")
logger.info(f"🔍 Current payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
# Check for missing payment profiles OR test validity of existing ones
needs_recovery = False
print(f"🐛 DEBUG: Checking payment profiles - customer_id: {db_customer.auth_net_profile_id}, card_id: {db_card.auth_net_payment_profile_id}")
if (not db_customer.auth_net_profile_id or
not db_card.auth_net_payment_profile_id or
db_card.auth_net_payment_profile_id.strip() == "" or
str(db_card.auth_net_payment_profile_id).lower() == "none" or
db_card.auth_net_payment_profile_id is None):
# Missing/null payment profile - needs recovery
needs_recovery = True
print("🐛 DEBUG: NULL/MISSING PAYMENT PROFILE DETECTED")
logger.warning(f"🔧 NULL/MISSING PAYMENT PROFILE DETECTED - Triggering auto-recovery")
else:
# Payment profile exists in DB, but let's test if it's valid in Authorize.net
print(f"🐛 DEBUG: Payment profile exists, testing validity in Authorize.net...")
logger.info(f"🔍 Payment profile exists, testing validity in Authorize.net...")
try:
# Quick test: try to retrieve customer payment profiles to see if our ID is valid
print(f"🐛 DEBUG: Calling get_customer_payment_profiles for profile_id: {db_customer.auth_net_profile_id}")
test_profiles = payment_service.get_customer_payment_profiles(db_customer.auth_net_profile_id)
print(f"🐛 DEBUG: Got profiles from Authorize.net: {test_profiles}")
current_id = str(db_card.auth_net_payment_profile_id)
profile_ids_as_strings = [str(pid) for pid in test_profiles if pid]
print(f"🐛 DEBUG: Checking if '{current_id}' is in: {profile_ids_as_strings}")
if current_id not in profile_ids_as_strings:
needs_recovery = True
print(f"🐛 DEBUG: PAYMENT PROFILE {current_id} NOT FOUND - NEEDS RECOVERY")
logger.warning(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} NOT FOUND IN AUTHORIZE.NET - Invalid ID!")
logger.warning(f"🔧 Available profiles in Authorize.net: {test_profiles}")
else:
print(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} exists in Authorize.net, testing usability...")
# Profile exists in Authorize.net, but test if it's actually USABLE
# by doing a quick test authorization with minimal amount
try:
print(f"🐛 DEBUG: Testing if payment profile is actually usable...")
# Create a tiny test transaction (like $0.01) to validate the card works
test_transaction_req = schemas.TransactionAuthorizeByCardID(
card_id=db_card.id,
preauthorize_amount="0.01" # Minimal test amount
)
test_response = payment_service.authorize_customer_profile(
customer_profile_id=db_customer.auth_net_profile_id,
payment_profile_id=db_card.auth_net_payment_profile_id,
transaction_req=test_transaction_req,
db_session=None, # Don't pass DB session for test transaction
customer_id=None,
card_id=None
)
# Check if the test authorization worked
from ..services import payment_service as ps # Need access to _parse_authnet_response
test_status, _, test_reason = _parse_authnet_response(test_response)
if "E00121" in str(test_reason) or test_status == 1: # 1 = DECLINED
print(f"🐛 DEBUG: TEST AUTH FAILED - Payment profile exists but is INVALID!")
needs_recovery = True
logger.warning(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} EXISTS BUT IS UNUSABLE - E00121 detected during test!")
logger.warning(f"🔧 Test transaction failed: {test_reason}")
else:
print(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} is VALID and USABLE")
logger.info(f"✅ Payment profile {db_card.auth_net_payment_profile_id} is valid and usable in Authorize.net")
except Exception as e:
print(f"🐛 DEBUG: Exception during usability test: {str(e)} - assuming profile needs recreation")
needs_recovery = True
logger.warning(f"🔧 Could not test payment profile usability: {str(e)} - assuming it needs recreation")
except Exception as e:
print(f"🐛 DEBUG: Exception during profile validation: {str(e)}")
logger.warning(f"🔧 Could not verify payment profile validity in Authorize.net: {str(e)}")
# If we can't verify, assume it's okay and let the transaction proceed
# (better to try and fail than to block legitimate transactions)
logger.info(f"⚠️ Unable to verify profile validity - proceeding with transaction anyway")
if needs_recovery:
logger.warning(f"🔧 DETECTED PAYMENT PROFILE ISSUE - Triggering auto-recovery for customer {customer_id}")
# Auto-recover: Refresh payment profiles before transaction
from ..services import user_create
recovery_success = user_create.refresh_customer_payment_profiles(
db, customer_id, db_customer.auth_net_profile_id
)
if recovery_success:
logger.info("✅ Auto-recovery successful - proceeding with transaction")
# Re-fetch card data to get updated payment profile ID
db.refresh(db_card)
db.refresh(db_customer)
logger.info(f"🔍 After recovery - payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
else:
logger.error("❌ Auto-recovery failed - cannot proceed with transaction")
raise HTTPException(
status_code=400,
detail="Payment profile setup error detected and auto-recovery failed. Please contact support."
)
# Final validation before proceeding
if not db_customer.auth_net_profile_id or not db_card.auth_net_payment_profile_id:
logger.error(f"❌ CRITICAL: Payment profile validation failed after recovery attempt")
raise HTTPException(
status_code=400,
detail="Payment profile is not set up correctly for this customer/card"
)
logger.info(f"✅ Payment profile validation passed - proceeding with authorization")
# 🚨 ENHANCED E00121 ERROR HANDLING 🚨
# If transaction still fails with E00121 despite pre-validation, force-nuke the problematic ID
auth_net_response = payment_service.authorize_customer_profile(
customer_profile_id=db_customer.auth_net_profile_id,
payment_profile_id=db_card.auth_net_payment_profile_id,
transaction_req=transaction_req,
db_session=db,
customer_id=customer_id,
card_id=db_card.id
)
# Parse the transaction response (no need for E00121 nuclear cleanup since pre-validation should have caught it)
transaction_status, auth_net_transaction_id, rejection_reason = _parse_authnet_response(auth_net_response)
print(transaction_req)
transaction_data = schemas.TransactionBase(
preauthorize_amount=transaction_req.preauthorize_amount,
transaction_type=TransactionType.AUTHORIZE, # This is key
service_id=transaction_req.service_id,
delivery_id=transaction_req.delivery_id,
auto_id=transaction_req.auto_id,
card_id=transaction_req.card_id,
rejection_reason=rejection_reason
)
db_transaction = crud.create_transaction(
db=db,
transaction=transaction_data,
customer_id=customer_id,
status=transaction_status,
auth_net_transaction_id=auth_net_transaction_id
)
return db_transaction
def _nuclear_e00121_payment_profile_cleanup(db: Session, customer_id: int, card_id: int, corrupted_profile_id: str, customer_profile_id: str) -> bool:
"""
DEDICATED E00121 NUKER: Forcefully removes problematic payment profile IDs from both database and Authorize.net.
This is the nuclear option for when E00121 payment profile errors persist despite all attempts to recover.
Args:
db: Database session
customer_id: Customer ID
card_id: Card ID that has the corrupted profile
corrupted_profile_id: The problematic payment profile ID causing E00121
customer_profile_id: Customer profile ID in Authorize.net
Returns:
bool: True if cleanup successful and card can be retried
"""
print("💣 NUCLEAR E00121 CLEANUP INITIATED! 💣")
print(f"💣 Target: Card {card_id}, Profile {corrupted_profile_id}")
try:
from .. import crud
from ..services import user_delete
# Step 1: Get the card from database
card = crud.get_card_by_id(db, card_id)
if not card:
print(f"💣 ERROR: Card {card_id} not found in database")
return False
# Step 2: NUKE FROM AUTHORIZE.NET FIRST
print(f"💣 Deleting corrupted profile {corrupted_profile_id} from Authorize.net...")
try:
delete_success = user_delete._delete_payment_profile(customer_profile_id, corrupted_profile_id)
if delete_success:
print("✅ Successfully deleted corrupted profile from Authorize.net")
else:
print("⚠️ Profile may not have existed in Authorize.net or delete failed")
except Exception as e:
print(f"⚠️ Exception deleting from Authorize.net: {str(e)} - continuing anyway")
# Step 3: NUKE FROM DATABASE REGARDLESS
print(f"💣 Clearing corrupted profile ID {corrupted_profile_id} from database card {card_id}")
card.auth_net_payment_profile_id = None
db.add(card)
db.commit()
print("✅ Successfully cleared corrupted profile ID from database")
# Step 4: Attempt immediate recreation of payment profile
print("💣 Attempting immediate recreation of payment profile...")
try:
customer = crud.get_customer(db, customer_id)
# Format card data for recreation
# Convert to string first to handle cases where database returns int instead of string
exp_year_str = str(card.expiration_year)
exp_month_str = str(card.expiration_month)
exp_year = exp_year_str.zfill(4) if len(exp_year_str) < 4 else exp_year_str
exp_month = exp_month_str.zfill(2) if len(exp_month_str) < 2 else exp_month_str
exp_date = f"{exp_year}-{exp_month}"
card_create_data = schemas.CardCreate(
card_number=card.card_number,
expiration_date=exp_date,
cvv=card.security_number
)
from ..services import payment_service
new_profile_id = payment_service.add_payment_profile_to_customer(
customer_profile_id, customer, card_create_data, is_default=(card.main_card == True)
)
if new_profile_id:
print(f"✅ IMMEDIATE RECREATION SUCCESSFUL: New profile {new_profile_id}")
card.auth_net_payment_profile_id = str(new_profile_id)
db.add(card)
db.commit()
print(f"💣 Nuclear cleanup COMPLETE - Card {card_id} has new profile {new_profile_id}")
return True
else:
print("❌ Immediate recreation failed - no new profile ID")
return False
except Exception as recreate_e:
print(f"❌ Immediate recreation failed: {str(recreate_e)}")
print("💣 Database cleared but recreation failed - needs manual recreation later")
return False
except Exception as nuke_e:
print(f"💣 CRITICAL ERROR in nuclear cleanup: {str(nuke_e)}")
db.rollback()
return False
# --- CAPTURE ENDPOINT MOVED TO TRANSACTION ROUTER ---

View File

@@ -90,9 +90,9 @@ def verify_customer_authorize_account(db: Session, customer_id: int) -> dict:
# Check for payment profiles (cards) # Check for payment profiles (cards)
has_payment_methods = False has_payment_methods = False
if hasattr(response, 'profile') and response.profile: if hasattr(response, 'profile') and response.profile is not None:
payment_profiles = response.profile.paymentProfiles payment_profiles = response.profile.paymentProfiles
if payment_profiles and len(payment_profiles) > 0: if len(payment_profiles) > 0:
has_payment_methods = True has_payment_methods = True
missing_components = [] missing_components = []
@@ -127,7 +127,7 @@ def _is_profile_valid(response) -> bool:
""" """
try: try:
# Check basic response validity # Check basic response validity
if not response: if response is None:
return False return False
# Check if result code indicates success # Check if result code indicates success
@@ -139,7 +139,7 @@ def _is_profile_valid(response) -> bool:
return False return False
# Check for any error messages that indicate profile doesn't exist # Check for any error messages that indicate profile doesn't exist
if hasattr(response, 'messages') and response.messages.message: if hasattr(response, 'messages') and len(response.messages.message) > 0:
for message in response.messages.message: for message in response.messages.message:
# Check for specific error codes that indicate profile doesn't exist # Check for specific error codes that indicate profile doesn't exist
if hasattr(message, 'code'): if hasattr(message, 'code'):

View File

@@ -25,11 +25,11 @@ if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY
else: else:
constants.environment = constants.SANDBOX constants.environment = constants.SANDBOX
constants.show_url_on_request = True # Very useful for debugging
VALIDATION_MODE = "testMode" VALIDATION_MODE = "testMode"
API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID
TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY
constants.show_url_on_request = True # Very useful for debugging
def _is_e00121_response(response): def _is_e00121_response(response):
""" """
@@ -71,7 +71,7 @@ def _get_authnet_error_message(response):
return "No response from payment gateway." return "No response from payment gateway."
try: try:
if hasattr(response, 'messages') and response.messages is not None: if hasattr(response, 'messages') and response.messages is not None:
if hasattr(response, 'transactionResponse') and response.transactionResponse and hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors: if hasattr(response, 'transactionResponse') and response.transactionResponse is not None and hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors:
error = response.transactionResponse.errors[0] error = response.transactionResponse.errors[0]
return f"Error {error.errorCode}: {error.errorText}" return f"Error {error.errorCode}: {error.errorText}"
if hasattr(response.messages, 'message'): if hasattr(response.messages, 'message'):
@@ -251,11 +251,11 @@ def _perform_authorization(customer_profile_id: str, payment_profile_id: str, tr
response = controller.getresponse() response = controller.getresponse()
# Log response details # Log response details
if response and hasattr(response, 'messages'): if response is not None and hasattr(response, 'messages'):
result_code = getattr(response.messages, 'resultCode', 'Unknown') result_code = getattr(response.messages, 'resultCode', 'Unknown')
print(f"Authorize response: resultCode='{result_code}'") print(f"Authorize response: resultCode='{result_code}'")
else: else:
print("Authorize response: No standard response structure") print("Authorize response: No standard response structure")
return response return response

View File

@@ -13,8 +13,6 @@ from sqlalchemy.orm import Session
from . import payment_service from . import payment_service
from .. import schemas from .. import schemas
logger = logging.getLogger(__name__)
# Load Authorize.net credentials # Load Authorize.net credentials
ApplicationConfig = load_config() ApplicationConfig = load_config()
@@ -181,8 +179,8 @@ def create_user_account(db: Session, customer_id: int) -> dict:
print(f"Assigning {num_to_update} payment profile IDs to cards") print(f"Assigning {num_to_update} payment profile IDs to cards")
if len(payment_profile_ids) != len(cards): if len(payment_profile_ids) != len(cards):
logger.warning(f"Mismatch between payment profile count ({len(payment_profile_ids)}) and card count ({len(cards)})") print(f"Mismatch between payment profile count ({len(payment_profile_ids)}) and card count ({len(cards)})")
logger.warning("This could cause incorrect payment profile assignments!") print("This could cause incorrect payment profile assignments!")
cards_updated = 0 cards_updated = 0
for i in range(num_to_update): for i in range(num_to_update):
@@ -278,7 +276,7 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
payment_profile_ids = payment_service.get_customer_payment_profiles(auth_profile_id) payment_profile_ids = payment_service.get_customer_payment_profiles(auth_profile_id)
print(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}") print(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}")
except Exception as e: except Exception as e:
logger.warning(f"🔄 Could not retrieve payment profiles from Authorize.net: {str(e)}") print(f"🔄 Could not retrieve payment profiles from Authorize.net: {str(e)}")
print("🔄 Will attempt to recreate missing payment profiles") print("🔄 Will attempt to recreate missing payment profiles")
# STEP 2: Check if we have enough payment profiles for our cards # STEP 2: Check if we have enough payment profiles for our cards
@@ -290,7 +288,7 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
elif str(card.auth_net_payment_profile_id) not in [str(pid) for pid in payment_profile_ids if pid]: elif str(card.auth_net_payment_profile_id) not in [str(pid) for pid in payment_profile_ids if pid]:
# Payment profile ID exists in DB but not found in Authorize.net - likely invalid # Payment profile ID exists in DB but not found in Authorize.net - likely invalid
cards_need_update.append(card) cards_need_update.append(card)
logger.warning(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} but it's not found in Authorize.net - NEEDS RECREATION") print(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} but it's not found in Authorize.net - NEEDS RECREATION")
else: else:
if ApplicationConfig.penny_test_transaction: if ApplicationConfig.penny_test_transaction:
# Profile exists in Authorize.net, but let's double-check it's usable by doing a quick test # Profile exists in Authorize.net, but let's double-check it's usable by doing a quick test
@@ -311,7 +309,7 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
_, _, test_reason = payment_service._parse_authnet_response(test_response) _, _, test_reason = payment_service._parse_authnet_response(test_response)
if "E00121" in str(test_reason): if "E00121" in str(test_reason):
cards_need_update.append(card) cards_need_update.append(card)
logger.warning(f"🔄 Card {card.id} has profile {card.auth_net_payment_profile_id} that EXISTS but is CORRUPTED - NEEDS RECREATION") print(f"🔄 Card {card.id} has profile {card.auth_net_payment_profile_id} that EXISTS but is CORRUPTED - NEEDS RECREATION")
# Explicitly delete the corrupted profile first # Explicitly delete the corrupted profile first
try: try:
from . import user_delete from . import user_delete
@@ -321,14 +319,14 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
card.auth_net_payment_profile_id = None card.auth_net_payment_profile_id = None
db.add(card) db.add(card)
except Exception as del_e: except Exception as del_e:
logger.warning(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}") print(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}")
else: else:
logger.debug(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}") print(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}")
except Exception as test_e: except Exception as test_e:
logger.warning(f"🔄 Could not test usability of profile {card.auth_net_payment_profile_id} for card {card.id}: {str(test_e)} - assuming it's okay") print(f"🔄 Could not test usability of profile {card.auth_net_payment_profile_id} for card {card.id}: {str(test_e)} - assuming it's okay")
else: else:
print(f"🔄 Skipping penny test transaction for card {card.id} (disabled in config)") print(f"🔄 Skipping penny test transaction for card {card.id} (disabled in config)")
logger.debug(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - skipping usability test (config disabled)") print(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - skipping usability test (config disabled)")
# STEP 3: If we don't have enough valid payment profiles, recreate missing ones # STEP 3: If we don't have enough valid payment profiles, recreate missing ones
if len(cards_need_update) > 0: if len(cards_need_update) > 0:
@@ -400,7 +398,7 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
print(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs") print(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs")
return True return True
else: else:
logger.warning("🔄 Refresh PARTIAL: Some cards may still have invalid payment profile IDs") print("🔄 Refresh PARTIAL: Some cards may still have invalid payment profile IDs")
return False return False
except Exception as e: except Exception as e:

View File

@@ -36,3 +36,4 @@ class ApplicationConfig:
# # # Authorize.net credentials (Sandbox Test Credentials) # # # Authorize.net credentials (Sandbox Test Credentials)
# API_LOGIN_ID = '5KP3u95bQpv' # API_LOGIN_ID = '5KP3u95bQpv'
# TRANSACTION_KEY = '346HZ32z3fP4hTG2' # TRANSACTION_KEY = '346HZ32z3fP4hTG2'
penny_test_transaction = False # Run penny test in development