Skip to content

Commit

Permalink
Upgrade function button to button_init for API v1.9.
Browse files Browse the repository at this point in the history
  • Loading branch information
zbohm committed Jul 25, 2022
1 parent d622a40 commit e8495ff
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 29 deletions.
27 changes: 16 additions & 11 deletions pycsob/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,6 @@ def payment_init(self, order_no, total_amount, return_url, description, cart=Non
:return: response from gateway as OrderedDict
"""

if merchant_data:
merchant_data = b64encode(merchant_data).decode("UTF-8")
if len(merchant_data) > 255:
raise ValueError('Merchant data length encoded to BASE64 is over 255 chars')

# fill cart if not set
if not cart:
cart = [
Expand All @@ -116,7 +111,7 @@ def payment_init(self, order_no, total_amount, return_url, description, cart=Non
('cart', cart),
('customer', customer_data),
('order', order),
('merchantData', merchant_data),
('merchantData', utils.encode_merchant_data(merchant_data)),
('customerId', customer_id),
('language', language[:2]),
('ttlSec', ttl_sec),
Expand Down Expand Up @@ -204,7 +199,7 @@ def customer_info(self, customer_id):
base_url=self.base_url,
endpoint_url='echo/customer'
)
payload=utils.mk_payload(self.f_key, pairs=(
payload = utils.mk_payload(self.f_key, pairs=(
('merchantId', self.merchant_id),
('customerId', customer_id),
('dttm', utils.dttm())
Expand Down Expand Up @@ -250,14 +245,24 @@ def req_payload(self, pay_id, **kwargs):
pairs += ((k, v),)
return utils.mk_payload(keyfile=self.f_key, pairs=pairs)

def button(self, pay_id, brand):
def button_init(
self, order_no, total_amount, client_ip, return_url,
language='cs', return_method='POST', merchant_data=None):
"Get url to the button."

payload = utils.mk_payload(self.f_key, pairs=(
('merchantId', self.merchant_id),
('payId', pay_id),
('brand', brand),
('orderNo', str(order_no)),
('dttm', utils.dttm()),
('clientIp', client_ip),
('totalAmount', total_amount),
('currency', 'CZK'),
('returnUrl', return_url),
('returnMethod', return_method),
('brand', 'csob'),
('merchantData', utils.encode_merchant_data(merchant_data)),
('language', language[:2]),
))
url = utils.mk_url(base_url=self.base_url, endpoint_url='payment/button/')
url = utils.mk_url(base_url=self.base_url, endpoint_url='button/init')
r = self._client.post(url, data=json.dumps(payload))
return utils.validate_response(r, self.f_pubkey)
9 changes: 9 additions & 0 deletions pycsob/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,12 @@ def get_card_provider(long_masked_number):
if rx.match(long_masked_number[:6]):
return provider_id, conf.CARD_PROVIDERS[provider_id]
return None, None


def encode_merchant_data(merchant_data):
"""Encode merchant data. Raise ValueError if data length > 255."""
if merchant_data is not None:
merchant_data = b64encode(merchant_data).decode("UTF-8")
if len(merchant_data) > 255:
raise ValueError('Merchant data length encoded to BASE64 is over 255 chars')
return merchant_data
38 changes: 20 additions & 18 deletions tests_pycsob/test_api.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# coding: utf-8
import os
import datetime
import json
import pytest
from testfixtures import LogCapture
import os
from collections import OrderedDict
from freezegun import freeze_time
from requests.exceptions import HTTPError
from unittest import TestCase
from unittest.mock import call, patch
from urllib3_mock import Responses

import pytest
from freezegun import freeze_time
from pycsob import conf, utils
from pycsob.client import CsobClient
from requests.exceptions import HTTPError
from testfixtures import LogCapture
from urllib3_mock import Responses

KEY_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fixtures', 'test.key'))
PAY_ID = '34ae55eb69e2cBF'
Expand Down Expand Up @@ -357,16 +357,15 @@ def test_payment_init_language_with_locale_cs(self):
)

@responses.activate
def test_button(self):
resp_url = '/payment/button/'
def test_button_init(self):
resp_payload = utils.mk_payload(KEY_PATH, pairs=(
('payId', PAY_ID),
('dttm', utils.dttm()),
('resultCode', conf.RETURN_CODE_OK),
('resultMessage', 'OK'),
))
responses.add(responses.POST, resp_url, body=json.dumps(resp_payload), status=200)
out = self.c.button(PAY_ID, 'csob').payload
responses.add(responses.POST, '/button/init', body=json.dumps(resp_payload), status=200)
out = self.c.button_init(PAY_ID, 10000, '127.0.0.1', 'https://web.foo/').payload
self.assertEqual(out, OrderedDict([
('payId', '34ae55eb69e2cBF'),
('dttm', self.dttm),
Expand All @@ -375,15 +374,18 @@ def test_button(self):
('dttime', self.dttime),
]))
self.log_handler.check(
('pycsob', 'INFO', 'Pycsob request POST: https://gw.cz/payment/button/; Data: {"merchantId": "MERCHANT", '
'"payId": "34ae55eb69e2cBF", "brand": "csob", "dttm": "20190502161426", "signature": '
'"keFD/Lt5k4OSGdQOL+PlDUELx1U3z0gSSlWch8Z/U7CK4S01YjLuKRjHBcfuMAQgZDvauZmYSFp7clcqy15dVA=="}; '
'Json: None; {}'),
('pycsob', 'INFO', 'Pycsob request POST: https://gw.cz/button/init; Data: {"merchantId": '
'"MERCHANT", "orderNo": "34ae55eb69e2cBF", "dttm": "20190502161426", '
'"clientIp": "127.0.0.1", "totalAmount": 10000, "currency": "CZK", '
'"returnUrl": "https://web.foo/", "returnMethod": "POST", "brand": "csob", '
'"language": "cs", "signature": '
'"D3rppiWK7zp1B9ra94cxQczOwfUVrRnyd8oLRTd4guC+qXALRXKHgqc7AVPnM3kuMG6fRY9B4X9+10n/603C9Q=="}; '
'Json: None; {}'),
('pycsob', 'DEBUG', "Pycsob request headers: {'content-type': 'application/json', 'user-agent': "
"'py-csob/1.0.0', 'Content-Length': '202'}"),
('pycsob', 'INFO', 'Pycsob response: [200] {"payId": "34ae55eb69e2cBF", "dttm": "20190502161426", '
'"resultCode": 0, "resultMessage": "OK", "signature": '
'"mMvfLq/SzhagYKkJp/PnQ+Y9zoMJIGt1OznlxQLqq+gsyhOjUd4ghDtJtFt8bQkpr+jwj6kd/y8R5RyxZ7qgag=="}'),
"'py-csob/1.0.0', 'Content-Length': '345'}"),
('pycsob', 'INFO', 'Pycsob response: [200] {"payId": "34ae55eb69e2cBF", "dttm": '
'"20190502161426", "resultCode": 0, "resultMessage": "OK", "signature": '
'"mMvfLq/SzhagYKkJp/PnQ+Y9zoMJIGt1OznlxQLqq+gsyhOjUd4ghDtJtFt8bQkpr+jwj6kd/y8R5RyxZ7qgag=="}'),
('pycsob', 'DEBUG', "Pycsob response headers: {'Content-Type': 'text/plain'}")
)

Expand Down

0 comments on commit e8495ff

Please sign in to comment.