Skip to content

Commit 4502b4b

Browse files
authored
Merge pull request #10 from buserbrasil/update-readme-and-authors
Update authors, readme and data consistency
2 parents 3a4f7e2 + 5652e3e commit 4502b4b

File tree

8 files changed

+123
-186
lines changed

8 files changed

+123
-186
lines changed

README.MD

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,28 +16,51 @@ pip install santander-python-sdk
1616
```python
1717
from decimal import Decimal
1818
from santander_sdk import SantanderApiClient, SantanderClientConfiguration
19+
from santander_sdk.pix import transfer_pix_payment, get_transfer
1920

21+
22+
# Setup do client
2023
client = SantanderApiClient(SantanderClientConfiguration(
2124
client_id="client_id",
2225
client_secret="client_pk",
2326
cert="certificate_path",
24-
base_url="api_url"
27+
base_url="api_url",
28+
workspace_id="optional"
2529
))
2630

27-
# Realizar um PIX para uma chave
31+
# Exemplo 1 - PIX para uma chave (Telefone, email, chave aleatória, cpf ou cpnj)
2832
transfer = transfer_pix_payment(
2933
client,
30-
pix_info="[email protected]", # PIX key
34+
pix_key="[email protected]",
3135
value=Decimal(0.99),
3236
description="My first pix payment"
3337
)
3438

35-
pix_info = get_transfer(transfer["id"])
36-
# ...
37-
```
39+
# Exemplo 2 - Transferência pix via beneficiário:
40+
benefiary = SantanderBeneficiary(
41+
name="John Doe",
42+
bankCode="404",
43+
branch="2424",
44+
number="123456789", # Número da conta com dígito verificador
45+
type="CONTA_CORRENTE",
46+
documentType="CPF",
47+
documentNumber="12345678909",
48+
)
49+
50+
transfer = transfer_pix_payment(
51+
client,
52+
benefiary,
53+
value=Decimal(0.99),
54+
description="My second pix payment by beneficiary"
55+
)
56+
3857

39-
## Em desenvolvimento
40-
- Será atualizado o README
58+
# Exemplo 3 - Consulta de um pix realizado
59+
transfer = get_transfer(transfer["id"])
60+
assert transfer["status"] == "PAYED"
61+
62+
63+
```
4164

4265
## Funcionalidades
4366

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ dynamic = ["version"]
44
description = "Client não oficial da API do Santander em Python"
55
authors = [
66
{ name = "Samuel Rodrigues Coelho", email = "[email protected]" },
7+
{ name = "Erle Carrara", email = "[email protected]" },
8+
{ name = "Walison Filipe", email = "[email protected]" },
79
]
810
readme = "README.md"
911
keywords = ["santander", "api", "client", "python"]

santander_sdk/api_client/helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def convert_to_decimal(cents: int) -> Decimal:
142142
return Decimal(cents) / 100
143143

144144

145-
def document_type(document_number: str) -> str:
145+
def document_type(document_number: str) -> Literal["CPF", "CNPJ"]:
146146
if len(document_number) == 11:
147147
return "CPF"
148148
if len(document_number) == 14:

santander_sdk/pix.py

Lines changed: 29 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,12 @@
1313
)
1414

1515
from santander_sdk.api_client.helpers import (
16-
document_type,
1716
get_pix_key_type,
1817
retry_one_time_on_request_exception,
1918
truncate_value,
2019
)
2120
from santander_sdk.types import (
22-
BeneficiaryDataDict,
21+
SantanderBeneficiary,
2322
ConfirmOrderStatus,
2423
CreateOrderStatus,
2524
OrderStatus,
@@ -35,24 +34,17 @@
3534
MAX_UPDATE_STATUS_ATTEMPTS_TO_CONFIRM = 120
3635
PIX_CONFIRM_INTERVAL_TIME = 2
3736

38-
TYPE_ACCOUNT_MAP = {
39-
"savings": "CONTA_POUPANCA",
40-
"payment": "CONTA_PAGAMENTO",
41-
"checking": "CONTA_CORRENTE",
42-
}
43-
44-
4537
def transfer_pix_payment(
4638
client: SantanderApiClient,
47-
pix_info: str | BeneficiaryDataDict,
39+
pix_key: str | SantanderBeneficiary,
4840
value: D,
4941
description: str,
5042
tags: list[str] = [],
5143
) -> TransferPixResult:
5244
"""Realiza uma transferência PIX para uma chave PIX ou para um beneficiário
5345
- Se for informado uma chave PIX, o valor deve ser uma string com a chave CPF, CNPJ, EMAIL, CELULAR ou chave aleatória
5446
- CELULAR deve ser informado no formato +5511912345678 (14 caracteres incluindo o +)
55-
- Se for informado um beneficiário, o valor deve ser BeneficiaryDataDict com os dados do beneficiário
47+
- Se for informado um beneficiário, o valor deve ser SantanderBeneficiary com os dados do beneficiário
5648
5749
### Retorno de sucesso:
5850
- success: True se a transferência foi realizada com sucesso
@@ -69,7 +61,7 @@ def transfer_pix_payment(
6961
)
7062

7163
create_pix_response = _request_create_pix_payment(
72-
client, pix_info, value, description, tags
64+
client, pix_key, value, description, tags
7365
)
7466
pix_id = create_pix_response.get("id")
7567
logger.info("Santander - PIX criado com sucesso: {pix_id}")
@@ -94,6 +86,14 @@ def transfer_pix_payment(
9486
return {"success": False, "error": error_message, "data": None}
9587

9688

89+
def get_transfer(client: SantanderApiClient, pix_payment_id: str) -> SantanderPixResponse:
90+
if not pix_payment_id:
91+
raise SantanderValueErrorException("pix_payment_id não informado")
92+
93+
response = client.get(f"{PIX_ENDPOINT}/{pix_payment_id}")
94+
return cast(SantanderPixResponse, response)
95+
96+
9797
def _pix_payment_status_polling(
9898
client: SantanderApiClient,
9999
pix_id: str,
@@ -185,48 +185,32 @@ def _confirm_pix_payment(
185185

186186
def _request_create_pix_payment(
187187
client: SantanderApiClient,
188-
pix_info: BeneficiaryDataDict | str,
188+
pix_key: SantanderBeneficiary | str,
189189
value: D,
190190
description: str,
191191
tags: list[str] = [],
192192
) -> SantanderPixResponse:
193-
"""Cria uma ordem de pagamento. Caso o status seja REJECTED, a exceção SantanderRejectedTransactionException é lançada.
194-
Regra de negócio aqui: pagamento por beneficiário na request deve ser informado o bank_code ou ispb, nunca os dois."""
193+
"""Cria uma ordem de pagamento. Caso o status seja REJECTED, a exceção SantanderRejectedTransactionException é lançada."""
195194
data = {
196195
"tags": tags,
197196
"paymentValue": truncate_value(value),
198197
"remittanceInformation": description,
199198
}
200-
if isinstance(pix_info, str):
201-
pix_type = get_pix_key_type(pix_info)
202-
data.update({"dictCode": pix_info, "dictCodeType": pix_type})
203-
elif isinstance(pix_info, dict):
204-
try:
205-
beneficiary = {
206-
"branch": pix_info["bank_account"]["agencia"],
207-
"number": f"{pix_info['bank_account']['conta']}{pix_info['bank_account']['conta_dv']}",
208-
"type": TYPE_ACCOUNT_MAP[pix_info["bank_account"]["tipo_conta"]],
209-
"documentType": document_type(
210-
pix_info["bank_account"]["document_number"]
211-
),
212-
"documentNumber": pix_info["bank_account"]["document_number"],
213-
"name": pix_info["recebedor"]["name"],
214-
}
215-
bank_account = pix_info["bank_account"]
216-
bank_code = bank_account.get("bank_code_compe", "")
217-
bank_ispb = bank_account.get("bank_code_ispb", "")
218-
if bank_code:
219-
beneficiary["bankCode"] = bank_code
220-
elif bank_ispb:
221-
beneficiary["ispb"] = bank_ispb
222-
else:
223-
raise SantanderValueErrorException("A chave de entrada é inválida")
224-
225-
data.update({"beneficiary": beneficiary})
226-
except KeyError as e:
227-
raise SantanderValueErrorException(
228-
f"Campo obrigatório não informado para o beneficiário: {e}"
229-
)
199+
if isinstance(pix_key, str):
200+
pix_type = get_pix_key_type(pix_key)
201+
data.update({"dictCode": pix_key, "dictCodeType": pix_type})
202+
elif isinstance(pix_key, dict):
203+
beneficiary = cast(dict, pix_key.copy())
204+
bank_code = pix_key.get("bankCode", "")
205+
ispb = pix_key.get("ispb", "")
206+
207+
if bank_code and ispb:
208+
"Deve ser informado o bankCode ou ispb, nunca os dois."
209+
del beneficiary["ispb"]
210+
elif not bank_code and not ispb:
211+
raise SantanderValueErrorException("Deve ser informado 'bankCode' ou 'ispb'")
212+
213+
data.update({"beneficiary": beneficiary})
230214
else:
231215
raise SantanderValueErrorException("Chave PIX ou Beneficiário não informado")
232216

santander_sdk/types.py

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ class SantanderBeneficiary(TypedDict):
6060
name: str
6161
documentType: Literal["CPF", "CNPJ"]
6262
documentNumber: str
63-
bankCode: str
64-
ispb: str
63+
bankCode: str | None
64+
ispb: str | None
6565
branch: str
6666
number: str
6767
type: Literal["CONTA_CORRENTE", "CONTA_POUPANCA", "CONTA_PAGAMENTO"]
@@ -159,27 +159,6 @@ class SantanderTransferResponse(TypedDict):
159159
beneficiary: SantanderBeneficiary | None
160160

161161

162-
class BankAccountDict(TypedDict):
163-
agencia: str
164-
conta: str
165-
conta_dv: str
166-
tipo_conta: Literal["checking", "savings", "salary", "payment"]
167-
document_number: str
168-
bank_code_compe: str | None
169-
bank_code_ispb: str | None
170-
171-
172-
class ReceiverDataDict(BankAccountDict):
173-
name: str
174-
175-
176-
class BeneficiaryDataDict(TypedDict):
177-
"""Dados do beneficiário para transferência PIX"""
178-
179-
"Dados do recebedor para transferência PIX"
180-
bank_account: BankAccountDict
181-
recebedor: ReceiverDataDict
182-
183162

184163
SantanderPixResponse = SantanderTransferResponse | SantanderAPIErrorResponse
185164

0 commit comments

Comments
 (0)