Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cartão Cancelado perde dados #457

Open
anhaabaete opened this issue Jul 31, 2024 · 5 comments
Open

Cartão Cancelado perde dados #457

anhaabaete opened this issue Jul 31, 2024 · 5 comments
Labels

Comments

@anhaabaete
Copy link

Olá a todos,

perdi meu cartão e ao obter o novo, todos os dados relacionado com aquele cartão foi perdido.
Ou eu não sei onde foi parar, mas eu controlava tudo antes.
Portanto eu precisava saber como pego o numero do cartão ou identificação única para separar o meu e da minha esposa, pois são da mesma conta

@andreroggeri
Copy link
Owner

Se você entrar no site do nubank você vê as suas transações daquele cartão?
Consegue postar um exemplo de como você está buscando as transações?

@anhaabaete
Copy link
Author

anhaabaete commented Jul 31, 2024

No app eu vejo, mas o porém é que preciso saber qual cartão. Acho que ao cancelar eles apagam a informação. Não sei...

O código a baixo:

#!/bin/python3

from pynubank import Nubank
nu = Nubank()
import json
import os
from meu_googlesheet import googlesheet
import sys


########################
# Dados gerais da fatura
########################
mesabertura = ''
mesfechamento = ''

if len(sys.argv) > 2:
    mesabertura = sys.argv[1]
    mesfechamento = sys.argv[2]
else:
    print("falta argumentos: meunu.py [inicio] [fim]")
    exit(0)


hereiam = os.path.expanduser( '~' ) + "/code/meunu"


print("Auntenticando...")
nu.authenticate_with_cert('xxxxxxxx', 'xxxxxxxxx', hereiam+'/cert.p12')




jsonstr=""
bills=[]




print("get_bills...")
bills = nu.get_bills()
bills = [x for x in bills if x["summary"]["open_date"][:7] == mesabertura 
                                and x["summary"]["close_date"][:7] == mesfechamento]

summary = bills[0]["summary"]
abertura = summary["open_date"]
fechamento = summary["close_date"]

#######################
# Registros de compras desabilitado, bills já contem compras (com menos detalhes)
#######################
#card_statements = nu.get_card_statements()

#card_statements = [x for x in card_statements if x["time"][:10] >= summary["open_date"] 
 #                                                   and x["time"][:10] <= summary["close_date"]]


#file = open('lancamento_cartao.json', 'w')
#file.write(json.dumps(card_statements, indent=2))
#file.close()



##############
# Pagamentos
##############
print("get_bill_details...")
bill_details = nu.get_bill_details(bills[0])
r = len(bill_details['bill']['line_items'])
for i in range(r):
    percentagem = str(int((i / r) * 100));
    print(percentagem + "% ", end="\r")
    momentbill = bill_details['bill']['line_items'][i]


    file = open(hereiam+'/dump.json', 'w')
    file.write(json.dumps(momentbill, indent=2))
    file.close()
    if momentbill.get('category')!='Pagamento' and momentbill.get("type")!='payment':
        if momentbill.get("href"):
            idbill = momentbill.get("href").replace('nuapp://transaction/','https://prod-s1-facade.nubank.com.br/api/transactions/')
        else:
            idbill = 'https://prod-s1-facade.nubank.com.br/api/transactions/' + momentbill.get("loan_id")
    
        momentbill["_links"] = {"self": {
            "href": idbill
        }}
        try:
            bill_more_detail=nu.get_card_statement_details(momentbill)
            momentbill["card_last_four_digits"] = bill_more_detail['transaction'].get('card_last_four_digits')
        except:
            print(momentbill)
            
        
        
        

print("Fineshed                          ")

file = open(hereiam+'/bills.json', 'w')
file.write(json.dumps(bill_details, indent=2))
file.close()


creditonu = nu.get_credit_card_balance()
creditonu = creditonu['available']/100

## Atualiza Folha de Calculo ###
print("Atualizando Folha de Calculo...")
googlesheet(abertura,fechamento,hereiam,creditonu)

Mais especificamente neste trecho:

file = open(hereiam+'/dump.json', 'w')
    file.write(json.dumps(momentbill, indent=2))
    file.close()
    if momentbill.get('category')!='Pagamento' and momentbill.get("type")!='payment':
        if momentbill.get("href"):
            idbill = momentbill.get("href").replace('nuapp://transaction/','https://prod-s1-facade.nubank.com.br/api/transactions/')
        else:
            idbill = 'https://prod-s1-facade.nubank.com.br/api/transactions/' + momentbill.get("loan_id")
    
        momentbill["_links"] = {"self": {
            "href": idbill
        }}
        try:
            bill_more_detail=nu.get_card_statement_details(momentbill)
            momentbill["card_last_four_digits"] = bill_more_detail['transaction'].get('card_last_four_digits')
        except:
            print(momentbill)
            ```
            
            

@anhaabaete
Copy link
Author

Talvez meu código esteja antigo ou sujo devido a ter feito a muito tempo, e ser apenas para minhas próprias contas. Eu só preciso do valor e do número cartão que fez a compra.

@andreroggeri
Copy link
Owner

andreroggeri commented Aug 1, 2024

Eu fiz um teste aqui e consegui recuperar os 4 ultimos digitos:

nu = Nubank()
nu.authenticate_with_cert(...)

transactions = nu.get_card_statements()

transaction = transactions[0]

details = nu.get_card_statement_details(transaction)

print(f'card_last_four_digits={details["transaction"]["card_last_four_digits"]}')

@anhaabaete
Copy link
Author

nu = Nubank()
nu.authenticate_with_cert(...)

transactions = nu.get_card_statements()

transaction = transactions[0]

details = nu.get_card_statement_details(transaction)

print(f'card_last_four_digits={details["transaction"]["card_last_four_digits"]}')

Agradeço Imensamente o código resumido.
Mas acho que eles tiram a referencia mesmo porque aparece isso:

Auntenticando...
Traceback (most recent call last):
  File "/home/tneves/code/meunu/a.py", line 14, in <module>
    details = nu.get_card_statement_details(transaction)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/tneves/.local/lib/python3.12/site-packages/pynubank/auth_mode.py", line 23, in wrapper
    return function(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/tneves/.local/lib/python3.12/site-packages/pynubank/nubank.py", line 202, in get_card_statement_details
    return self._client.get(statement['_links']['self']['href'])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/tneves/.local/lib/python3.12/site-packages/pynubank/utils/http.py", line 46, in get
    return self._handle_response(self.raw_get(url))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/tneves/.local/lib/python3.12/site-packages/pynubank/utils/http.py", line 35, in _handle_response
    raise NuRequestException(response)
pynubank.exception.NuRequestException: The request made failed with HTTP status code 400

Como se não existisse a referência.
Será que perde-se mesmo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants