Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove deprecated Razorpay payment gateway plugin (#19552)
Lukasz Ostrowski6a6036124af4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34cb811153..88186d080c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ All notable, unreleased changes to this project will be documented in this file.### Breaking changes- Removed the deprecated Authorize.Net payment gateway plugin (`mirumee.payments.authorize_net`).+- Removed the deprecated Razorpay payment gateway plugin (`mirumee.payments.razorpay`).- Removed the deprecated Braintree payment gateway plugin (`mirumee.payments.braintree`).- Apps will be no longer to be granted with `MANAGE_APPS` permission. In certain cases, this permission was able to be assigned by the authorized user.App with such permission was not able to *act* like an admin app, but permission technically was granted.diff --git a/pyproject.toml b/pyproject.tomlindex 4718523a33..70f1d2d332 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -54,7 +54,6 @@ dependencies = ["python-http-client>=3.3.7,<4","python-json-logger>=0.1.11,<3.3.0","pytimeparse>=1.1.8,<2",- "razorpay~=1.2","redis>=5.0.1,<6","requests>=2.33.0,<3","requests-hardened>=1.3.0b1,<2.0.0",diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.pydeleted file mode 100644index 9218c0df18..0000000000--- a/saleor/payment/gateways/razorpay/__init__.py+++ /dev/null@@ -1,161 +0,0 @@-import logging-import uuid-from decimal import Decimal--import razorpay-import razorpay.errors--from ....core.telemetry import saleor_attributes, tracer-from ... import TransactionKind-from ...interface import GatewayConfig, GatewayResponse, PaymentData-from . import errors-from .utils import get_amount_for_razorpay, get_error_response--# 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.-RAZORPAY_EXCEPTIONS = (- razorpay.errors.BadRequestError,- razorpay.errors.GatewayError,- razorpay.errors.ServerError,-)--# Get the logger for this file, it will allow us to log-# error responses from razorpay.-logger = logging.getLogger(__name__)---def _generate_response(- payment_information: PaymentData, kind: str, data: dict-) -> GatewayResponse:- """Generate Saleor transaction information from the payload or from passed data."""- return GatewayResponse(- transaction_id=data.get("id", payment_information.token), # type: ignore[arg-type]- action_required=False,- kind=kind,- amount=data.get("amount", payment_information.amount),- currency=data.get("currency", payment_information.currency),- error=data.get("error"),- is_success=data.get("is_success", True),- raw_response=data,- )---def check_payment_supported(payment_information: PaymentData) -> str | None:- """Check that a given payment is supported."""- if payment_information.currency not in SUPPORTED_CURRENCIES:- return errors.UNSUPPORTED_CURRENCY % {"currency": payment_information.currency}- return None---def get_error_message_from_razorpay_error(exc: BaseException) -> str:- """Convert a Razorpay error to a user-friendly error message.-- It also logs the exception to stderr.- """- logger.exception(exc)- if isinstance(exc, razorpay.errors.BadRequestError):- return errors.INVALID_REQUEST- return errors.SERVER_ERROR---def clean_razorpay_response(response: dict):- """Convert the Razorpay response to our internal representation.-- As the Razorpay response payload contains the final amount- in paisa, we convert the amount to Indian Rupees (by dividing by 100).- """- response["amount"] = Decimal(response["amount"]) / 100---def get_client(public_key: str, private_key: str, **_):- """Create a Razorpay client from set-up application keys."""- razorpay_client = razorpay.Client(auth=(public_key, private_key))- return razorpay_client---def get_client_token(**_):- """Generate a random client token."""- return str(uuid.uuid4())---def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:- """Capture 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 return- a short user friendly description of the error after logging the error to stderr.- """- error = check_payment_supported(payment_information=payment_information)- razorpay_client = get_client(**config.connection_params)- razorpay_amount = get_amount_for_razorpay(payment_information.amount)-- if not error:- try:- with tracer.start_as_current_span("razorpay.payment.capture") as span:- span.set_attribute(saleor_attributes.COMPONENT, "payment")- response = razorpay_client.payment.capture(- 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(- payment_information.amount, error=error, id=payment_information.token- )- else:- response = get_error_response(- payment_information.amount, error=error, id=payment_information.token- )-- return _generate_response(- payment_information=payment_information,- kind=TransactionKind.CAPTURE,- data=response,- )---def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:- """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 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 = check_payment_supported(payment_information=payment_information)-- if error:- response = get_error_response(payment_information.amount, error=error)- else:- razorpay_client = get_client(**config.connection_params)- razorpay_amount = get_amount_for_razorpay(payment_information.amount)- try:- with tracer.start_as_current_span("razorpay.payment.refund") as span:- span.set_attribute(saleor_attributes.COMPONENT, "payment")- response = razorpay_client.payment.refund(- 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(payment_information.amount, error=error)-- return _generate_response(- payment_information=payment_information,- kind=TransactionKind.REFUND,- data=response,- )---def process_payment(- payment_information: PaymentData, config: GatewayConfig-) -> GatewayResponse:- return capture(payment_information=payment_information, config=config)diff --git a/saleor/payment/gateways/razorpay/errors.py b/saleor/payment/gateways/razorpay/errors.pydeleted file mode 100644index 192e11f886..0000000000--- a/saleor/payment/gateways/razorpay/errors.py+++ /dev/null@@ -1,4 +0,0 @@-ORDER_NOT_CHARGED = "Order was not charged."-INVALID_REQUEST = "The payment data was invalid."-SERVER_ERROR = "The order couldn't be proceeded."-UNSUPPORTED_CURRENCY = "The %(currency)s currency is not supported."diff --git a/saleor/payment/gateways/razorpay/plugin.py b/saleor/payment/gateways/razorpay/plugin.pydeleted file mode 100644index 9fd732015c..0000000000--- a/saleor/payment/gateways/razorpay/plugin.py+++ /dev/null@@ -1,111 +0,0 @@-from typing import TYPE_CHECKING--from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField--from ..utils import get_supported_currencies-from . import GatewayConfig, capture, process_payment, refund--GATEWAY_NAME = "Razorpay"--if TYPE_CHECKING:- from . import GatewayResponse, PaymentData---class DeprecatedRazorpayGatewayPlugin(BasePlugin):- """Deprecated.-- This plugin is deprecated and will be removed in future version.- """-- PLUGIN_NAME = GATEWAY_NAME- PLUGIN_ID = "mirumee.payments.razorpay"- DEFAULT_CONFIGURATION = [- {"name": "Public API key", "value": None},- {"name": "Secret API key", "value": None},- {"name": "Store customers card", "value": False},- {"name": "Automatic payment capture", "value": True},- {"name": "Supported currencies", "value": ""},- ]-- CONFIG_STRUCTURE = {- "Public API key": {- "type": ConfigurationTypeField.SECRET,- "help_text": "Provide public API key.",- "label": "Public API key",- },- "Secret API key": {- "type": ConfigurationTypeField.SECRET,- "help_text": "Provide Stripe secret API key.",- "label": "Secret API key",- },- "Store customers card": {- "type": ConfigurationTypeField.BOOLEAN,- "help_text": "Determines if Saleor should store cards on payments "- "in Stripe customer.",- "label": "Store customers card",- },- "Automatic payment capture": {- "type": ConfigurationTypeField.BOOLEAN,- "help_text": "Determines if Saleor should automatically capture payments.",- "label": "Automatic payment capture",- },- "Supported currencies": {- "type": ConfigurationTypeField.STRING,- "help_text": "Determines currencies supported by gateway."- " Please enter currency codes separated by a comma.",- "label": "Supported currencies",- },- }-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- configuration = {item["name"]: item["value"] for item in self.configuration}- self.config = GatewayConfig(- gateway_name=GATEWAY_NAME,- auto_capture=configuration["Automatic payment capture"],- supported_currencies=configuration["Supported currencies"],- connection_params={- "public_key": configuration["Public API key"],- "private_key": configuration["Secret API key"],- "prefill": True,- "store_name": None,- "store_image": None,- },- store_customer=configuration["Store customers card"],- )-- def _get_gateway_config(self):- return self.config-- def capture_payment(- self, payment_information: "PaymentData", previous_value- ) -> "GatewayResponse":- if not self.active:- return previous_value- return capture(payment_information, self._get_gateway_config())-- def refund_payment(- self, payment_information: "PaymentData", previous_value- ) -> "GatewayResponse":- if not self.active:- return previous_value- return refund(payment_information, self._get_gateway_config())-- def process_payment(- self, payment_information: "PaymentData", previous_value- ) -> "GatewayResponse":- if not self.active:- return previous_value- return process_payment(payment_information, self._get_gateway_config())-- def get_supported_currencies(self, previous_value):- if not self.active:- return previous_value- config = self._get_gateway_config()- return get_supported_currencies(config, GATEWAY_NAME)-- def get_payment_config(self, previous_value):- if not self.active:- return previous_value- config = self._get_gateway_config()- return [{"field": "api_key", "value": config.connection_params["public_key"]}]diff --git a/saleor/payment/gateways/razorpay/tests/__init__.py b/saleor/payment/gateways/razorpay/tests/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/payment/gateways/razorpay/tests/test_razorpay.py b/saleor/payment/gateways/razorpay/tests/test_razorpay.pydeleted file mode 100644index 9d6dcdcde2..0000000000--- a/saleor/payment/gateways/razorpay/tests/test_razorpay.py+++ /dev/null@@ -1,262 +0,0 @@-from decimal import Decimal-from unittest.mock import patch--import pytest-from razorpay.errors import BadRequestError, ServerError--from .... import ChargeStatus, TransactionKind-from ....interface import GatewayConfig-from ....utils import create_payment_information-from .. import (- capture,- check_payment_supported,- clean_razorpay_response,- errors,- get_amount_for_razorpay,- get_client,- get_client_token,- logger,- refund,-)--TRANSACTION_AMOUNT = Decimal("61.33")---def gateway_config():- return GatewayConfig(- gateway_name="razorpay",- auto_capture=False,- supported_currencies="USD",- connection_params={- "public_key": "public",- "private_key": "secret",- "prefill": True,- "store_name": "Saleor",- "store_image": "image.png",- },- )---def razorpay_success_response():- return {- "id": "transaction123",- "amount": get_amount_for_razorpay(TRANSACTION_AMOUNT),- "currency": "INR",- }---def razorpay_payment(payment_dummy):- payment_dummy.currency = "INR"- return payment_dummy---def charged_payment(razorpay_payment):- razorpay_payment.captured_amount = razorpay_payment.total- razorpay_payment.charge_status = ChargeStatus.FULLY_CHARGED- razorpay_payment.save(update_fields=["captured_amount", "charge_status"])-- razorpay_payment.transactions.create(- amount=razorpay_payment.total,- kind=TransactionKind.CAPTURE,- gateway_response={},- is_success=True,- )- return razorpay_payment---def test_check_payment_supported(razorpay_payment):- payment_info = create_payment_information(razorpay_payment)- found_error = check_payment_supported(payment_info)- assert not found_error---def test_check_payment_supported_non_supported(razorpay_payment):- razorpay_payment.currency = "USD"- payment_info = create_payment_information(razorpay_payment)- found_error = check_payment_supported(payment_info)- assert found_error---def test_get_amount_for_razorpay():- assert get_amount_for_razorpay(Decimal("61.33")) == 6133---def test_clean_razorpay_response():- response = {"amount": 6133}- clean_razorpay_response(response)- assert response["amount"] == Decimal("61.33")---@patch("razorpay.Client")-def test_get_client(mocked_gateway, gateway_config):- get_client(**gateway_config.connection_params)- mocked_gateway.assert_called_once_with(auth=("public", "secret"))---def test_get_client_token():- assert get_client_token()---@patch("razorpay.Client")-def test_charge(- mocked_gateway, razorpay_payment, razorpay_success_response, gateway_config-):- # Data to be passed- payment_token = "123"-- # Mock the gateway response to a success response- 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- response = capture(payment_info, gateway_config)-- # Ensure the was no error returned- assert not response.error- assert response.is_success-- assert response.kind == TransactionKind.CAPTURE- 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"]---def test_charge_unsupported_currency(razorpay_payment, gateway_config):- # Set the payment currency to an unsupported currency- razorpay_payment.currency = "USD"-- # Data to be passed- payment_token = "123"-- payment_info = create_payment_information(- razorpay_payment, payment_token=payment_token, amount=TRANSACTION_AMOUNT- )-- # Attempt charging- response = capture(payment_info, gateway_config)-- # Ensure a error was returned- assert response.error == (errors.UNSUPPORTED_CURRENCY % {"currency": "USD"})- assert not response.is_success-- # Ensure the response is correctly set- assert response.kind == TransactionKind.CAPTURE- assert response.transaction_id == payment_token--[email protected](logger, "exception")-@patch("razorpay.Client")-def test_charge_invalid_request(- mocked_gateway, mocked_logger, razorpay_payment, gateway_config-):- # Data to be passed- payment_token = "123"-- # Assign the side effect to the gateway's `capture()` method,- # 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- response = capture(payment_info, gateway_config)-- # Ensure an error was returned- assert response.error == errors.INVALID_REQUEST- assert not response.is_success-- # Ensure the response is correctly set- assert response.kind == TransactionKind.CAPTURE- assert response.transaction_id == payment_token-- # Ensure the HTTP error was logged- assert mocked_logger.call_count == 1---@patch("razorpay.Client")-def test_refund(- mocked_gateway, charged_payment, razorpay_success_response, gateway_config-):- # Mock the gateway response to a success response- mocked_gateway.return_value.payment.refund.return_value = razorpay_success_response-- payment_info = create_payment_information(- charged_payment, amount=TRANSACTION_AMOUNT- )-- # Attempt charging- response = refund(payment_info, gateway_config)-- # Ensure the was no error returned- assert not response.error- assert response.is_success-- 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"]---def test_refund_unsupported_currency(razorpay_payment, charged_payment, gateway_config):- # Set the payment currency to an unsupported currency- razorpay_payment.currency = "USD"-- payment_info = create_payment_information(- razorpay_payment, amount=TRANSACTION_AMOUNT- )-- # Attempt charging- response = refund(payment_info, gateway_config)-- # Ensure a error was returned- assert response.error == (errors.UNSUPPORTED_CURRENCY % {"currency": "USD"})- assert not response.is_success-- # Ensure the kind is correctly set- assert response.kind == TransactionKind.REFUND--[email protected](logger, "exception")-@patch("razorpay.Client")-def test_refund_invalid_data(- mocked_gateway,- mocked_logger,- charged_payment,- razorpay_success_response,- gateway_config,-):- # 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()-- # Attempt charging- payment_info = create_payment_information(- charged_payment, amount=TRANSACTION_AMOUNT- )- response = refund(payment_info, gateway_config)-- # Ensure a error was returned- assert response.error == errors.SERVER_ERROR- assert not response.is_success-- # Ensure the transaction is correctly set- assert response.kind == TransactionKind.REFUND-- # Ensure the HTTP error was logged- assert mocked_logger.call_count == 1diff --git a/saleor/payment/gateways/razorpay/utils.py b/saleor/payment/gateways/razorpay/utils.pydeleted file mode 100644index 74501195ba..0000000000--- a/saleor/payment/gateways/razorpay/utils.py+++ /dev/null@@ -1,17 +0,0 @@-from decimal import Decimal---def get_error_response(amount: Decimal, **additional_kwargs) -> dict:- """Create a placeholder response for invalid or failed requests.-- It is used to generate a failed transaction object.- """- return {"is_success": False, "amount": amount, **additional_kwargs}---def get_amount_for_razorpay(amount: Decimal) -> int:- """Convert an amount of Indian rupees to paisa (needed by Razorpay).-- Multiplies the value by 100.- """- return int(amount * 100)diff --git a/saleor/settings.py b/saleor/settings.pyindex b230d7c553..781f5721b9 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -928,7 +928,6 @@ BUILTIN_PLUGINS = ["saleor.payment.gateways.dummy.plugin.DeprecatedDummyGatewayPlugin","saleor.payment.gateways.dummy_credit_card.plugin.DeprecatedDummyCreditCardGatewayPlugin","saleor.payment.gateways.stripe.plugin.StripeGatewayPlugin",- "saleor.payment.gateways.razorpay.plugin.DeprecatedRazorpayGatewayPlugin","saleor.plugins.user_email.plugin.UserEmailPlugin","saleor.plugins.admin_email.plugin.AdminEmailPlugin","saleor.plugins.sendgrid.plugin.DeprecatedSendgridEmailPlugin",diff --git a/uv.lock b/uv.lockindex d64e2de2c5..bdc7bc02d6 100644--- a/uv.lock+++ b/uv.lock@@ -2343,18 +2343,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" },]-[[package]]-name = "razorpay"-version = "1.4.2"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "requests", marker = "platform_python_implementation != 'PyPy'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/97/fb/14d5baeffc5b812775bc34cb7d416aa090be6f5779c04aaf45d2ba17458b/razorpay-1.4.2.tar.gz", hash = "sha256:0d812030ba29e776e66d1ceaacc31635810fde18b66ff2591e582eb651bb5131", size = 194335, upload-time = "2024-03-19T12:12:08.904Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/e9/3d/07a25e3c6f3d65a319da30300f055d946860e90f705c05bb39524dc46f30/razorpay-1.4.2-py3-none-any.whl", hash = "sha256:aaf525baebc5001e5c54ae317a372c3c17c81314cedcbbf71aa0a2d3419a9757", size = 174302, upload-time = "2024-03-19T12:12:06.883Z" },-]-[[package]]name = "redis"version = "5.2.1"@@ -2535,7 +2523,6 @@ dependencies = [{ name = "python-magic", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'win32'" },{ name = "python-magic-bin", marker = "platform_python_implementation != 'PyPy' and sys_platform == 'win32'" },{ name = "pytimeparse", marker = "platform_python_implementation != 'PyPy'" },- { name = "razorpay", marker = "platform_python_implementation != 'PyPy'" },{ name = "redis", marker = "platform_python_implementation != 'PyPy'" },{ name = "requests", marker = "platform_python_implementation != 'PyPy'" },{ name = "requests-hardened", marker = "platform_python_implementation != 'PyPy'" },@@ -2645,7 +2632,6 @@ requires-dist = [{ name = "python-magic", marker = "sys_platform != 'win32'", specifier = ">=0.4.27,<0.5" },{ name = "python-magic-bin", marker = "sys_platform == 'win32'", specifier = ">=0.4.14,<0.5" },{ name = "pytimeparse", specifier = ">=1.1.8,<2" },- { name = "razorpay", specifier = "~=1.2" },{ name = "redis", specifier = ">=5.0.1,<6" },{ name = "requests", specifier = ">=2.33.0,<3" },{ name = "requests-hardened", specifier = ">=1.3.0b1,<2.0.0" },