261 lines
12 KiB
Python
261 lines
12 KiB
Python
## File: your_app/views.py
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from typing import Tuple, Optional
|
|
import enum
|
|
|
|
from .. import crud, models, schemas, database
|
|
from ..services import payment_service
|
|
import logging
|
|
|
|
|
|
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 is not None and hasattr(response, 'messages') and 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.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.
|
|
"""
|
|
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")
|
|
|
|
# Add CRITICAL DEBUGGING to see exactly what's in the database
|
|
print(f"ROUTER DEBUG: Customer ID: {customer_id}")
|
|
print(f"ROUTER DEBUG: db_customer: {db_customer}")
|
|
print(f"ROUTER DEBUG: db_customer.auth_net_profile_id: '{db_customer.auth_net_profile_id}' (type: {type(db_customer.auth_net_profile_id)})")
|
|
print(f"ROUTER DEBUG: db_card: {db_card}")
|
|
print(f"ROUTER DEBUG: db_card.auth_net_payment_profile_id: '{db_card.auth_net_payment_profile_id}' (type: {type(db_card.auth_net_payment_profile_id)})")
|
|
|
|
# Check for specific problem values
|
|
if db_card.auth_net_payment_profile_id is None:
|
|
print("ROUTER DEBUG: CRITICAL - payment_profile_id is None - this will cause E00121!")
|
|
elif db_card.auth_net_payment_profile_id == "":
|
|
print("ROUTER DEBUG: CRITICAL - payment_profile_id is empty string - this will cause E00121!")
|
|
elif str(db_card.auth_net_payment_profile_id).lower() == "none":
|
|
print("ROUTER DEBUG: CRITICAL - payment_profile_id is string 'None' - this will cause E00121!")
|
|
else:
|
|
print(f"ROUTER DEBUG: payment_profile_id appears valid: '{db_card.auth_net_payment_profile_id}'")
|
|
|
|
if not db_customer.auth_net_profile_id or not db_card.auth_net_payment_profile_id:
|
|
print(f"ROUTER DEBUG: WILL THROW HTTP 400 ERROR: auth_net_profile_id='{db_customer.auth_net_profile_id}', payment_profile_id='{db_card.auth_net_payment_profile_id}'")
|
|
raise HTTPException(status_code=400, detail="Payment profile is not set up correctly for this customer/card")
|
|
|
|
# Call the service function for authorization with auto-recovery enabled
|
|
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, # For auto-recovery
|
|
customer_id=customer_id, # For auto-recovery
|
|
card_id=db_card.id # For auto-recovery
|
|
)
|
|
|
|
status, auth_net_transaction_id, rejection_reason = _parse_authnet_response(auth_net_response)
|
|
|
|
# Create the transaction record in your database with the correct type
|
|
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,
|
|
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
|
|
)
|
|
|
|
# --- CAPTURE ENDPOINT MOVED TO TRANSACTION ROUTER ---
|