Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add further payment API improvements
Artur Smętc60c16b6f738
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 36544dfb8b..e6b4fb6a30 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -45,6 +45,9 @@ from .page.types import Pagefrom .product.schema import ProductMutations, ProductQueriesfrom .payment.types import Payment, PaymentGatewayEnumfrom .payment.resolvers import resolve_payments, resolve_payment_client_token+from .payment.mutations import (+ CheckoutPaymentMethodCreate, PaymentMethodCharge, PaymentMethodRefund,+ PaymentMethodVoid)from .shipping.resolvers import resolve_shipping_zonesfrom .shipping.types import ShippingZonefrom .shipping.mutations import (diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 432b6dc919..2c2073c23c 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -2,7 +2,9 @@ import graphenefrom graphql_jwt.decorators import permission_requiredfrom ...payment import PaymentError-from ...payment.utils import create_payment_method, gateway_authorize, gateway_charge+from ...payment.utils import (+ create_payment_method, gateway_authorize, gateway_charge, gateway_refund,+ gateway_void)from ..account.types import AddressInputfrom ..checkout.types import Checkoutfrom ..core.mutations import BaseMutation@@ -31,8 +33,8 @@ class CheckoutPaymentMethodCreate(BaseMutation):input = PaymentMethodInput(required=True, description='Payment method details')- transaction_id = graphene.String()- transaction_success = graphene.String()+ payment_method = graphene.Field(+ PaymentMethod, description='Updated payment method')class Meta:description = 'Creates credit card transaction.'@@ -62,14 +64,13 @@ class CheckoutPaymentMethodCreate(BaseMutation):**billing_data)# authorize paymenttry:- transaction = gateway_authorize(payment_method, input['transaction_token'])+ gateway_authorize(payment_method, input['transaction_token'])except PaymentError as exc:msg = str(exc)- cls.add_error(field='transaction_token', message=msg, errors=errors)+ cls.add_error(field=None, message=msg, errors=errors)return CheckoutPaymentMethodCreate(- transaction_id=transaction.token,- transaction_success=transaction.is_success, errors=errors)+ payment_method=payment_method, errors=errors)@classmethoddef clean_billing_address(cls, billing_address):@@ -95,6 +96,7 @@ class CheckoutPaymentMethodCreate(BaseMutation):'customer_user_agent': user_agent}+class PaymentMethodCharge(BaseMutation):class Arguments:@@ -106,7 +108,6 @@ class PaymentMethodCharge(BaseMutation):payment_method = graphene.Field(PaymentMethod, description='Updated payment method')-@classmethod@permission_required('order.manage_orders')def mutate(cls, root, info, payment_method_id, amount=None):@@ -122,6 +123,56 @@ class PaymentMethodCharge(BaseMutation):gateway_charge(payment_method, amount=amount)except PaymentError as exc:msg = str(exc)- cls.add_error(field='payment_method_id', message=msg, errors=errors)+ cls.add_error(field=None, message=msg, errors=errors)return PaymentMethodCharge(payment_method=payment_method, errors=errors)+++class PaymentMethodRefund(PaymentMethodCharge):++ @classmethod+ @permission_required('order.manage_orders')+ def mutate(cls, root, info, payment_method_id, amount=None):+ errors = []+ payment_method = cls.get_node_or_error(+ info, payment_method_id, errors, 'payment_method_id',+ only_type=PaymentMethod)++ if not payment_method:+ return PaymentMethodRefund(errors=errors)++ try:+ gateway_refund(payment_method, amount=amount)+ except PaymentError as exc:+ msg = str(exc)+ cls.add_error(field=None, message=msg, errors=errors)++ return PaymentMethodRefund(payment_method=payment_method, errors=errors)+++class PaymentMethodVoid(BaseMutation):+ class Arguments:+ payment_method_id = graphene.ID(+ required=True, description='Payment method ID')++ payment_method = graphene.Field(+ PaymentMethod, description='Updated payment method')++ @classmethod+ @permission_required('order.manage_orders')+ def mutate(cls, root, info, payment_method_id, amount=None):+ errors = []+ payment_method = cls.get_node_or_error(+ info, payment_method_id, errors, 'payment_method_id',+ only_type=PaymentMethod)++ if not payment_method:+ return PaymentMethodVoid(errors=errors)++ try:+ gateway_void(payment_method)+ except PaymentError as exc:+ msg = str(exc)+ cls.add_error(field=None, message=msg, errors=errors)++ return PaymentMethodVoid(payment_method=payment_method, errors=errors)diff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex 9cc0779c60..bc7972f20e 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -1,21 +1,70 @@import json+import pytestimport graphenefrom django.shortcuts import reversefrom tests.utils import get_graphql_contentfrom saleor.payment.models import Transaction, PaymentMethodChargeStatus, TransactionType+CHARGE_QUERY = """+ mutation PaymentMethodCharge($paymentMethodId: ID!, $amount: Decimal!) {+ paymentMethodCharge(paymentMethodId: $paymentMethodId, amount: $amount) {+ paymentMethod {+ id,+ chargeStatus+ }+ errors {+ field+ message+ }+ }+ }+ """-def test_checkout_add_payment_method(- user_api_client, cart_with_item, graphql_address_data):- cart = cart_with_item- assert cart.user is None+REFUND_QUERY = """+ mutation PaymentMethodRefund($paymentMethodId: ID!, $amount: Decimal!) {+ paymentMethodRefund(paymentMethodId: $paymentMethodId, amount: $amount) {+ paymentMethod {+ id,+ chargeStatus+ }+ errors {+ field+ message+ }+ }+ }+ """- query = """+VOID_QUERY = """+ mutation PaymentMethodRefund($paymentMethodId: ID!, $amount: Decimal!) {+ paymentMethodRefund(paymentMethodId: $paymentMethodId, amount: $amount) {+ paymentMethod {+ id,+ chargeStatus+ }+ errors {+ field+ message+ }+ }+ }+ """++CREATE_QUERY = """mutation CheckoutPaymentMethodCreate($input: PaymentMethodInput!) {checkoutPaymentMethodCreate(input: $input) {- transactionId,- transactionSuccess,+ paymentMethod {+ transactions(first: 1) {+ edges {+ node {+ transactionType,+ token+ }+ }+ }+ chargeStatus+ }errors {fieldmessage@@ -23,6 +72,12 @@ def test_checkout_add_payment_method(}}"""++def test_checkout_add_payment_method(+ user_api_client, cart_with_item, graphql_address_data):+ cart = cart_with_item+ assert cart.user is None+checkout_id = graphene.Node.to_global_id('Checkout', cart.pk)variables = json.dumps({@@ -35,12 +90,12 @@ def test_checkout_add_payment_method('storePaymentMethod': False}})response = user_api_client.post(- reverse('api'), {'query': query, 'variables': variables})+ reverse('api'), {'query': CREATE_QUERY, 'variables': variables})content = get_graphql_content(response)assert 'errors' not in contentdata = content['data']['checkoutPaymentMethodCreate']assert not data['errors']- transaction_id = data['transactionId']+ transaction_id = data['paymentMethod']['transactions']['edges'][0]['node']['token']txn = Transaction.objects.filter(token=transaction_id).first()assert txn.transaction_type == TransactionType.AUTHassert txn is not None@@ -58,26 +113,12 @@ def test_payment_method_charge_success(admin_api_client, payment_method_dummy):payment_method_id = graphene.Node.to_global_id('PaymentMethod', payment_method_dummy.pk)- query = """- mutation PaymentMethodCharge($paymentMethodId: ID!, $amount: Decimal!) {- paymentMethodCharge(paymentMethodId: $paymentMethodId, amount: $amount) {- paymentMethod {- id,- chargeStatus- }- errors {- field- message- }- }- }- """variables = json.dumps({'paymentMethodId': payment_method_id,'amount': payment_method_dummy.total})response = admin_api_client.post(- reverse('api'), {'query': query, 'variables': variables})+ reverse('api'), {'query': CHARGE_QUERY, 'variables': variables})content = get_graphql_content(response)assert 'errors' not in contentdata = content['data']['paymentMethodCharge']@@ -97,20 +138,6 @@ def test_payment_method_charge_gateway_error(payment_method_id = graphene.Node.to_global_id('PaymentMethod', payment_method_dummy.pk)- query = """- mutation PaymentMethodCharge($paymentMethodId: ID!, $amount: Decimal!) {- paymentMethodCharge(paymentMethodId: $paymentMethodId, amount: $amount) {- paymentMethod {- id,- chargeStatus- }- errors {- field- message- }- }- }- """variables = json.dumps({'paymentMethodId': payment_method_id,'amount': payment_method_dummy.total@@ -118,15 +145,73 @@ def test_payment_method_charge_gateway_error(monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)response = admin_api_client.post(- reverse('api'), {'query': query, 'variables': variables})+ reverse('api'), {'query': CHARGE_QUERY, 'variables': variables})content = get_graphql_content(response)data = content['data']['paymentMethodCharge']assert 'errors' in dataerrors = data['errors']- assert errors[0]['field'] == 'paymentMethodId'+ assert errors[0]['field'] == None+ assert errors[0]['message'] is not Nonepayment_method_dummy.refresh_from_db()assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGEDassert payment_method.transactions.count() == 1txn = payment_method.transactions.first()assert txn.transaction_type == TransactionType.CHARGEassert not txn.is_success+++def test_payment_method_refund_success(admin_api_client, payment_method_dummy):++ payment_method = payment_method_dummy+ payment_method.charge_status = PaymentMethodChargeStatus.CHARGED+ payment_method.captured_amount = payment_method.total+ payment_method.save()+ payment_method_id = graphene.Node.to_global_id(+ 'PaymentMethod', payment_method.pk)++ variables = json.dumps({+ 'paymentMethodId': payment_method_id,+ 'amount': payment_method_dummy.total+ })+ response = admin_api_client.post(+ reverse('api'), {'query': REFUND_QUERY, 'variables': variables})+ content = get_graphql_content(response)+ assert 'errors' not in content+ data = content['data']['paymentMethodRefund']+ assert not data['errors']+ payment_method_dummy.refresh_from_db()+ assert payment_method.charge_status == PaymentMethodChargeStatus.FULLY_REFUNDED+ assert payment_method.transactions.count() == 1+ txn = payment_method.transactions.first()+ assert txn.transaction_type == TransactionType.REFUND+++def test_payment_method_refund_error(+ admin_api_client, payment_method_dummy, monkeypatch):++ payment_method = payment_method_dummy+ payment_method.charge_status = PaymentMethodChargeStatus.CHARGED+ payment_method.captured_amount = payment_method.total+ payment_method.save()+ payment_method_id = graphene.Node.to_global_id(+ 'PaymentMethod', payment_method_dummy.pk)+ variables = json.dumps({+ 'paymentMethodId': payment_method_id,+ 'amount': payment_method.total+ })+ monkeypatch.setattr(+ 'saleor.payment.providers.dummy.dummy_success', lambda: False)+ response = admin_api_client.post(+ reverse('api'), {'query': REFUND_QUERY, 'variables': variables})+ content = get_graphql_content(response)+ data = content['data']['paymentMethodRefund']+ assert 'errors' in data+ errors = data['errors']+ assert errors[0]['field'] == None+ assert errors[0]['message'] is not None+ payment_method_dummy.refresh_from_db()+ assert payment_method.charge_status == PaymentMethodChargeStatus.CHARGED+ assert payment_method.transactions.count() == 1+ txn = payment_method.transactions.first()+ assert txn.transaction_type == TransactionType.REFUND+ assert not txn.is_successdiff --git a/tests/conftest.py b/tests/conftest.pyindex 39485706a2..d479d44c08 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -98,6 +98,17 @@ def address(db): # pylint: disable=W0613country='PL',phone='+48713988102')+def graphql_address_data():+ return {+ 'firstName': 'John',+ 'lastName': 'Doe',+ 'streetAddress1': 'Wall st.',+ 'streetAddress2': '',+ 'postalCode': '902010',+ 'country': 'US',+ 'city': 'New York',+ 'countryArea': ''}@pytest.fixturedef customer_user(address): # pylint: disable=W0613