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() # Set Authorize.net environment based on configuration if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION': #constants.environment = constants.PRODUCTION print("Constants:", ApplicationConfig.CURRENT_SETTINGS) print("Authorize.Net URL:", constants.environment) API_LOGIN_ID = '4d2Mn6H23R' TRANSACTION_KEY = '7B94d8xfTQXv37WS' # Override to standard production endpoint constants.environment = "https://api.authorize.net/xml/v1/request.api" print("Overridden Authorize.Net URL:", constants.environment) else: print("Constants:", ApplicationConfig.CURRENT_SETTINGS) constants.environment = constants.SANDBOX print("Authorize.Net URL:", constants.environment) API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY 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 } print(customer) # 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 # Convert to string first to handle cases where database returns int instead of string exp_year_str = str(first_card.expiration_year) exp_month_str = str(first_card.expiration_month) expiration_year = exp_year_str.zfill(4) if len(exp_year_str) < 4 else exp_year_str expiration_month = exp_month_str.zfill(2) if len(exp_month_str) < 2 else exp_month_str 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 # 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_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 } def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profile_id: str) -> bool: """ Refresh payment profiles for a customer by syncing from Authorize.net to database. This ensures database payment_profile_ids stay in sync with Authorize.net. NOW WITH RECREATION FALLBACK: If no payment profiles exist in Authorize.net, recreates them from stored card data instead of failing. Args: db: Database session customer_id: ID of the customer auth_profile_id: Authorize.net customer profile ID Returns: bool: True if refresh successful, False otherwise """ try: # Import here to avoid circular imports from .. import crud # Get customer's current cards from database cards_before = crud.get_customer_cards(db, customer_id) customer = crud.get_customer(db, customer_id) logger.info(f"🔄 Refresh START: customer_id={customer_id}, profile_id={auth_profile_id}, current cards={len(cards_before)}") # STEP 1: Try to get actual payment profiles from Authorize.net payment_profile_ids = [] try: payment_profile_ids = payment_service.get_customer_payment_profiles(auth_profile_id) logger.info(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}") except Exception as e: logger.warning(f"🔄 Could not retrieve payment profiles from Authorize.net: {str(e)}") logger.info("🔄 Will attempt to recreate missing payment profiles") # STEP 2: Check if we have enough payment profiles for our cards cards_need_update = [] for card in cards_before: if not card.auth_net_payment_profile_id or card.auth_net_payment_profile_id.strip() == "": cards_need_update.append(card) logger.info(f"🔄 Card {card.id} needs payment profile ID assignment") 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 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") else: # Profile exists in Authorize.net, but let's double-check it's usable by doing a quick test logger.info(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - testing usability...") try: test_req = schemas.TransactionAuthorizeByCardID( card_id=card.id, preauthorize_amount="0.01" ) test_response = payment_service.authorize_customer_profile( customer_profile_id=customer.auth_net_profile_id, payment_profile_id=card.auth_net_payment_profile_id, transaction_req=test_req, db_session=None, customer_id=None, card_id=None ) # Check test result _, _, test_reason = payment_service._parse_authnet_response(test_response) if "E00121" in str(test_reason): 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") # Explicitly delete the corrupted profile first try: from . import user_delete delete_success = user_delete._delete_payment_profile(customer.auth_net_profile_id, card.auth_net_payment_profile_id) if delete_success: logger.info(f"🔄 Successfully deleted corrupted payment profile {card.auth_net_payment_profile_id}") card.auth_net_payment_profile_id = None db.add(card) except Exception as del_e: logger.warning(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}") else: logger.debug(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}") 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") # STEP 3: If we don't have enough valid payment profiles, recreate missing ones if len(cards_need_update) > 0: logger.info(f"🔄 Need to recreate {len(cards_need_update)} payment profiles") # Clear payment profile IDs for cards that need recreation (they're invalid anyway) for card in cards_need_update: if card.auth_net_payment_profile_id: logger.info(f"🔄 Clearing invalid payment profile ID {card.auth_net_payment_profile_id} for card {card.id}") card.auth_net_payment_profile_id = None db.add(card) # Recreate payment profiles for cards that need them recreated_cards = [] for card in cards_need_update: try: # Format expiration date 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 ) logger.info(f"🔄 Recreating payment profile for card {card.id} (**** **** **** {card.last_four_digits})") new_payment_profile_id = payment_service.add_payment_profile_to_customer( auth_profile_id, customer, card_create_data, is_default=(card.main_card == True) ) if new_payment_profile_id: card.auth_net_payment_profile_id = str(new_payment_profile_id) db.add(card) recreated_cards.append(card) logger.info(f"✅ Successfully recreated payment profile {new_payment_profile_id} for card {card.id}") else: logger.error(f"❌ Failed to recreate payment profile for card {card.id} - no ID returned") except Exception as e: logger.error(f"❌ Failed to recreate payment profile for card {card.id}: {str(e)}") continue if recreated_cards: db.commit() logger.info(f"✅ Successfully recreated and saved {len(recreated_cards)} payment profiles") else: logger.error("❌ No payment profiles could be recreated - this is a critical failure") return False else: logger.info(f"🔄 All {len(cards_before)} cards have valid payment profile IDs") # STEP 4: Final verification that everything looks good cards_final = crud.get_customer_cards(db, customer_id) logger.info("🔄 FINAL VERIFICATION:") all_valid = True for card in cards_final: status = "✅ VALID" if card.auth_net_payment_profile_id and card.auth_net_payment_profile_id.strip() else "❌ INVALID" logger.info(f"🔄 {status} Card {card.id}: auth_net_payment_profile_id='{card.auth_net_payment_profile_id}'") if not card.auth_net_payment_profile_id or card.auth_net_payment_profile_id.strip() == "": all_valid = False if all_valid: logger.info(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs") return True else: logger.warning("🔄 Refresh PARTIAL: Some cards may still have invalid payment profile IDs") return False except Exception as e: logger.error(f"🔄 Refresh FAILED for customer {customer_id}: {str(e)}") logger.error(f"🔄 Refresh traceback: {traceback.format_exc()}") db.rollback() return False