Skip to content

Commit

Permalink
commit(deps): bump actions/checkout from 2 to 4 (#1)
Browse files Browse the repository at this point in the history
* commit(deps): bump actions/checkout from 2 to 4

Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](actions/checkout@v2...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
dependabot[bot] and pre-commit-ci[bot] authored Dec 12, 2024
1 parent 8f04e64 commit 1331037
Show file tree
Hide file tree
Showing 7 changed files with 213 additions and 127 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions/setup-python@v3
- uses: pre-commit/action@v3.0.1
7 changes: 3 additions & 4 deletions khipu_tools/pykhipu/banks.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
# -*- coding: utf-8 -*-
import requests
from pykhipu.responses import BanksResponse


class Banks(object):
ENDPOINT = '/banks'
class Banks:
ENDPOINT = "/banks"

def __init__(self, client):
self.client = client

def get(self):
response = self.client.make_request('GET', self.ENDPOINT)
response = self.client.make_request("GET", self.ENDPOINT)
return BanksResponse.from_response(response)
100 changes: 57 additions & 43 deletions khipu_tools/pykhipu/client.py
Original file line number Diff line number Diff line change
@@ -1,121 +1,135 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import hmac
import logging
import os
import sys

import requests
import hmac
import logging

if sys.version_info.major < 3 or sys.version_info.minor < 9:
from importlib_metadata import version
else:
from importlib.metadata import version

from hashlib import sha256
from six.moves.urllib.parse import urlencode, quote
#from urllib.parse import urlencode, quote
from pykhipu.payments import Payments

from pykhipu.banks import Banks

# from urllib.parse import urlencode, quote
from pykhipu.payments import Payments
from pykhipu.receivers import Receivers
from urllib.parse import quote, urlencode

API_BASE = "https://khipu.com/api/2.0"
TRUE_LIST = [True, "True", "true", "TRUE", 1, "1"]
FALSE_LIST = [False, "False", "false", "FALSE", 0, "0"]

API_BASE = 'https://khipu.com/api/2.0'
TRUE_LIST = [True, 'True', 'true', 'TRUE', 1, '1']
FALSE_LIST = [False, 'False', 'false', 'FALSE', 0, '0']

class Client(object):
class Client:
def __init__(self, receiver_id=None, secret=None, debug=False):
self.receiver_id = receiver_id
self.secret = secret
self.is_debug = debug

@property
def receiver_id(self):
return self._receiver_id or os.getenv('KHIPU_RECEIVER_ID')
return self._receiver_id or os.getenv("KHIPU_RECEIVER_ID")

@receiver_id.setter
def receiver_id(self, value):
self._receiver_id = value

@property
def secret(self):
return self._secret or os.getenv('KHIPU_SECRET')
return self._secret or os.getenv("KHIPU_SECRET")

@secret.setter
def secret(self, value):
self._secret = value

@property
def is_debug(self):
return self._debug or (os.getenv('KHIPU_DEBUG') in TRUE_LIST)
return self._debug or (os.getenv("KHIPU_DEBUG") in TRUE_LIST)

@is_debug.setter
def is_debug(self, value):
self._debug = (
value in TRUE_LIST
and value not in FALSE_LIST
)

self._debug = value in TRUE_LIST and value not in FALSE_LIST

@property
def payments(self):
if not hasattr(self, '_payments'):
if not hasattr(self, "_payments"):
self._payments = Payments(self)
return self._payments

@property
def banks(self):
if not hasattr(self, '_banks'):
if not hasattr(self, "_banks"):
self._banks = Banks(self)
return self._banks

@property
def receivers(self):
if not hasattr(self, '_receivers'):
if not hasattr(self, "_receivers"):
self._receivers = Receivers(self)
return self._receivers

def __make_signature(self, method, url, params=None, data=None):
method_name = method.upper()
to_sign = '&'.join([method_name, quote(url, safe='')])
to_sign = "&".join([method_name, quote(url, safe="")])

def quote_items(tuples):
return ['='.join([quote(str(pair[0]), safe=''),
quote(str(pair[1]), safe='')]) for pair in tuples]
return [
"=".join([quote(str(pair[0]), safe=""), quote(str(pair[1]), safe="")])
for pair in tuples
]

if params:
sorted_items = sorted(params.items(), key = lambda item: item[0])
to_sign = '&'.join([to_sign,] + quote_items(sorted_items))
sorted_items = sorted(params.items(), key=lambda item: item[0])
to_sign = "&".join(
[
to_sign,
]
+ quote_items(sorted_items)
)
if data:
sorted_items = sorted(data.items(), key = lambda item: item[0])
to_sign = '&'.join([to_sign,] + quote_items(sorted_items))

hasher = hmac.new(self.secret.encode(), to_sign.encode('UTF-8'), digestmod=sha256)
signature = "{id}:{hash}".format(id=self.receiver_id,
hash=hasher.hexdigest())
sorted_items = sorted(data.items(), key=lambda item: item[0])
to_sign = "&".join(
[
to_sign,
]
+ quote_items(sorted_items)
)

hasher = hmac.new(
self.secret.encode(), to_sign.encode("UTF-8"), digestmod=sha256
)
signature = f"{self.receiver_id}:{hasher.hexdigest()}"

if self.is_debug:
logging.debug('a firmar: %s', to_sign)
logging.debug('firma: %s', signature)
logging.debug("a firmar: %s", to_sign)
logging.debug("firma: %s", signature)

return signature

def make_request(self, method, endpoint, params=None, data=None):
url = API_BASE + endpoint
signature = self.__make_signature(method, url, params, data)
payload = {
'headers': {
'Authorization': signature,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'pykhipu/{version}'.format(version=version('pykhipu')),
'Accept': 'application/json'
"headers": {
"Authorization": signature,
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "pykhipu/{version}".format(version=version("pykhipu")),
"Accept": "application/json",
}
}

if params:
payload.update({ 'params': params })
payload.update({"params": params})
if data:
payload.update({ 'data': data })
payload.update({"data": data})

response = requests.request(method, url, **payload)

if self.is_debug:
logging.debug('Response: %s', response.text)
logging.debug("Response: %s", response.text)

return response
17 changes: 11 additions & 6 deletions khipu_tools/pykhipu/items.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
class BankItem(object):
class BankItem:
def __init__(self, bank_id, name, message, min_amount, bank_type, parent):
self._bank_id = bank_id
self._name = name
Expand All @@ -14,8 +13,14 @@ def from_data(cls, data):
Constructor que permite obtener una instancia de BankItem a partir de un
diccionario de datos.
"""
return cls(data.get('bank_id'), data.get('name'), data.get('message'),
data.get('min_amount'), data.get('type'), data.get('parent'))
return cls(
data.get("bank_id"),
data.get("name"),
data.get("message"),
data.get("min_amount"),
data.get("type"),
data.get("parent"),
)

@property
def bank_id(self):
Expand Down Expand Up @@ -61,14 +66,14 @@ def parent(self):
return self._parent


class ErrorItem(object):
class ErrorItem:
def __init__(self, field, message):
self._field = field
self._message = message

@classmethod
def from_data(cls, data):
return cls(data.get('field'), data.get('message'))
return cls(data.get("field"), data.get("message"))

@property
def field(self):
Expand Down
43 changes: 19 additions & 24 deletions khipu_tools/pykhipu/payments.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
# -*- coding: utf-8 -*-
from datetime import datetime
from pykhipu.responses import (
PaymentsResponse,
PaymentsCreateResponse,
SuccessResponse,
)

from pykhipu.responses import PaymentsCreateResponse, PaymentsResponse, SuccessResponse

class Payments(object):
ENDPOINT = '/payments'

class Payments:
ENDPOINT = "/payments"

def __init__(self, client):
self.client = client
Expand All @@ -19,41 +15,40 @@ def get(self, notification_token):
actual del pago. Se obtiene del notification_token que envia khipu
cuando el pago es conciliado.
"""
response = self.client.make_request('GET', self.ENDPOINT,
params={ 'notification_token': notification_token })
response = self.client.make_request(
"GET", self.ENDPOINT, params={"notification_token": notification_token}
)
return PaymentsResponse.from_response(response)

def post(self, subject, currency, amount, **kwargs):
"""
Crea un pago en khipu y obtiene las URLs para redirección al usuario
para que complete el pago.
"""
data = {'subject': subject,
'currency': currency,
'amount': amount }
data = {"subject": subject, "currency": currency, "amount": amount}
data.update(kwargs)
if hasattr(data, 'expires_date'):
if isinstance(data['expires_date'], datetime):
data['expires_date'] = data['expires_date'].isoformat()
response = self.client.make_request('POST', self.ENDPOINT, data=data)
if hasattr(data, "expires_date"):
if isinstance(data["expires_date"], datetime):
data["expires_date"] = data["expires_date"].isoformat()
response = self.client.make_request("POST", self.ENDPOINT, data=data)
return PaymentsCreateResponse.from_response(response)

def get_id(self, id):
"""
Información completa del pago. Datos con los que fue creado y el estado
actual del pago.
"""
endpoint = "{0}/{1}/".format(self.ENDPOINT, id)
response = self.client.make_request('GET', endpoint)
endpoint = f"{self.ENDPOINT}/{id}/"
response = self.client.make_request("GET", endpoint)
return PaymentsResponse.from_response(response)

def delete(self, id):
"""
Solo se pueden borrar pagos que estén pendientes de pagar. Esta
operación no puede deshacerse.
"""
endpoint = "{0}/{1}/".format(self.ENDPOINT, id)
response = self.client.make_request('DELETE', endpoint)
endpoint = f"{self.ENDPOINT}/{id}/"
response = self.client.make_request("DELETE", endpoint)
return SuccessResponse.from_response(response)

def post_refunds(self, id, amount=None):
Expand All @@ -64,7 +59,7 @@ def post_refunds(self, id, amount=None):
"""
data = None
if amount:
data = { 'amount': amount }
endpoint = "{0}/{1}/refunds".format(self.ENDPOINT, id)
response = self.client.make_request('POST', endpoint, data=data)
data = {"amount": amount}
endpoint = f"{self.ENDPOINT}/{id}/refunds"
response = self.client.make_request("POST", endpoint, data=data)
return SuccessResponse.from_response(response)
7 changes: 3 additions & 4 deletions khipu_tools/pykhipu/receivers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
class Receivers(object):
ENDPOINT = '/receivers'
class Receivers:
ENDPOINT = "/receivers"

def __init__(self, client):
self.client = client
Expand All @@ -11,5 +10,5 @@ def post(self, data):
de la cuenta de usuario asociada, datos de facturación y datos de
contacto.
"""
response = self.client.make_request('POST', self.ENDPOINT, data=data)
response = self.client.make_request("POST", self.ENDPOINT, data=data)
return ReceiversCreateResponse.from_response(response)
Loading

0 comments on commit 1331037

Please sign in to comment.