Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Checks if the currency is supported by razorpay before transactions
NyanKiyoshi60d53988f490
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.pyindex 10115c9551..d1b4f43e5f 100644--- a/saleor/payment/gateways/razorpay/__init__.py+++ b/saleor/payment/gateways/razorpay/__init__.py@@ -12,6 +12,7 @@ from ... import TransactionKindfrom ...models import Payment, Transactionfrom ...utils import create_transactionfrom .forms import RazorPaymentForm+from .utils import get_amount_for_razorpay, get_error_response# Define the existing error messages as lazy `pgettext`.ERROR_MSG_ORDER_NOT_CHARGED = pgettext_lazy(@@ -20,6 +21,11 @@ ERROR_MSG_INVALID_REQUEST = pgettext_lazy('Razorpay payment error', 'The payment data was invalid.')ERROR_MSG_SERVER_ERROR = pgettext_lazy('Razorpay payment error', 'The order couldn\'t be proceeded.')+ERROR_UNSUPPORTED_CURRENCY = pgettext_lazy(+ 'Razorpay payment error', 'The %(currency)s currency is not supported.')++# The list of currencies supported by razorpay+SUPPORTED_CURRENCIES = 'INR',# Define what are the razorpay exceptions,# as the razorpay provider doesn't define a base exception as of now.@@ -52,6 +58,13 @@ def _generate_transaction(return transaction+def check_payment_supported(payment: Payment):+ """Checks that a given payment is supported"""+ if payment.currency not in SUPPORTED_CURRENCIES:+ return ERROR_UNSUPPORTED_CURRENCY % {+ 'currency': payment.currency}++def get_error_message_from_razorpay_error(exc: BaseException):"""Convert a error razorpay error to a user friendly error messageand log the exception to stderr."""@@ -62,17 +75,6 @@ def get_error_message_from_razorpay_error(exc: BaseException):return ERROR_MSG_SERVER_ERROR-def get_error_response(amount: Decimal) -> dict:- """Create a place holder response for invalid/ failed requests- for generated a failed transaction object."""- return {'is_success': False, 'amount': amount}---def get_amount_for_razorpay(amount: Decimal) -> int:- """Convert a decimal amount to int, by multiplying the value by 100."""- return int(amount * 100)--def clean_razorpay_response(response: dict):"""As the Razorpay response payload contains the final amountas an integer, we converts it to a decimal object (by dividing by 100)."""@@ -101,22 +103,28 @@ def charge(amount: Decimal,**connection_params: Dict) -> Tuple[Transaction, str]:"""Charge a authorized payment using the razorpay client.++ But it first check if the given payment instance is supported+ by the gateway.+If an error from razorpay occurs,we flag the transaction as failed and returna short user friendly description of the errorafter logging the error to stderr."""- error = ''+ error = check_payment_supported(payment=payment)razorpay_client = get_client(**connection_params)razorpay_amount = get_amount_for_razorpay(amount)- try:- response = razorpay_client.payment.capture(- payment_token, razorpay_amount)- clean_razorpay_response(response)- except RAZORPAY_EXCEPTIONS as exc:- error = get_error_message_from_razorpay_error(exc)- response = get_error_response(amount)- response['id'] = payment_token+ if not error:+ try:+ response = razorpay_client.payment.capture(+ payment_token, razorpay_amount)+ clean_razorpay_response(response)+ except RAZORPAY_EXCEPTIONS as exc:+ error = get_error_message_from_razorpay_error(exc)+ response = get_error_response(amount, id=payment_token)+ else:+ response = get_error_response(amount, id=payment_token)transaction = _generate_transaction(payment=payment, kind=TransactionKind.CHARGE, **response)@@ -126,15 +134,20 @@ def charge(def refund(payment: Payment, amount: Decimal, **connection_params):"""Refund a payment using the razorpay client.+ But it first check if the given payment instance is supported+ by the gateway.+It first retrieve a `charge` transaction to retrieve thepayment id to refund. And return an error with a failed transactionif the there is no such transaction, or if an errorfrom razorpay occurs during the refund."""- error = ''+ error = check_payment_supported(payment=payment)capture_txn = payment.transactions.filter(kind=TransactionKind.CHARGE, is_success=True).first()- if capture_txn is not None:+ if error:+ response = get_error_response(amount)+ elif capture_txn is not None:razorpay_client = get_client(**connection_params)razorpay_amount = get_amount_for_razorpay(amount)try:diff --git a/saleor/payment/gateways/razorpay/forms.py b/saleor/payment/gateways/razorpay/forms.pyindex 32b946a415..99d87df1f0 100644--- a/saleor/payment/gateways/razorpay/forms.py+++ b/saleor/payment/gateways/razorpay/forms.py@@ -6,6 +6,7 @@ from django.utils.translation import pgettext_lazyfrom ...forms import PaymentFormfrom ...models import Payment+from .utils import get_amount_for_razorpayCHECKOUT_SCRIPT_URL = 'https://checkout.razorpay.com/v1/checkout.js'@@ -32,7 +33,7 @@ class RazorPayCheckoutWidget(HiddenInput):'data-image': store_image,'data-name': store_name,'data-description': SECONDARY_TITLE,- 'data-amount': int(payment.total * 100),+ 'data-amount': get_amount_for_razorpay(payment.total),'data-currency': payment.currency}if prefill:diff --git a/saleor/payment/gateways/razorpay/utils.py b/saleor/payment/gateways/razorpay/utils.pynew file mode 100644index 0000000000..0ad3f53354--- /dev/null+++ b/saleor/payment/gateways/razorpay/utils.py@@ -0,0 +1,12 @@+from decimal import Decimal+++def get_error_response(amount: Decimal, **additional_kwargs) -> dict:+ """Create a place holder response for invalid/ failed requests+ for generated a failed transaction object."""+ return dict(is_success=False, amount=amount, **additional_kwargs)+++def get_amount_for_razorpay(amount: Decimal) -> int:+ """Convert a decimal amount to int, by multiplying the value by 100."""+ return int(amount * 100)diff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.pyindex 610eee248f..debb9c6228 100644--- a/tests/gateway/test_razorpay.py+++ b/tests/gateway/test_razorpay.py@@ -7,9 +7,9 @@ from razorpay.errors import BadRequestError, ServerErrorfrom saleor.payment import ChargeStatus, TransactionKindfrom saleor.payment.gateways.razorpay import (ERROR_MSG_INVALID_REQUEST, ERROR_MSG_ORDER_NOT_CHARGED,- ERROR_MSG_SERVER_ERROR, charge, clean_razorpay_response,- get_amount_for_razorpay, get_client, get_client_token, get_form_class,- refund)+ ERROR_MSG_SERVER_ERROR, ERROR_UNSUPPORTED_CURRENCY, charge,+ clean_razorpay_response, get_amount_for_razorpay, get_client,+ get_client_token, get_form_class, logger, refund)from saleor.payment.gateways.razorpay.forms import (RazorPayCheckoutWidget, RazorPaymentForm)@@ -31,56 +31,62 @@ def razorpay_success_response():return {'id': 'transaction123','amount': get_amount_for_razorpay(TRANSACTION_AMOUNT),- 'currency': 'USD'}+ 'currency': 'INR'}@pytest.fixture()-def charged_payment(payment_dummy):- payment_dummy.captured_amount = payment_dummy.total- payment_dummy.charge_status = ChargeStatus.CHARGED- payment_dummy.save(update_fields=['captured_amount', 'charge_status'])+def razorpay_payment(payment_dummy):+ payment_dummy.currency = 'INR'+ return payment_dummy+- payment_dummy.transactions.create(- amount=payment_dummy.total,+def charged_payment(razorpay_payment):+ razorpay_payment.captured_amount = razorpay_payment.total+ razorpay_payment.charge_status = ChargeStatus.CHARGED+ razorpay_payment.save(update_fields=['captured_amount', 'charge_status'])++ razorpay_payment.transactions.create(+ amount=razorpay_payment.total,kind=TransactionKind.CHARGE,gateway_response={},is_success=True)- return payment_dummy+ return razorpay_payment-def test_checkout_widget_render_without_prefill(payment_dummy, gateway_params):+def test_checkout_widget_render_without_prefill(razorpay_payment, gateway_params):gateway_params['prefill'] = Falsewidget = RazorPayCheckoutWidget(- payment=payment_dummy, attrs={'data-custom': '123'},+ payment=razorpay_payment, attrs={'data-custom': '123'},**gateway_params)assert widget.render() == ('<script data-amount="8000" data-buttontext="Pay now with Razorpay" '- 'data-currency="USD" data-custom="123" '+ 'data-currency="INR" data-custom="123" ''data-description="Total payment" ''data-image="image.png" data-key="public" data-name="Saleor" ''src="https://checkout.razorpay.com/v1/checkout.js"></script>')-def test_checkout_widget_render_with_prefill(payment_dummy, gateway_params):+def test_checkout_widget_render_with_prefill(razorpay_payment, gateway_params):widget = RazorPayCheckoutWidget(- payment=payment_dummy, **gateway_params)+ payment=razorpay_payment, **gateway_params)assert widget.render() == ('<script data-amount="8000" data-buttontext="Pay now with Razorpay" '- 'data-currency="USD" data-description="Total payment" '+ 'data-currency="INR" data-description="Total payment" ''data-image="image.png" data-key="public" data-name="Saleor" ''data-prefill.email="[email protected]" ''data-prefill.name="Doe John" ''src="https://checkout.razorpay.com/v1/checkout.js"></script>')-def test_checkout_form(payment_dummy, gateway_params):+def test_checkout_form(razorpay_payment, gateway_params):form = RazorPaymentForm(data={'razorpay_payment_id': '123'},- payment=payment_dummy,+ payment=razorpay_payment,gateway=None, gateway_params=gateway_params)assert form.is_valid()- with patch.object(payment_dummy, 'charge') as mocked_charge:- assert form.process_payment() == payment_dummy+ with patch.object(razorpay_payment, 'charge') as mocked_charge:+ assert form.process_payment() == razorpay_paymentmocked_charge.assert_called_once_with('123')@@ -112,7 +118,7 @@ def test_get_form_class():@patch('razorpay.Client')def test_charge(mocked_gateway,- payment_dummy,+ razorpay_payment,razorpay_success_response,gateway_params):@@ -125,14 +131,14 @@ def test_charge(# Attempt chargingtxn, error = charge(- payment_dummy, payment_token,+ razorpay_payment, payment_token,TRANSACTION_AMOUNT, **gateway_params)# Ensure the was no error returnedassert not errorassert txn.is_success- assert txn.payment == payment_dummy+ assert txn.payment == razorpay_paymentassert txn.kind == TransactionKind.CHARGEassert txn.amount == TRANSACTION_AMOUNTassert txn.currency == razorpay_success_response['currency']@@ -140,10 +146,35 @@ def test_charge(assert txn.token == razorpay_success_response['id']+def test_charge_unsupported_currency(razorpay_payment, gateway_params):+ # Set the payment currency to an unsupported currency+ razorpay_payment.currency = 'USD'++ # Data to be passed+ payment_token = '123'++ # Attempt charging+ txn, error = charge(+ razorpay_payment, payment_token,+ TRANSACTION_AMOUNT, **gateway_params)++ # Ensure a error was returned+ assert error == ERROR_UNSUPPORTED_CURRENCY % {'currency': 'USD'}+ assert not txn.is_success++ # Ensure the transaction is correctly set+ assert txn.payment == razorpay_payment+ assert txn.kind == TransactionKind.CHARGE+ assert txn.token == payment_token++[email protected](logger, 'exception')@patch('razorpay.Client')def test_charge_invalid_request(mocked_gateway,- payment_dummy,+ mocked_logger,+ razorpay_payment,gateway_params):# Data to be passed@@ -155,7 +186,7 @@ def test_charge_invalid_request(# Attempt chargingtxn, error = charge(- payment_dummy, payment_token,+ razorpay_payment, payment_token,TRANSACTION_AMOUNT, **gateway_params)# Ensure an error was returned@@ -163,10 +194,13 @@ def test_charge_invalid_request(assert not txn.is_success# Ensure the transaction is correctly set- assert txn.payment == payment_dummy+ assert txn.payment == razorpay_paymentassert txn.kind == TransactionKind.CHARGEassert txn.token == payment_token+ # Ensure the HTTP error was logged+ assert mocked_logger.call_count == 1+@pytest.mark.integration@patch('razorpay.Client')@@ -196,11 +230,30 @@ def test_refund(assert txn.token == razorpay_success_response['id']+def test_refund_unsupported_currency(+ razorpay_payment, charged_payment, gateway_params):+ # Set the payment currency to an unsupported currency+ razorpay_payment.currency = 'USD'++ # Attempt charging+ txn, error = refund(+ razorpay_payment, TRANSACTION_AMOUNT, **gateway_params)++ # Ensure a error was returned+ assert error == ERROR_UNSUPPORTED_CURRENCY % {'currency': 'USD'}+ assert not txn.is_success++ # Ensure the transaction is correctly set+ assert txn.payment == razorpay_payment+ assert txn.kind == TransactionKind.REFUND++@pytest.mark.integration@patch('razorpay.Client')-def test_refund_invalid_payment(+def test_refund_not_paid(mocked_gateway,- payment_dummy,+ razorpay_payment,razorpay_success_response,gateway_params):@@ -210,21 +263,23 @@ def test_refund_invalid_payment(# Attempt chargingtxn, error = refund(- payment_dummy, TRANSACTION_AMOUNT, **gateway_params)+ razorpay_payment, TRANSACTION_AMOUNT, **gateway_params)# Ensure a error was returnedassert error == ERROR_MSG_ORDER_NOT_CHARGEDassert not txn.is_success# Ensure the transaction is correctly set- assert txn.payment == payment_dummy+ assert txn.payment == razorpay_paymentassert txn.kind == TransactionKind.REFUND@pytest.mark.integration[email protected](logger, 'exception')@patch('razorpay.Client')def test_refund_invalid_data(mocked_gateway,+ mocked_logger,charged_payment,razorpay_success_response,gateway_params):@@ -244,3 +299,6 @@ def test_refund_invalid_data(# Ensure the transaction is correctly setassert txn.payment == charged_paymentassert txn.kind == TransactionKind.REFUND++ # Ensure the HTTP error was logged+ assert mocked_logger.call_count == 1