Skip to content

Commit

Permalink
cliente api
Browse files Browse the repository at this point in the history
  • Loading branch information
mariofix committed Dec 14, 2024
1 parent 3c27a01 commit 3513f96
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 12 deletions.
19 changes: 14 additions & 5 deletions django_payments_chile/FlowProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from payments.core import BasicProvider, get_base_url
from payments.forms import PaymentForm as BasePaymentForm

from .clientes import ClienteAPI


class FlowProvider(BasicProvider):
"""
Expand Down Expand Up @@ -63,9 +65,9 @@ def get_form(self, payment, data: Optional[dict] = None) -> Any:
if not payment.transaction_id:
datos_para_flow = {
"apiKey": self.api_key,
"commerceOrder": payment.token,
"commerceOrder": str(payment.token),
"urlReturn": payment.get_success_url(),
"urlConfirmation": f"{get_base_url()}{payment.get_process_url()}",
"urlConfirmation": payment.get_process_url(),
"subject": payment.description,
"amount": int(payment.total),
"paymentMethod": self.api_medio,
Expand All @@ -83,9 +85,10 @@ def get_form(self, payment, data: Optional[dict] = None) -> Any:
except Exception as e: # noqa
# Dificil llegar acá, y si llegamos es problema de django-payments
raise PaymentError(f"Ocurrió un error al guardar attrs.datos_flow: {e}") # noqa

firma_datos = ...
datos_para_flow = dict(sorted(datos_para_flow.items()))
firma_datos = ClienteAPI.genera_firma(datos_para_flow, self.api_secret)
datos_para_flow.update({"s": firma_datos})
print(f"{datos_para_flow = }")
try:
pago_req = requests.post(f"{self.api_endpoint}/payment/create", data=datos_para_flow, timeout=5)
pago_req.raise_for_status()
Expand Down Expand Up @@ -135,9 +138,15 @@ def actualiza_estado(self, payment) -> dict:
Returns:
dict: Diccionario con valores del objeto `PaymentStatus`.
"""
datos_para_flow = {"apiKey": self.api_key, "token": payment.token}
datos_para_flow = dict(sorted(datos_para_flow.items()))
firma_datos = ClienteAPI.genera_firma(datos_para_flow, self.api_secret)
datos_para_flow.update({"s": firma_datos})
print(f"{datos_para_flow = }")

try:
# status = FlowPayment.getStatus(self._client, payment.transaction_id)
estado_req = requests.post(f"{self.api_endpoint}/payment/getStatus", timeout=5)
estado_req = requests.get(f"{self.api_endpoint}/payment/getStatus", data=datos_para_flow, timeout=5)
estado_req.raise_for_status()

except Exception as e:
Expand Down
12 changes: 12 additions & 0 deletions django_payments_chile/clientes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import hashlib
import hmac
from dataclasses import dataclass


@dataclass
class ClienteAPI:
@classmethod
def genera_firma(cls, datos: list, secret_key: str):
datos_flow = "".join(f"{str(key)}{str(value)}" for key, value in datos.items())
firma = hmac.new(key=secret_key.encode(), msg=datos_flow.encode(), digestmod=hashlib.sha256)
return firma.hexdigest()
12 changes: 6 additions & 6 deletions tests/test_flowprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def get_success_url(self):

class TestFlowProviderLive(TestCase):
def test_provider_create_session_success(self):
payment = Payment()
test_payment = Payment()
provider = FlowProvider(api_key=API_KEY, api_secret=API_SECRET)
with patch("django_payments_chile.FlowProvider.requests.post") as mock_post:
# Configure mock response
Expand All @@ -57,12 +57,12 @@ def test_provider_create_session_success(self):
mock_post.return_value = mock_response

with self.assertRaises(RedirectNeeded):
provider.get_form(payment)
provider.get_form(test_payment)

self.assertEqual(payment.status, PaymentStatus.WAITING)
self.assertEqual(payment.attrs.respuesta_flow["url"], "https://flow.cl")
self.assertEqual(payment.attrs.respuesta_flow["token"], "TOKEN_ID")
self.assertEqual(payment.attrs.respuesta_flow["flowOrder"], "ORDER_ID")
self.assertEqual(test_payment.status, PaymentStatus.WAITING)
self.assertEqual(test_payment.attrs.respuesta_flow["url"], "https://flow.cl")
self.assertEqual(test_payment.attrs.respuesta_flow["token"], "TOKEN_ID")
self.assertEqual(test_payment.attrs.respuesta_flow["flowOrder"], "ORDER_ID")

def test_provider_create_session_error(self):
payment = Payment()
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ deps=
extras=
transkbank-sdk
commands=
pytest -v {posargs}
pytest -vs {posargs}
coverage xml

[gh-actions]
Expand Down

0 comments on commit 3513f96

Please sign in to comment.