import logging import pprint import traceback from authorizenet import apicontractsv1 from authorizenet.apicontrollers import ( createCustomerProfileController, createCustomerPaymentProfileController ) from authorizenet.constants import constants from config import load_config from sqlalchemy.orm import Session from . import payment_service from .. import schemas logger = logging.getLogger(__name__) # Load Authorize.net credentials ApplicationConfig = load_config() API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY # Set Authorize.net environment based on configuration if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION': constants.environment = constants.PRODUCTION else: constants.environment = constants.SANDBOX constants.show_url_on_request = True def _get_error_message(response): """ Robust error parsing function that correctly handles the API's response format. """ if response is None: return "No response from payment gateway." try: 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: error = response.transactionResponse.errors[0] return f"Error {error.errorCode}: {error.errorText}" if hasattr(response.messages, 'message'): message_list = response.messages.message if not isinstance(message_list, list): message_list = [message_list] if message_list: msg = message_list[0] code = msg.code if hasattr(msg, 'code') else 'Unknown' text = msg.text if hasattr(msg, 'text') else 'No details provided.' return f"Error {code}: {text}" except Exception as e: logger.error(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." def create_user_account(db: Session, customer_id: int) -> dict: """ Create a complete Authorize.net account for a user from scratch. This includes creating the customer profile with their first card, and adding any additional cards as payment profiles. Args: db: Database session customer_id: ID of the customer to create account for Returns: Dict with success status, message, and account details """ try: # Get customer and their cards from .. import crud # Import here to avoid circular imports customer = crud.get_customer(db, customer_id) if not customer: return { "success": False, "message": f"Customer {customer_id} not found", "profile_id": None } # Get customer's cards from database cards = crud.get_customer_cards(db, customer_id) if not cards: return { "success": False, "message": "No cards available for customer - cannot create account", "profile_id": None } # Determine if this is a new creation or update of existing profile original_profile_id = customer.auth_net_profile_id # Get the first card to use for initial profile creation first_card = cards[0] logger.info(f"Using first card ID={first_card.id} for profile creation") logger.info(f"Card Number: {first_card.card_number[:4]}**** ****{first_card.card_number[-4:]}") logger.info(f"Expiration: {first_card.expiration_month}/{first_card.expiration_year}") # Create CardCreate object for the first card # Format expiration date for string values - pad year to 4 digits and month to 2 digits expiration_year = first_card.expiration_year.zfill(4) if len(first_card.expiration_year) < 4 else first_card.expiration_year expiration_month = first_card.expiration_month.zfill(2) if len(first_card.expiration_month) < 2 else first_card.expiration_month expiration_date = f"{expiration_year}-{expiration_month}" card_info = schemas.CardCreate( card_number=first_card.card_number, expiration_date=expiration_date, cvv=first_card.security_number ) logger.info(f"Card info expiration_date: {card_info.expiration_date}") logger.info(f"Processing Authorize.net profile for customer {customer_id} with {len(cards)} cards") # Create customer profile and payment profiles if not exists if not customer.auth_net_profile_id: # Create the initial customer profile with first card (doesn't return payment profile IDs) try: auth_profile_id, _ = payment_service.create_customer_profile(customer, card_info) except ValueError as e: error_str = str(e) logger.error(f"API call failed: {error_str}") return { "success": False, "message": f"Failed to create customer profile: {error_str}", "profile_id": None, "error_detail": error_str, "is_duplicate": "E00039" in error_str } if not auth_profile_id: logger.error("No auth_profile_id returned from API") return { "success": False, "message": "Failed to create customer profile - no profile ID returned", "profile_id": None } # Add first payment profile to the customer profile try: first_payment_profile_id = payment_service.add_payment_profile_to_customer( auth_profile_id, customer, card_info, is_default=True ) logger.info(f"Successfully added first payment profile: {first_payment_profile_id} (default)") # Assign to first_card first_card.auth_net_payment_profile_id = first_payment_profile_id db.add(first_card) except ValueError as e: logger.error(f"Failed to add payment profile for first card: {str(e)}") return { "success": False, "message": f"Failed to add first payment profile: {str(e)}", "profile_id": None } # Create additional payment profiles for additional cards for card in cards[1:]: try: # Format expiration date for string values exp_year = card.expiration_year.zfill(4) if len(card.expiration_year) < 4 else card.expiration_year exp_month = card.expiration_month.zfill(2) if len(card.expiration_month) < 2 else card.expiration_month exp_date = f"{exp_year}-{exp_month}" card_info_additional = schemas.CardCreate( card_number=card.card_number, expiration_date=exp_date, cvv=card.security_number ) # create_customer_payment_profile DOES return the payment profile ID payment_profile_id = payment_service.add_payment_profile_to_customer( auth_profile_id, customer, card_info_additional, is_default=False ) logger.info(f"Successfully added additional payment profile ID '{payment_profile_id}' for card {card.id}") except ValueError as e: logger.error(f"Failed to add payment profile for additional card {card.id}: {str(e)}") else: auth_profile_id = customer.auth_net_profile_id logger.info(f"Using existing Authorize.net profile {auth_profile_id}") # RETRIEVE ALL PAYMENT PROFILE IDs - This is the key step try: payment_profile_ids = payment_service.get_customer_payment_profiles(auth_profile_id) logger.info(f"DEBUG: Retrieved {len(payment_profile_ids)} payment profile IDs: {payment_profile_ids}") except ValueError as e: logger.error(f"Failed to retrieve payment profiles: {str(e)}") return { "success": False, "message": f"Failed to retrieve payment profiles: {str(e)}", "profile_id": None } # Assign payment profile IDs to cards num_to_update = min(len(cards), len(payment_profile_ids)) logger.info(f"Assigning {num_to_update} payment profile IDs to 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)})") logger.warning("This could cause incorrect payment profile assignments!") cards_updated = 0 for i in range(num_to_update): if payment_profile_ids[i] and str(payment_profile_ids[i]).strip(): # Validate the ID exists and isn't empty cards[i].auth_net_payment_profile_id = str(payment_profile_ids[i]) # Ensure string db.add(cards[i]) logger.info(f"Successfully assigned payment profile ID '{payment_profile_ids[i]}' to card {cards[i].id}") cards_updated += 1 else: logger.error(f"Missing or invalid payment profile ID '{payment_profile_ids[i]}' for card {cards[i].id}") # Save customer profile ID if not set (handle both new and existing case) if not customer.auth_net_profile_id: customer.auth_net_profile_id = auth_profile_id db.add(customer) # Commit all changes db.commit() logger.info(f"Successfully committed payment profile IDs to database ({cards_updated} cards updated)") # Enhanced verification - check what was actually saved logger.info("Verifying payment profile IDs were saved correctly:") all_saved_correctly = True for i, card in enumerate(cards[:num_to_update]): committed_card = crud.get_card_by_id(db, card.id) if committed_card and committed_card.auth_net_payment_profile_id: logger.info(f"SUCCESS: Card {card.id} has payment profile ID '{committed_card.auth_net_payment_profile_id}'") else: logger.error(f"ERROR: Card {card.id} is missing payment profile ID") all_saved_correctly = False if not all_saved_correctly: logger.error("PAYMENT PROFILE ASSIGNMENT ERRORS DETECTED - This may cause transaction failures!") operation_type = "created" if not original_profile_id else "updated" logger.info(f"Successfully {operation_type} Authorize.net profile {auth_profile_id} for customer {customer_id} with {len(cards)} cards") # 🔄 PROACTIVELY REFRESH PAYMENT PROFILES TO ENSURE VALIDITY logger.info(f"🔄 Auto-refresh START: customer_id={customer_id}, auth_profile_id={auth_profile_id}") logger.info(f"🔄 Auto-refresh BEFORE: Cards have these payment profile IDs: {[f'card_{c.id}={c.auth_net_payment_profile_id}' for c in cards]}") # Check what changed after refresh cards_after = crud.get_customer_cards(db, customer_id) logger.info(f"🔄 Auto-refresh AFTER: Cards now have these payment profile IDs: {[f'card_{c.id}={c.auth_net_payment_profile_id}' for c in cards_after]}") logger.info(f"🔄 Auto-refresh COMPLETE - IDs changed: {len([c for c in cards if c.auth_net_payment_profile_id != cards_after[cards.index(c)].auth_net_payment_profile_id])} cards updated") return { "success": True, "message": f"Successfully {operation_type} Authorize.net account with profile ID {auth_profile_id} (profiles auto-refreshed)", "profile_id": auth_profile_id, "total_cards_updated": cards_updated } except Exception as e: logger.error(f"Critical exception during user account creation for customer {customer_id}: {traceback.format_exc()}") db.rollback() return { "success": False, "message": f"An unexpected error occurred: {str(e)}", "profile_id": None }