Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Made suggested changes over the razorpay gateway

NyanKiyoshi75583f953815
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index ac84c88587..1bdd87b565 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -1,28 +1,46 @@
+import logging
import uuid
from decimal import Decimal
from typing import Dict, Tuple
+from django.utils.translation import pgettext_lazy
+
import razorpay
+from razorpay import errors
from ... import TransactionKind
-from ...utils import create_transaction
from ...models import Payment, Transaction
-
+from ...utils import create_transaction
from .forms import RazorPaymentForm
+# Define the existing error messages as lazy `pgettext`.
+ERROR_MSG_ORDER_NOT_CHARGED = pgettext_lazy(
+ 'Razorpay payment error', 'Order was not charged.')
+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.')
-E_ORDER_NOT_CHARGED = 'Order was not charged.'
+# Define what are the razorpay exceptions,
+# as the razorpay provider doesn't define a base exception as of now.
+RAZORPAY_EXCEPTIONS = (
+ errors.BadRequestError, errors.GatewayError, errors.ServerError)
+# Get the logger for this file, it will allow us to log
+# error responses from razorpay.
+logger = logging.getLogger(__name__)
-def _generate_transaction(
- payment, kind: str, amount=None,
- *, id='', is_success=True, **data):
-
- if isinstance(amount, int):
- amount = Decimal(amount) / 100
- elif amount is None:
- amount = payment.total
+def _generate_transaction(
+ payment: Payment,
+ kind: str,
+ amount: Decimal,
+ *,
+ id='',
+ is_success=True,
+ **data) -> Transaction:
+ """Creates a transaction from a Razorpay's success payload
+ or from passed data."""
transaction = create_transaction(
payment=payment,
kind=kind,
@@ -31,20 +49,49 @@ def _generate_transaction(
gateway_response=data,
token=id,
is_success=is_success)
-
return transaction
+def get_error_message_from_razorpay_error(exc: BaseException):
+ """Convert a error razorpay error to a user friendly error message
+ and log the exception to stderr."""
+ logger.exception(exc)
+ if isinstance(exc, errors.BadRequestError):
+ return ERROR_MSG_INVALID_REQUEST
+ else:
+ return ERROR_MSG_SERVER_ERROR
+
+
+def get_error_response(amount: Decimal):
+ """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 amount
+ as an integer, we converts it to a decimal object (by dividing by 100)."""
+ response['amount'] = Decimal(response['amount']) / 100
+
+
def get_form_class():
+ """Return the associated razorpay payment form."""
return RazorPaymentForm
-def get_client(public_key, secret_key, **_):
+def get_client(public_key: str, secret_key: str, **_):
+ """Create a Razorpay client from set-up application keys."""
razorpay_client = razorpay.Client(auth=(public_key, secret_key))
return razorpay_client
def get_client_token(**_):
+ """Generate a random client token."""
return str(uuid.uuid4())
@@ -53,37 +100,53 @@ def charge(
payment_token: str,
amount: Decimal,
**connection_params: Dict) -> Tuple[Transaction, str]:
-
- int_amount = int(amount) * 100
+ """Charge a authorized payment using the razorpay client.
+ If an error from razorpay occurs,
+ we flag the transaction as failed and return
+ a short user friendly description of the error
+ after logging the error to stderr."""
+ error = ''
razorpay_client = get_client(**connection_params)
- response = razorpay_client.payment.capture(payment_token, int_amount)
+ 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)
transaction = _generate_transaction(
payment=payment, kind=TransactionKind.CHARGE, **response)
- return transaction, ''
+ return transaction, error
+
+def refund(payment: Payment, amount: Decimal, **connection_params):
+ """Refund a payment using the razorpay client.
-def refund(payment, amount: Decimal, **connection_params):
+ It first retrieve a `charge` transaction to retrieve the
+ payment id to refund. And return an error with a failed transaction
+ if the there is no such transaction, or if an error
+ from razorpay occurs during the refund."""
error = ''
capture_txn = payment.transactions.filter(
kind=TransactionKind.CHARGE, is_success=True).first()
if capture_txn is not None:
- int_amount = int(amount * 100)
razorpay_client = get_client(**connection_params)
- response = razorpay_client.payment.refund(
- capture_txn.token, int_amount)
+ razorpay_amount = get_amount_for_razorpay(amount)
+ try:
+ response = razorpay_client.payment.refund(
+ capture_txn.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)
else:
- response = {'is_success': False}
- error = E_ORDER_NOT_CHARGED
+ error = ERROR_MSG_ORDER_NOT_CHARGED
+ response = get_error_response(amount)
transaction = _generate_transaction(
payment=payment, kind=TransactionKind.REFUND, **response)
return transaction, error
-
-
-def void(payment, **params):
- transaction = _generate_transaction(
- payment=payment, kind=TransactionKind.VOID,
- id=get_client_token(**params))
- return transaction, ''
diff --git a/saleor/payment/gateways/razorpay/forms.py b/saleor/payment/gateways/razorpay/forms.py
index 47fcdb3b45..32b946a415 100644
--- a/saleor/payment/gateways/razorpay/forms.py
+++ b/saleor/payment/gateways/razorpay/forms.py
@@ -5,6 +5,7 @@ from django.utils.html import format_html
from django.utils.translation import pgettext_lazy
from ...forms import PaymentForm
+from ...models import Payment
CHECKOUT_SCRIPT_URL = 'https://checkout.razorpay.com/v1/checkout.js'
@@ -16,12 +17,15 @@ SECONDARY_TITLE = pgettext_lazy(
class RazorPayCheckoutWidget(HiddenInput):
def __init__(
- self,
- *, payment,
- public_key, prefill, store_name, store_image,
- **kwargs):
- override_attrs = kwargs.get('attrs', None)
- base_attrs = kwargs['attrs'] = {
+ self, *,
+ payment: Payment,
+ public_key: str,
+ prefill: bool,
+ store_name: str,
+ store_image: str,
+ **additional_parameters):
+ override_attrs = additional_parameters.get('attrs', None)
+ base_attrs = additional_parameters['attrs'] = {
'src': CHECKOUT_SCRIPT_URL,
'data-key': public_key,
'data-buttontext': PRIMARY_BTN_TEXT,
@@ -29,8 +33,7 @@ class RazorPayCheckoutWidget(HiddenInput):
'data-name': store_name,
'data-description': SECONDARY_TITLE,
'data-amount': int(payment.total * 100),
- 'data-currency': payment.currency
- }
+ 'data-currency': payment.currency}
if prefill:
customer_name = '%s %s' % (
@@ -38,14 +41,13 @@ class RazorPayCheckoutWidget(HiddenInput):
payment.billing_first_name)
base_attrs.update({
'data-prefill.name': customer_name,
- 'data-prefill.email': payment.billing_email
- })
+ 'data-prefill.email': payment.billing_email})
if override_attrs:
base_attrs.update(override_attrs)
super().__init__(attrs=base_attrs)
- def render(self, *args, **kwargs):
+ def render(self, **kwargs):
attrs = kwargs.setdefault('attrs', {})
attrs.update(self.attrs)
return format_html('<script{0}></script>', flatatt(attrs))
@@ -64,6 +66,6 @@ class RazorPaymentForm(PaymentForm):
def process_payment(self):
data = super(RazorPaymentForm, self).clean()
- transaction_id = data['razorpay_payment_id']
- self.payment.charge(transaction_id)
+ payment_token = data['razorpay_payment_id']
+ self.payment.charge(payment_token)
return self.payment
diff --git a/saleor/settings.py b/saleor/settings.py
index a9b351a6a0..5bfbb82b78 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -556,7 +556,8 @@ BRAINTREE = 'braintree'
RAZORPAY = 'razorpay'
CHECKOUT_PAYMENT_GATEWAYS = {
- DUMMY: pgettext_lazy('Payment method name', 'Dummy gateway')
+ DUMMY: pgettext_lazy('Payment method name', 'Dummy gateway'),
+ RAZORPAY: ''
}
PAYMENT_GATEWAYS = {
diff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.py
index 4ae85d7346..9dbb0034fb 100644
--- a/tests/gateway/test_razorpay.py
+++ b/tests/gateway/test_razorpay.py
@@ -1,148 +1,245 @@
+from decimal import Decimal
from unittest.mock import patch
import pytest
-from django.conf import settings
-from saleor.payment import ChargeStatus, PaymentError, TransactionKind
-from saleor.payment.gateways import razorpay
+from razorpay.errors import BadRequestError, ServerError
+from saleor.payment import ChargeStatus, TransactionKind
+from 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)
from saleor.payment.gateways.razorpay.forms import (
RazorPayCheckoutWidget, RazorPaymentForm)
+TRANSACTION_AMOUNT = Decimal('61.33')
+
@pytest.fixture()
-def mocked_gateway_client(razorpay_payment):
- with patch('razorpay.Client') as mocked:
- response = {'amount': int(razorpay_payment.total * 100)}
- mocked().payment.capture.return_value = response
- mocked().payment.refund.return_value = response
- yield mocked
+def gateway_params():
+ return {
+ 'public_key': 'public',
+ 'secret_key': 'secret',
+ 'prefill': True,
+ 'store_name': 'Saleor',
+ 'store_image': 'image.png'}
@pytest.fixture()
-def razorpay_payment(payment_dummy):
- payment_dummy.gateway = settings.RAZORPAY
- return payment_dummy
+def razorpay_success_response():
+ return {
+ 'id': 'transaction123',
+ 'amount': get_amount_for_razorpay(TRANSACTION_AMOUNT),
+ 'currency': 'USD'}
-def _get_gateway_params(*, prefill=True):
- return {
- 'prefill': prefill,
- 'public_key': '123',
- 'store_name': 'Saleor',
- 'store_image': 'image.png'}
+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'])
+
+ payment_dummy.transactions.create(
+ amount=payment_dummy.total,
+ kind=TransactionKind.CHARGE,
+ gateway_response={},
+ is_success=True)
+ return payment_dummy
-def test_checkout_widget_render_without_prefill(payment_dummy):
+def test_checkout_widget_render_without_prefill(payment_dummy, gateway_params):
+ gateway_params['prefill'] = False
widget = RazorPayCheckoutWidget(
payment=payment_dummy, attrs={'data-custom': '123'},
- **_get_gateway_params(prefill=False))
+ **gateway_params)
assert widget.render() == (
'<script data-amount="8000" data-buttontext="Pay now with Razorpay" '
'data-currency="USD" data-custom="123" '
'data-description="Total payment" '
- 'data-image="image.png" data-key="123" data-name="Saleor" '
+ '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):
+def test_checkout_widget_render_with_prefill(payment_dummy, gateway_params):
widget = RazorPayCheckoutWidget(
- payment=payment_dummy, **_get_gateway_params(prefill=True))
+ payment=payment_dummy, **gateway_params)
assert widget.render() == (
'<script data-amount="8000" data-buttontext="Pay now with Razorpay" '
'data-currency="USD" data-description="Total payment" '
- 'data-image="image.png" data-key="123" data-name="Saleor" '
+ '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):
+def test_checkout_form(payment_dummy, gateway_params):
form = RazorPaymentForm(
data={'razorpay_payment_id': '123'},
payment=payment_dummy,
- gateway=None, gateway_params=_get_gateway_params())
+ 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
mocked_charge.assert_called_once_with('123')
-def test_gateway_get_form_class():
- assert razorpay.get_form_class() == RazorPaymentForm
+def test_get_amount_for_razorpay():
+ assert get_amount_for_razorpay(Decimal('61.33')) == 6133
-def test_gateway_void(razorpay_payment):
- txn = razorpay_payment.void()
- razorpay_payment.refresh_from_db()
+def test_clean_razorpay_response():
+ response = {'amount': 6133}
+ clean_razorpay_response(response)
+ assert response['amount'] == Decimal('61.33')
- assert txn.is_success
- assert txn.kind == TransactionKind.VOID
- assert txn.payment == razorpay_payment
- assert not razorpay_payment.is_active
+@patch('razorpay.Client')
+def test_get_client(mocked_gateway, gateway_params):
+ get_client(**gateway_params)
+ mocked_gateway.assert_called_once_with(auth=('public', 'secret'))
-def test_gateway_charge(mocked_gateway_client, razorpay_payment):
- capture_txn = razorpay_payment.charge(payment_token='token')
- mocked_gateway_client().payment.capture.assert_called_once_with(
- 'token', int(razorpay_payment.total * 100))
+def test_get_client_token():
+ assert get_client_token()
- assert capture_txn.is_success
- assert capture_txn.kind == TransactionKind.CHARGE
- assert capture_txn.payment == razorpay_payment
- assert capture_txn.amount == razorpay_payment.total
- razorpay_payment.refresh_from_db()
- assert razorpay_payment.charge_status == ChargeStatus.CHARGED
- assert razorpay_payment.captured_amount == razorpay_payment.total
- assert razorpay_payment.is_active
+def test_get_form_class():
+ assert get_form_class() == RazorPaymentForm
-def test_refund_success(mocked_gateway_client, razorpay_payment):
- razorpay_payment.captured_amount = razorpay_payment.total
- razorpay_payment.charge_status = ChargeStatus.CHARGED
- razorpay_payment.save(update_fields=['captured_amount', 'charge_status'])
+@patch('razorpay.Client')
+def test_charge(
+ mocked_gateway,
+ payment_dummy,
+ razorpay_success_response,
+ gateway_params):
- razorpay_payment.transactions.create(
- amount=razorpay_payment.total,
- kind=TransactionKind.CHARGE,
- gateway_response={},
- is_success=True)
+ # Data to be passed
+ payment_token = '123'
- txn = razorpay_payment.refund()
- razorpay_payment.refresh_from_db()
+ # Mock the gateway response to a success response
+ mocked_gateway.return_value.payment.capture.return_value = (
+ razorpay_success_response)
- mocked_gateway_client().payment.refund.assert_called_once_with(
- razorpay_payment.token, int(razorpay_payment.total * 100))
+ # Attempt charging
+ txn, error = charge(
+ payment_dummy, payment_token,
+ TRANSACTION_AMOUNT, **gateway_params)
- assert txn.payment == razorpay_payment
- assert txn.kind == TransactionKind.REFUND
- assert txn.amount == razorpay_payment.total
+ # Ensure the was no error returned
+ assert not error
assert txn.is_success
- assert razorpay_payment.charge_status == ChargeStatus.FULLY_REFUNDED
- assert not razorpay_payment.captured_amount
- assert not razorpay_payment.is_active
+ assert txn.payment == payment_dummy
+ assert txn.kind == TransactionKind.CHARGE
+ assert txn.amount == TRANSACTION_AMOUNT
+ assert txn.currency == razorpay_success_response['currency']
+ assert txn.gateway_response == {}
+ assert txn.token == razorpay_success_response['id']
+
+
+@patch('razorpay.Client')
+def test_charge_invalid_request(
+ mocked_gateway,
+ payment_dummy,
+ gateway_params):
+
+ # Data to be passed
+ payment_token = '123'
+
+ # Assign the side effect to the gateway's `charge()` method,
+ # that should trigger the expected error.
+ mocked_gateway.return_value.payment.capture.side_effect = BadRequestError()
+ # Attempt charging
+ txn, error = charge(
+ payment_dummy, payment_token,
+ TRANSACTION_AMOUNT, **gateway_params)
+
+ # Ensure an error was returned
+ assert error == ERROR_MSG_INVALID_REQUEST
+ assert not txn.is_success
+
+ # Ensure the transaction is correctly set
+ assert txn.payment == payment_dummy
+ assert txn.kind == TransactionKind.CHARGE
-def test_refund_failed(mocked_gateway_client, razorpay_payment):
- razorpay_payment.captured_amount = razorpay_payment.total
- razorpay_payment.charge_status = ChargeStatus.CHARGED
- razorpay_payment.save(update_fields=['captured_amount', 'charge_status'])
- with pytest.raises(PaymentError, message=razorpay.E_ORDER_NOT_CHARGED):
- razorpay_payment.refund()
+@patch('razorpay.Client')
+def test_refund(
+ mocked_gateway,
+ charged_payment,
+ razorpay_success_response,
+ gateway_params):
- razorpay_payment.refresh_from_db()
- txn = razorpay_payment.transactions.last()
- assert txn
+ # Mock the gateway response to a success response
+ mocked_gateway.return_value.payment.refund.return_value = (
+ razorpay_success_response)
- assert txn.payment == razorpay_payment
+ # Attempt charging
+ txn, error = refund(
+ charged_payment, TRANSACTION_AMOUNT, **gateway_params)
+
+ # Ensure the was no error returned
+ assert not error
+ assert txn.is_success
+
+ assert txn.payment == charged_payment
assert txn.kind == TransactionKind.REFUND
+ assert txn.amount == TRANSACTION_AMOUNT
+ assert txn.currency == razorpay_success_response['currency']
+ assert txn.gateway_response == {}
+ assert txn.token == razorpay_success_response['id']
+
+
+@patch('razorpay.Client')
+def test_refund_invalid_payment(
+ mocked_gateway,
+ payment_dummy,
+ razorpay_success_response,
+ gateway_params):
+
+ # Mock the gateway response to a success response
+ mocked_gateway.return_value.payment.refund.return_value = (
+ razorpay_success_response)
+
+ # Attempt charging
+ txn, error = refund(
+ payment_dummy, TRANSACTION_AMOUNT, **gateway_params)
+
+ # Ensure a error was returned
+ assert error == ERROR_MSG_ORDER_NOT_CHARGED
assert not txn.is_success
- assert mocked_gateway_client().payment.refund.call_count == 0
+ # Ensure the transaction is correctly set
+ assert txn.payment == payment_dummy
+ assert txn.kind == TransactionKind.REFUND
+
+
+@patch('razorpay.Client')
+def test_refund_invalid_data(
+ mocked_gateway,
+ charged_payment,
+ razorpay_success_response,
+ gateway_params):
+
+ # Assign the side effect to the gateway's `refund()` method,
+ # that should trigger the expected error.
+ mocked_gateway.return_value.payment.refund.side_effect = ServerError()
- assert razorpay_payment.charge_status == ChargeStatus.CHARGED
- assert razorpay_payment.captured_amount
- assert razorpay_payment.is_active
+ # Attempt charging
+ txn, error = refund(
+ charged_payment, TRANSACTION_AMOUNT, **gateway_params)
+
+ # Ensure a error was returned
+ assert error == ERROR_MSG_SERVER_ERROR
+ assert not txn.is_success
+
+ # Ensure the transaction is correctly set
+ assert txn.payment == charged_payment
+ assert txn.kind == TransactionKind.REFUND