Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Adjust Razorpay to new payments core
Michał Jelonekbe2fe47ab8c9
diff --git a/saleor/payment/gateways/braintree/forms.py b/saleor/payment/gateways/braintree/forms.pyindex 8c58bfb023..a46667e39b 100644--- a/saleor/payment/gateways/braintree/forms.py+++ b/saleor/payment/gateways/braintree/forms.py@@ -13,7 +13,7 @@ class BraintreePaymentForm(forms.Form):# responsepayment_method_nonce = forms.CharField()- def __init__(self, payment_information, gateway_params, *args, **kwargs):+ def __init__(self, payment_information, gateway_params, *args, **kwargs):super().__init__(*args, **kwargs)self.payment_information = payment_informationself.fields['amount'].initial = payment_information['amount']diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.pyindex 7d5a780d4e..c5d58afcdb 100644--- a/saleor/payment/gateways/razorpay/__init__.py+++ b/saleor/payment/gateways/razorpay/__init__.py@@ -8,8 +8,6 @@ import razorpay.errorsfrom . import errorsfrom ... import TransactionKind-from ...models import Payment, Transaction-from ...utils import create_transactionfrom .forms import RazorPaymentFormfrom .utils import get_amount_for_razorpay, get_error_response@@ -28,32 +26,29 @@ RAZORPAY_EXCEPTIONS = (logger = logging.getLogger(__name__)-def _generate_transaction(- payment: Payment,+def _generate_response(+ payment_information: Dict,kind: str,- amount: Decimal,*,- id='',is_success=True,- **data) -> Transaction:+ **data) -> Dict:"""Creates a transaction from a Razorpay's success payloador from passed data."""- transaction = create_transaction(- payment=payment,- kind=kind,- amount=amount,- currency=data.pop('currency', payment.currency),- gateway_response=data,- token=id,- is_success=is_success)- return transaction---def check_payment_supported(payment: Payment):- """Checks that a given payment is supported"""- if payment.currency not in SUPPORTED_CURRENCIES:+ return {+ 'transaction_id': data.get('id', payment_information['token']),+ 'kind': kind,+ 'amount': data.get('amount', payment_information['amount']),+ 'currency': data.get('currency', payment_information['currency']),+ 'error': data.get('error', None),+ 'is_success': is_success,+ 'raw_response': data}+++def check_payment_supported(payment_information: Dict):+ """Checks that a given payment is supported."""+ if payment_information['currency'] not in SUPPORTED_CURRENCIES:return errors.UNSUPPORTED_CURRENCY % {- 'currency': payment.currency}+ 'currency': payment_information['currency']}def get_error_message_from_razorpay_error(exc: BaseException):@@ -72,6 +67,10 @@ def clean_razorpay_response(response: dict):response['amount'] = Decimal(response['amount']) / 100+def get_template():+ return 'order/payment/razorpay.html'++def get_form_class():"""Return the associated razorpay payment form."""return RazorPaymentForm@@ -88,11 +87,11 @@ def get_client_token(**_):return str(uuid.uuid4())-def charge(- payment: Payment,- payment_token: str,- amount: Decimal,- **connection_params: Dict) -> Tuple[Transaction, str]:+def process_payment(payment_information: Dict, **connection_params) -> Dict:+ return charge(payment_information=payment_information, **connection_params)+++def charge(payment_information: Dict, **connection_params: Dict) -> Dict:"""Charge a authorized payment using the razorpay client.But it first check if the given payment instance is supported@@ -102,27 +101,30 @@ def charge(we flag the transaction as failed and returna short user friendly description of the errorafter logging the error to stderr."""- error = check_payment_supported(payment=payment)+ error = check_payment_supported(payment_information=payment_information)razorpay_client = get_client(**connection_params)- razorpay_amount = get_amount_for_razorpay(amount)+ razorpay_amount = get_amount_for_razorpay(payment_information['amount'])if not error:try:response = razorpay_client.payment.capture(- payment_token, razorpay_amount)+ payment_information['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)+ response = get_error_response(+ payment_information['amount'], error=error,+ id=payment_information['token'])else:- response = get_error_response(amount, id=payment_token)+ response = get_error_response(+ payment_information['amount'], error=error,+ id=payment_information['token'])- transaction = _generate_transaction(- payment=payment, kind=TransactionKind.CHARGE, **response)- return transaction, error+ return _generate_response(+ payment_information=payment_information, kind='charge', **response)-def refund(payment: Payment, amount: Decimal, **connection_params):+def refund(payment_information: Dict, **connection_params) -> Dict:"""Refund a payment using the razorpay client.But it first check if the given payment instance is supported@@ -132,26 +134,22 @@ def refund(payment: Payment, amount: Decimal, **connection_params):payment 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 = check_payment_supported(payment=payment)- capture_txn = payment.transactions.filter(- kind=TransactionKind.CHARGE, is_success=True).first()+ error = check_payment_supported(payment_information=payment_information)if error:- response = get_error_response(amount)- elif capture_txn is not None:+ response = get_error_response(+ payment_information['amount'], error=error)+ else:razorpay_client = get_client(**connection_params)- razorpay_amount = get_amount_for_razorpay(amount)+ razorpay_amount = get_amount_for_razorpay(payment_information['amount'])try:response = razorpay_client.payment.refund(- capture_txn.token, razorpay_amount)+ payment_information['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:- error = errors.ORDER_NOT_CHARGED- response = get_error_response(amount)+ response = get_error_response(+ payment_information['amount'], error=error)- transaction = _generate_transaction(- payment=payment, kind=TransactionKind.REFUND, **response)- return transaction, error+ return _generate_response(+ payment_information=payment_information, kind='refund', **response)diff --git a/saleor/payment/gateways/razorpay/forms.py b/saleor/payment/gateways/razorpay/forms.pyindex 99d87df1f0..e561101fbc 100644--- a/saleor/payment/gateways/razorpay/forms.py+++ b/saleor/payment/gateways/razorpay/forms.py@@ -1,11 +1,11 @@+from typing import Dict+from django import formsfrom django.forms.utils import flatattfrom django.forms.widgets import HiddenInputfrom django.utils.html import format_htmlfrom django.utils.translation import pgettext_lazy-from ...forms import PaymentForm-from ...models import Paymentfrom .utils import get_amount_for_razorpayCHECKOUT_SCRIPT_URL = 'https://checkout.razorpay.com/v1/checkout.js'@@ -17,9 +17,10 @@ SECONDARY_TITLE = pgettext_lazy(class RazorPayCheckoutWidget(HiddenInput):+def __init__(self, *,- payment: Payment,+ payment_information: Dict,public_key: str,prefill: bool,store_name: str,@@ -33,16 +34,16 @@ class RazorPayCheckoutWidget(HiddenInput):'data-image': store_image,'data-name': store_name,'data-description': SECONDARY_TITLE,- 'data-amount': get_amount_for_razorpay(payment.total),- 'data-currency': payment.currency}+ 'data-amount': get_amount_for_razorpay(payment_information['amount']),+ 'data-currency': payment_information['currency']}if prefill:customer_name = '%s %s' % (- payment.billing_last_name,- payment.billing_first_name)+ payment_information['billing']['last_name'],+ payment_information['billing']['first_name'])base_attrs.update({'data-prefill.name': customer_name,- 'data-prefill.email': payment.billing_email})+ 'data-prefill.email': payment_information['customer_email']})if override_attrs:base_attrs.update(override_attrs)@@ -54,19 +55,16 @@ class RazorPayCheckoutWidget(HiddenInput):return format_html('<script{0}></script>', flatatt(attrs))-class RazorPaymentForm(PaymentForm):+class RazorPaymentForm(forms.Form):razorpay_payment_id = forms.CharField(required=True, widget=forms.HiddenInput)- def __init__(self, *args, **kwargs):+ def __init__(self, payment_information, gateway_params, *args, **kwargs):super().__init__(*args, **kwargs)widget = RazorPayCheckoutWidget(- payment=self.payment, **self.gateway_params)+ payment_information=payment_information, **gateway_params)self.fields['razorpay'] = forms.CharField(widget=widget, required=False)- def process_payment(self):- data = super(RazorPaymentForm, self).clean()- payment_token = data['razorpay_payment_id']- self.payment.charge(payment_token)- return self.payment+ def get_payment_token(self):+ return self.cleaned_data['razorpay_payment_id']diff --git a/saleor/payment/gateways/razorpay/utils.py b/saleor/payment/gateways/razorpay/utils.pyindex 7cab2f5635..d1b6082520 100644--- a/saleor/payment/gateways/razorpay/utils.py+++ b/saleor/payment/gateways/razorpay/utils.py@@ -4,7 +4,7 @@ from decimal import Decimaldef get_error_response(amount: Decimal, **additional_kwargs) -> dict:"""Create a place holder response for invalid/ failed requestsfor generated a failed transaction object."""- return dict(is_success=False, amount=amount, **additional_kwargs)+ return {'is_success': False, 'amount': amount, **additional_kwargs}def get_amount_for_razorpay(amount: Decimal) -> int:diff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.pyindex f3a958fce3..18891b7589 100644--- a/tests/gateway/test_razorpay.py+++ b/tests/gateway/test_razorpay.py@@ -11,6 +11,7 @@ from saleor.payment.gateways.razorpay import (logger, refund)from saleor.payment.gateways.razorpay.forms import (RazorPayCheckoutWidget, RazorPaymentForm)+from saleor.payment.utils import create_payment_informationTRANSACTION_AMOUNT = Decimal('61.33')@@ -55,8 +56,9 @@ def charged_payment(razorpay_payment):def test_checkout_widget_render_without_prefill(razorpay_payment, gateway_params):gateway_params['prefill'] = False+ payment_info = create_payment_information(razorpay_payment)widget = RazorPayCheckoutWidget(- payment=razorpay_payment, attrs={'data-custom': '123'},+ payment_information=payment_info, attrs={'data-custom': '123'},**gateway_params)assert widget.render() == ('<script data-amount="8000" data-buttontext="Pay now with Razorpay" '@@ -67,8 +69,9 @@ def test_checkout_widget_render_without_prefill(razorpay_payment, gateway_paramsdef test_checkout_widget_render_with_prefill(razorpay_payment, gateway_params):+ payment_info = create_payment_information(razorpay_payment)widget = RazorPayCheckoutWidget(- payment=razorpay_payment, **gateway_params)+ payment_information=payment_info, **gateway_params)assert widget.render() == ('<script data-amount="8000" data-buttontext="Pay now with Razorpay" ''data-currency="INR" data-description="Total payment" '@@ -79,24 +82,24 @@ def test_checkout_widget_render_with_prefill(razorpay_payment, gateway_params):def test_checkout_form(razorpay_payment, gateway_params):+ payment_info = create_payment_information(razorpay_payment)form = RazorPaymentForm(data={'razorpay_payment_id': '123'},- payment=razorpay_payment,- gateway=None, gateway_params=gateway_params)+ payment_information=payment_info,+ gateway_params=gateway_params)assert form.is_valid()- with patch.object(razorpay_payment, 'charge') as mocked_charge:- assert form.process_payment() == razorpay_payment- mocked_charge.assert_called_once_with('123')def test_check_payment_supported(razorpay_payment):- found_error = check_payment_supported(razorpay_payment)+ payment_info = create_payment_information(razorpay_payment)+ found_error = check_payment_supported(payment_info)assert not found_errordef test_check_payment_supported_non_supported(razorpay_payment):razorpay_payment.currency = 'USD'- found_error = check_payment_supported(razorpay_payment)+ payment_info = create_payment_information(razorpay_payment)+ found_error = check_payment_supported(payment_info)assert found_error@@ -139,21 +142,22 @@ def test_charge(mocked_gateway.return_value.payment.capture.return_value = (razorpay_success_response)+ payment_info = create_payment_information(+ razorpay_payment, payment_token=payment_token,+ amount=TRANSACTION_AMOUNT)+# Attempt charging- txn, error = charge(- razorpay_payment, payment_token,- TRANSACTION_AMOUNT, **gateway_params)+ response = charge(payment_info, **gateway_params)# Ensure the was no error returned- assert not error- assert txn.is_success+ assert not response['error']+ assert response['is_success']- assert txn.payment == razorpay_payment- 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']+ assert response['kind'] == TransactionKind.CHARGE+ assert response['amount'] == TRANSACTION_AMOUNT+ assert response['currency'] == razorpay_success_response['currency']+ assert response['raw_response'] == razorpay_success_response+ assert response['transaction_id'] == razorpay_success_response['id']@pytest.mark.integration@@ -164,19 +168,21 @@ def test_charge_unsupported_currency(razorpay_payment, gateway_params):# Data to be passedpayment_token = '123'+ payment_info = create_payment_information(+ razorpay_payment, payment_token=payment_token,+ amount=TRANSACTION_AMOUNT)+# Attempt charging- txn, error = charge(- razorpay_payment, payment_token,- TRANSACTION_AMOUNT, **gateway_params)+ response = charge(payment_info, **gateway_params)# Ensure a error was returned- assert error == errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'}- assert not txn.is_success+ assert response['error'] == (+ errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'})+ assert not response['is_success']- # Ensure the transaction is correctly set- assert txn.payment == razorpay_payment- assert txn.kind == TransactionKind.CHARGE- assert txn.token == payment_token+ # Ensure the response is correctly set+ assert response['kind'] == TransactionKind.CHARGE+ assert response['transaction_id'] == payment_token@patch.object(logger, 'exception')@@ -194,19 +200,20 @@ def test_charge_invalid_request(# that should trigger the expected error.mocked_gateway.return_value.payment.capture.side_effect = BadRequestError()+ payment_info = create_payment_information(+ razorpay_payment, payment_token=payment_token,+ amount=TRANSACTION_AMOUNT)+# Attempt charging- txn, error = charge(- razorpay_payment, payment_token,- TRANSACTION_AMOUNT, **gateway_params)+ response = charge(payment_info, **gateway_params)# Ensure an error was returned- assert error == errors.INVALID_REQUEST- assert not txn.is_success+ assert response['error'] == errors.INVALID_REQUEST+ assert not response['is_success']- # Ensure the transaction is correctly set- assert txn.payment == razorpay_payment- assert txn.kind == TransactionKind.CHARGE- assert txn.token == payment_token+ # Ensure the response is correctly set+ assert response['kind'] == TransactionKind.CHARGE+ assert response['transaction_id'] == payment_token# Ensure the HTTP error was loggedassert mocked_logger.call_count == 1@@ -224,20 +231,21 @@ def test_refund(mocked_gateway.return_value.payment.refund.return_value = (razorpay_success_response)+ payment_info = create_payment_information(+ charged_payment, amount=TRANSACTION_AMOUNT)+# Attempt charging- txn, error = refund(- charged_payment, TRANSACTION_AMOUNT, **gateway_params)+ response = refund(payment_info, **gateway_params)# Ensure the was no error returned- assert not error- assert txn.is_success+ assert not response['error']+ assert response['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']+ assert response['kind'] == TransactionKind.REFUND+ assert response['amount'] == TRANSACTION_AMOUNT+ assert response['currency'] == razorpay_success_response['currency']+ assert response['raw_response'] == razorpay_success_response+ assert response['transaction_id'] == razorpay_success_response['id']@pytest.mark.integration@@ -246,42 +254,19 @@ def test_refund_unsupported_currency(# Set the payment currency to an unsupported currencyrazorpay_payment.currency = 'USD'- # Attempt charging- txn, error = refund(- razorpay_payment, TRANSACTION_AMOUNT, **gateway_params)-- # Ensure a error was returned- assert error == errors.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---@patch('razorpay.Client')-def test_refund_not_paid(- mocked_gateway,- razorpay_payment,- razorpay_success_response,- gateway_params):-- # Mock the gateway response to a success response- mocked_gateway.return_value.payment.refund.return_value = (- razorpay_success_response)+ payment_info = create_payment_information(+ razorpay_payment, amount=TRANSACTION_AMOUNT)# Attempt charging- txn, error = refund(- razorpay_payment, TRANSACTION_AMOUNT, **gateway_params)+ response = refund(payment_info, **gateway_params)# Ensure a error was returned- assert error == errors.ORDER_NOT_CHARGED- assert not txn.is_success+ assert response['error'] == (+ errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'})+ assert not response['is_success']- # Ensure the transaction is correctly set- assert txn.payment == razorpay_payment- assert txn.kind == TransactionKind.REFUND+ # Ensure the kind is correctly set+ assert response['kind'] == TransactionKind.REFUND@pytest.mark.integration@@ -299,16 +284,16 @@ def test_refund_invalid_data(mocked_gateway.return_value.payment.refund.side_effect = ServerError()# Attempt charging- txn, error = refund(- charged_payment, TRANSACTION_AMOUNT, **gateway_params)+ payment_info = create_payment_information(+ charged_payment, amount=TRANSACTION_AMOUNT)+ response = refund(payment_info, **gateway_params)# Ensure a error was returned- assert error == errors.SERVER_ERROR- assert not txn.is_success+ assert response['error'] == errors.SERVER_ERROR+ assert not response['is_success']# Ensure the transaction is correctly set- assert txn.payment == charged_payment- assert txn.kind == TransactionKind.REFUND+ assert response['kind'] == TransactionKind.REFUND# Ensure the HTTP error was loggedassert mocked_logger.call_count == 1