[Python] GoCardless Error 403 Forbidden during User Creation (works in sandbox but fails in...

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using the GoCardless API to create customers and mandates, and the code works perfectly fine in the sandbox environment. However, when I switch to the live environment, I receive a 403 Forbidden error during customer creation.

    def create_gocardless_customer(self):
    self.ensure_one()
    try:
    print("Inizio processo di associazione/creazione cliente GoCardless") # Debug

    # Verifica dei campi obbligatori
    if not self.surname:
    raise UserError("Il campo 'Cognome' è obbligatorio.")
    if not self.pec and not self.email:
    raise UserError("Il campo 'Email' è obbligatorio.")
    if (not self.pec and ("@" not in self.email or "." not in self.email)) or (
    self.pec and ("@" not in self.pec or "." not in self.pec)):
    raise UserError("L'indirizzo email fornito non è valido.")
    if not self.iban:
    raise UserError("Il campo 'IBAN' è obbligatorio.")

    print("Campi obbligatori verificati") # Debug

    # Creazione del client GoCardless
    client = gocardless_pro.Client(
    access_token=token,
    environment='live'
    )
    print("Client GoCardless creato con successo") # Debug

    # Ricerca del cliente tramite email
    customer = None
    customers_list = client.customers.list()
    print("Lista clienti recuperata:", customers_list.records) # Stampa la lista dei clienti
    for existing_customer in customers_list.records:
    if existing_customer.email == (self.pec if self.pec else self.email):
    customer = existing_customer
    print(f"Cliente esistente trovato con ID: {customer.id}") # Debug
    self.id_gocardless = customer.id
    break

    # Creazione del cliente se non esiste
    if not customer:
    customer_data = {
    "given_name": self.name,
    "family_name": self.surname,
    "email": self.pec if self.pec else self.email,
    "address_line1": " ",
    "city": " ",
    "postal_code": " ",
    "country_code": "IT"
    }
    print(f"Creazione nuovo cliente con i seguenti dati: {customer_data}") # Debug
    customer = client.customers.create(params=customer_data)
    self.id_gocardless = customer.id
    self.env.cr.commit()

    # Verifica se esiste già un account bancario con lo stesso IBAN (utilizzando 'account_number_ending')
    existing_bank_accounts = client.customer_bank_accounts.list(params={"customer": customer.id})
    print("Lista account bancari per il cliente:",
    existing_bank_accounts.records) # Debug lista account bancari

    for account in existing_bank_accounts.records:
    print(f"Account number ending: {account.attributes['account_number_ending']}") # Debug

    matching_account = next(
    (account for account in existing_bank_accounts.records if
    account.attributes['account_number_ending'] == self.iban[-2:]),
    None
    )

    if matching_account:
    print(f"Account bancario esistente trovato con ID: {matching_account.attributes['id']}") # Debug
    self.bank_account_id = matching_account.attributes['id']
    # Verifica se esiste un mandato attivo
    existing_mandates = client.mandates.list(
    params={"customer_bank_account": matching_account.attributes['id']})
    print("Lista mandati per account bancario:", existing_mandates.records) # Debug lista mandati
    active_mandate = next(
    (mandate for mandate in existing_mandates.records if mandate.status == 'active'),
    None
    )
    if active_mandate:
    print(f"Mandato attivo esistente trovato con ID: {active_mandate.id}") # Debug
    self.mandato_id = active_mandate.id
    else:
    # Crea un nuovo mandato se non esiste un mandato attivo
    mandate_data = {
    "scheme": "sepa_core",
    "links": {
    "customer_bank_account": matching_account.attributes['id']
    }
    }
    mandate = client.mandates.create(params=mandate_data)
    print(f"Nuovo mandato creato con ID: {mandate.id}") # Debug
    self.mandato_id = mandate.id
    else:
    try:
    # Solo se non esiste un account bancario con lo stesso IBAN, creazione nuovo account bancario e mandato
    bank_account_data = {
    "iban": self.iban,
    "account_holder_name": f"{self.name} {self.surname}",
    "country_code": "IT",
    "links": {
    "customer": customer.id
    }
    }
    print(f"Creazione nuovo account bancario con i seguenti dati: {bank_account_data}") # Debug
    new_bank_account = client.customer_bank_accounts.create(params=bank_account_data)
    print(f"Nuovo account bancario creato con ID: {new_bank_account.id}") # Debug
    self.bank_account_id = new_bank_account.id
    mandate_data = {
    "scheme": "sepa_core",
    "links": {
    "customer_bank_account": new_bank_account.id
    }
    }
    mandate = client.mandates.create(params=mandate_data)
    print(f"Nuovo mandato creato con ID: {mandate.id}") # Debug
    self.mandato_id = mandate.id
    except Exception as e:
    if "Bank account already exists" in str(e):
    # Se l'account esiste già, recuperalo
    existing_bank_accounts = client.customer_bank_accounts.list(params={"customer": customer.id})
    matching_account = next(
    (account for account in existing_bank_accounts.records if
    account.attributes['account_number_ending'] == self.iban[-2:] and
    account.attributes['account_holder_name'] == f"{self.name} {self.surname}"),
    None
    )
    if matching_account:
    print(
    f"Account bancario esistente trovato con ID: {matching_account.attributes['id']} dopo errore di creazione") # Debug
    self.bank_account_id = matching_account.attributes['id']
    existing_mandates = client.mandates.list(
    params={"customer_bank_account": matching_account.attributes['id']})
    active_mandate = next(
    (mandate for mandate in existing_mandates.records if mandate.status == 'active'),
    None
    )
    if active_mandate:
    print(f"Mandato attivo esistente trovato con ID: {active_mandate.id}") # Debug
    self.mandato_id = active_mandate.id
    else:
    # Crea un nuovo mandato se non esiste un mandato attivo
    mandate_data = {
    "scheme": "sepa_core",
    "links": {
    "customer_bank_account": matching_account.attributes['id']
    }
    }
    mandate = client.mandates.create(params=mandate_data)
    print(f"Nuovo mandato creato con ID: {mandate.id}") # Debug
    self.mandato_id = mandate.id
    else:
    raise

    self.env.cr.commit()
    print("Operazione completata con successo") # Debug

    except PermissionsError as e:
    print(f"Errore di permessi GoCardless: {e}") # Debug
    raise UserError(f"Errore di permessi GoCardless: {e}")
    except InvalidApiUsageError as e:
    print(f"Errore di utilizzo API GoCardless: {e}") # Debug
    raise UserError(f"Errore di utilizzo API GoCardless: {e}")
    except InvalidStateError as e:
    print(f"Errore di stato GoCardless: {e}") # Debug
    raise UserError(f"Errore di stato GoCardless: {e}")
    except Exception as e:
    print(f"Errore GoCardless generico: {e}") # Debug
    raise UserError(f"Errore GoCardless: {e}")


    Sandbox environment: The customer creation process works perfectly, and I can create customers and mandates without any issues.

    Live environment: I receive a 403 Forbidden error when trying to create a customer.

    Continue reading...

Compartilhe esta Página