Working flow authorize

This commit is contained in:
2025-09-16 12:45:22 -04:00
parent 47e3fb443b
commit 630584512e
5 changed files with 132 additions and 61 deletions

View File

@@ -47,21 +47,53 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
status = TransactionStatus.DECLINED
auth_net_transaction_id = None
rejection_reason = "Payment declined by gateway."
print("DEBUG: Full response object")
print(response)
print("DEBUG: response.messages")
print(response.messages)
print("DEBUG: response.messages.resultCode")
print(response.messages.resultCode)
if response is not None:
if hasattr(response, 'transactionResponse') and response.transactionResponse and hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors:
print("DEBUG: Using transactionResponse.errors")
error = response.transactionResponse.errors[0]
rejection_reason = f"{error.errorCode.text}: {error.errorText.text}"
elif hasattr(response, 'messages') and response.messages and hasattr(response.messages, 'message') and response.messages.message:
print("DEBUG: Using response.messages.message")
msg = response.messages.message[0]
rejection_reason = f"{msg.code.text}: {msg.text.text}"
print("DEBUG: msg object")
print(msg)
print("DEBUG: msg attributes")
print(dir(msg))
print("DEBUG: msg.code")
print(getattr(msg, 'code', 'NO code ATTR'))
print("DEBUG: msg.text")
print(getattr(msg, 'text', 'NO text ATTR'))
code_val = None
text_val = None
if hasattr(msg, 'code') and msg.code is not None and hasattr(msg.code, 'text'):
code_val = msg.code.text
elif hasattr(msg, 'code'):
code_val = str(msg.code)
if hasattr(msg, 'text') and msg.text is not None and hasattr(msg.text, 'text'):
text_val = msg.text.text
elif hasattr(msg, 'text'):
text_val = str(msg.text)
rejection_reason = f"{code_val}: {text_val}" if code_val and text_val and text_val != "None" else f"{code_val}" if code_val else f"Error: {getattr(msg, 'text', 'Unknown error')}"
print("DEBUG: Constructed rejection_reason")
print(rejection_reason)
return status, auth_net_transaction_id, rejection_reason
@router.post("/customers/{customer_id}/cards", response_model=schemas.CustomerCardResponse, summary="Add a new payment card for a customer")
@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:
@@ -69,9 +101,9 @@ def add_card_to_customer(customer_id: int, card_info: schemas.CardCreate, db: Se
# 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:
@@ -86,33 +118,15 @@ def add_card_to_customer(customer_id: int, card_info: schemas.CardCreate, db: Se
customer=customer_schema,
card_info=card_info
)
# This creates the card in our local database
new_card = crud.create_customer_card(
db=db,
customer_id=customer_id,
card_info=card_info,
payment_profile_id=payment_profile_id
)
# ========= THIS IS THE FIX FOR THE FRONTEND =========
# 1. Convert the newly created card object into a Pydantic model, then a dictionary.
# Make sure your schemas.Card uses `user_id` to match your model.
response_data = schemas.Card.from_orm(new_card).model_dump()
# 2. Manually add the 'customer_state' field that the frontend needs.
response_data['customer_state'] = "MA"
# 3. Return the complete dictionary. FastAPI validates it against CustomerCardResponse
# and sends it to the frontend.
return response_data
# 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
logger.error(f"An unexpected error occurred: {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")
@@ -120,7 +134,7 @@ def charge_saved_card(customer_id: int, transaction_req: schemas.TransactionCrea
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.customer_id != customer_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:
@@ -190,25 +204,4 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
auth_net_transaction_id=auth_net_transaction_id
)
# --- YOUR EXISTING CAPTURE ENDPOINT NEEDS NO CHANGES ---
@router.post("/capture/", response_model=schemas.Transaction, summary="Capture a previously authorized amount")
def capture_authorized_amount(transaction: schemas.TransactionCapture, db: Session = Depends(database.get_db)):
# This endpoint continues to work perfectly.
# It finds the original transaction by its ID and captures the funds.
auth_transaction = crud.get_transaction_by_auth_id(db, auth_net_transaction_id=transaction.auth_net_transaction_id)
if not auth_transaction:
raise HTTPException(status_code=404, detail="Authorization transaction not found")
# ... The rest of your existing capture logic remains the same ...
auth_net_response = payment_service.capture_authorized_transaction(transaction)
status, _, rejection_reason = _parse_authnet_response(auth_net_response) # The capture response doesn't return a new ID
# Use your existing CRUD function to update the transaction
return crud.update_transaction_for_capture(
db=db,
auth_net_transaction_id=transaction.auth_net_transaction_id,
charge_amount=transaction.charge_amount,
status=status,
rejection_reason=rejection_reason
)
# --- CAPTURE ENDPOINT MOVED TO TRANSACTION ROUTER ---