Ошибка Gocardless 403 Запрещена во время создания пользователей (работает в песочнице, но не удается в живой среде)Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка Gocardless 403 Запрещена во время создания пользователей (работает в песочнице, но не удается в живой среде)

Сообщение Anonymous »

Я использую API без Gocard для создания клиентов и мандатов, и код отлично работает в среде песочницы. Однако, когда я переключаюсь в живую среду, я получаю запрещенную ошибку 403 во время создания клиентов. < /P>

Код: Выделить всё

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}")
Среда песочницы: процесс создания клиентов работает отлично, и я могу создавать клиентов и мандаты без каких -либо проблем.
Живая среда: я получаю запрету>

Подробнее здесь: https://stackoverflow.com/questions/791 ... -but-fails
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Ошибка GoCardless 403, запрещена при создании пользователя (работает в песочнице, но не работает в реальной среде)
    Anonymous » » в форуме Python
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Laravel 5.4 -> запрещена ошибка 403 для файлов в хранилище с «публичной» видимостью
    Anonymous » » в форуме Php
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • API Fetch API для удаленного входа (POST) — ошибка 403 запрещена
    Anonymous » » в форуме Javascript
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • PHP Gocardless Pro Unaught Ошибка: класс "gocardlesspro \ client" не найден
    Anonymous » » в форуме Php
    0 Ответы
    2 Просмотры
    Последнее сообщение Anonymous
  • Подпись hmac PHP gocardless не совпадает
    Anonymous » » в форуме Php
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»