Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve payments API, add more tests
Artur Smęt70f8a6463568
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex da75807179..36544dfb8b 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -114,7 +114,7 @@ class Query(ProductQueries):Page, query=graphene.String(description=DESCRIPTIONS['page']),description='List of the shop\'s pages.')- payment = graphene.Field(Payment, id=graphene.Argument(graphene.ID))+ payment = graphene.Field(PaymentMethod, id=graphene.Argument(graphene.ID))payment_client_token = graphene.Field(graphene.String, args={'gateway': PaymentGatewayEnum()})payments = DjangoFilterConnectionField(@@ -205,7 +205,7 @@ class Query(ProductQueries):return resolve_payment_client_token(gateway)def resolve_payments(self, info, query=None, **kwargs):- return resolve_payments(info, query)+ return resolve_payment_methods(info, query)@login_requireddef resolve_orders(@@ -282,6 +282,7 @@ class Mutations(ProductMutations):checkout_customer_detach = CheckoutCustomerDetach.Field()checkout_shipping_address_update = CheckoutShippingAddressUpdate.Field()checkout_email_update = CheckoutEmailUpdate.Field()+ checkout_payment_method_create = CheckoutPaymentMethodCreate.Field()menu_create = MenuCreate.Field()menu_delete = MenuDelete.Field()diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 5c702c733a..432b6dc919 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -1,25 +1,35 @@import graphene-from ..core.mutations import BaseMutation-from ..core.types.common import Decimal, Error-from .types import PaymentGatewayEnum+from graphql_jwt.decorators import permission_required+from ...payment import PaymentError-from ...payment.utils import create_payment_method, gateway_authorize+from ...payment.utils import create_payment_method, gateway_authorize, gateway_chargefrom ..account.types import AddressInput+from ..checkout.types import Checkout+from ..core.mutations import BaseMutation+from ..core.types.common import Decimal+from .types import PaymentGatewayEnum, PaymentMethod+++class PaymentMethodInput(graphene.InputObjectType):+ gateway = PaymentGatewayEnum()+ checkout_id = graphene.ID(description='Checkout ID')+ transaction_token = graphene.Argument(+ graphene.String,+ required=True,+ description='One time transaction token')+ amount = graphene.Argument(+ Decimal, required=True, description='Transaction amount')+ billing_address = AddressInput(description='Billing address')+ store_payment_method = graphene.Argument(+ graphene.Boolean,+ default_value=False,+ description='Store card for further usage')+-class CompleteCheckoutWithCreditCard(BaseMutation):+class CheckoutPaymentMethodCreate(BaseMutation):class Arguments:- gateway = PaymentGatewayEnum()- transaction_token = graphene.Argument(- graphene.String,- required=True,- description='One time transaction token')- amount = graphene.Argument(- Decimal, required=True, description='Transaction amount')- billing_address = AddressInput(description='Billing address')- store_payment_method = graphene.Argument(- graphene.Boolean,- default_value=False,- description='Store card as payment method')+ input = PaymentMethodInput(+ required=True, description='Payment method details')transaction_id = graphene.String()transaction_success = graphene.String()@@ -27,70 +37,91 @@ class CompleteCheckoutWithCreditCard(BaseMutation):class Meta:description = 'Creates credit card transaction.'- def mutate(- self,- info,- gateway,- transaction_token,- amount,- store_payment_method,- billing_address=None):- # FIXME: This mutation should also fetch cart+ @classmethod+ def mutate(cls, root, info, input):+ # FIXME: improve error handling+ errors = []+ checkout = cls.get_node_or_error(+ info, input['checkout_id'], errors, 'checkout_id',+ only_type=Checkout)+ if not checkout:+ return CheckoutPaymentMethodCreate(errors=errors)- client_ip = info.context.META['REMOTE_ADDR']- x_forwarded_for = info.context.META.get('HTTP_X_FORWARDED_FOR')- user_agent = info.context.META['HTTP_USER_AGENT']-- extra_data = {- 'customer_ip_address': x_forwarded_for if x_forwarded_for else client_ip,- 'customer_user_agent': user_agent- }billing_data = {}- if billing_address:- billing_data = {- 'billing_first_name': billing_address.first_name,- 'billing_last_name': billing_address.last_name,- 'billing_address_1': billing_address.street_address_1,- 'billing_address_2': billing_address.street_address_2,- 'billing_city': billing_address.city,- 'billing_postcide': billing_address.postal_code,- 'billing_country_code': billing_address.country,- 'billing_country_area': billing_address.country_area}+ extra_data = cls.get_extra_info(info)+ if input['billing_address']:+ billing_data = cls.clean_billing_address(input['billing_address'])+# create payment methodpayment_method = create_payment_method(- variant=gateway,- billing_email='',+ variant=input['gateway'],+ billing_email=checkout.email,extra_data=extra_data,- total=amount,+ total=input['amount'],+ checkout=checkout,**billing_data)# authorize paymenttry:- transaction = gateway_authorize(payment_method, transaction_token)+ transaction = gateway_authorize(payment_method, input['transaction_token'])except PaymentError as exc:- field = 'transaction_token'msg = str(exc)- return CompleteCheckoutWithCreditCard(- errors=[Error(field=field, message=msg)])+ cls.add_error(field='transaction_token', message=msg, errors=errors)- return CompleteCheckoutWithCreditCard(+ return CheckoutPaymentMethodCreate(transaction_id=transaction.token,- transaction_success=transaction.is_success)+ transaction_success=transaction.is_success, errors=errors)+ @classmethod+ def clean_billing_address(cls, billing_address):+ billing_data = {+ 'billing_first_name': billing_address.first_name,+ 'billing_last_name': billing_address.last_name,+ 'billing_address_1': billing_address.street_address_1,+ 'billing_address_2': billing_address.street_address_2,+ 'billing_city': billing_address.city,+ 'billing_postcode': billing_address.postal_code,+ 'billing_country_code': billing_address.country,+ 'billing_country_area': billing_address.country_area}+ return billing_data++ @classmethod+ def get_extra_info(cls, info):+ client_ip = info.context.META['REMOTE_ADDR']+ x_forwarded_for = info.context.META.get('HTTP_X_FORWARDED_FOR')+ user_agent = info.context.META.get('HTTP_USER_AGENT')+ customer_ip = x_forwarded_for if x_forwarded_for else client_ip+ return {+ 'customer_ip_address': customer_ip,+ 'customer_user_agent': user_agent}-# class PaymentMethodCreate(BaseMutation):-# pass-# class PaymentMethodUpdate(BaseMutation):-# pass+class PaymentMethodCharge(BaseMutation):++ class Arguments:+ payment_method_id = graphene.ID(+ required=True, description='Payment method ID')+ amount = graphene.Argument(+ Decimal, description='Transaction amount')-# class PaymentMethodDelete(BaseMutation):-# pass+ payment_method = graphene.Field(+ PaymentMethod, description='Updated payment method')-# class TransactionRefund(BaseMutation):-# pass-# class TransactionVoid(BaseMutation):-# pass+ @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 PaymentMethodCharge(errors=errors)++ try:+ gateway_charge(payment_method, amount=amount)+ except PaymentError as exc:+ msg = str(exc)+ cls.add_error(field='payment_method_id', message=msg, errors=errors)-# class PaymentMethodNonceCreate(BaseMutation):-# pass+ return PaymentMethodCharge(payment_method=payment_method, errors=errors)diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.pyindex af00140711..fb2396bd50 100644--- a/saleor/graphql/payment/resolvers.py+++ b/saleor/graphql/payment/resolvers.py@@ -1,22 +1,22 @@from graphql_jwt.decorators import login_required-from ...order import models+from ...payment import modelsfrom ...payment.utils import gateway_get_client_tokenfrom ..utils import filter_by_query_param, get_node-from .types import Payment+from .types import PaymentMethodPAYMENT_SEARCH_FIELDS = ['id']# @login_required-def resolve_payments(info, query):- queryset = models.Payment.objects.all().distinct()+def resolve_payment_methods(info, query):+ queryset = models.PaymentMethod.objects.all().distinct()queryset = filter_by_query_param(queryset, query, PAYMENT_SEARCH_FIELDS)return queryset# @login_required-def resolve_payment(info, id):- payment = get_node(info, id, only_type=Payment)+def resolve_payment_method(info, id):+ payment = get_node(info, id, only_type=PaymentMethod)return paymentdiff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex d32dc95a83..d84a9a3f45 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -1,17 +1,19 @@import graphenefrom graphene import relay-from ...order import models+from ...payment import PROVIDERS_ENUM, modelsfrom ..core.types.common import CountableDjangoObjectType-from ...payment import PROVIDERS_ENUM-from graphene import types+PaymentGatewayEnum = graphene.Enum.from_enum(PROVIDERS_ENUM)-class Payment(CountableDjangoObjectType):+class PaymentMethod(CountableDjangoObjectType):class Meta:- description = 'Represents payment.'+ description = 'Payment method'interfaces = [relay.Node]- model = models.Payment- exclude_fields = ['order']+ model = models.PaymentMethod-PaymentGatewayEnum = graphene.Enum.from_enum(PROVIDERS_ENUM)+class Transaction(CountableDjangoObjectType):+ class Meta:+ description = 'Single payment transaction'+ interfaces = [relay.Node]+ model = models.Transactiondiff --git a/tests/api/test_payment.py b/tests/api/test_payment.pynew file mode 100644index 0000000000..9cc0779c60--- /dev/null+++ b/tests/api/test_payment.py@@ -0,0 +1,132 @@+import json++import graphene+from django.shortcuts import reverse+from tests.utils import get_graphql_content+from saleor.payment.models import Transaction, PaymentMethodChargeStatus, TransactionType+++def test_checkout_add_payment_method(+ user_api_client, cart_with_item, graphql_address_data):+ cart = cart_with_item+ assert cart.user is None++ query = """+ mutation CheckoutPaymentMethodCreate($input: PaymentMethodInput!) {+ checkoutPaymentMethodCreate(input: $input) {+ transactionId,+ transactionSuccess,+ errors {+ field+ message+ }+ }+ }+ """+ checkout_id = graphene.Node.to_global_id('Checkout', cart.pk)++ variables = json.dumps({+ 'input': {+ 'checkoutId': checkout_id,+ 'gateway': 'DUMMY',+ 'transactionToken': 'sample-token',+ 'amount': str(cart.get_total().gross.amount),+ 'billingAddress': graphql_address_data,+ 'storePaymentMethod': False}+ })+ response = user_api_client.post(+ reverse('api'), {'query': query, 'variables': variables})+ content = get_graphql_content(response)+ assert 'errors' not in content+ data = content['data']['checkoutPaymentMethodCreate']+ assert not data['errors']+ transaction_id = data['transactionId']+ txn = Transaction.objects.filter(token=transaction_id).first()+ assert txn.transaction_type == TransactionType.AUTH+ assert txn is not None+ payment_method = txn.payment_method+ assert payment_method.checkout == cart+ assert payment_method.is_active+ assert payment_method.total == cart.get_total().gross.amount+ assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+++def test_payment_method_charge_success(admin_api_client, payment_method_dummy):++ payment_method = payment_method_dummy+ assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ 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})+ content = get_graphql_content(response)+ assert 'errors' not in content+ data = content['data']['paymentMethodCharge']+ assert not data['errors']+ 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.CHARGE+++def test_payment_method_charge_gateway_error(+ admin_api_client, payment_method_dummy, monkeypatch):++ payment_method = payment_method_dummy+ assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ 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+ })+ monkeypatch.setattr(+ 'saleor.payment.providers.dummy.dummy_success', lambda: False)+ response = admin_api_client.post(+ reverse('api'), {'query': query, 'variables': variables})+ content = get_graphql_content(response)+ data = content['data']['paymentMethodCharge']+ assert 'errors' in data+ errors = data['errors']+ assert errors[0]['field'] == 'paymentMethodId'+ payment_method_dummy.refresh_from_db()+ assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ assert payment_method.transactions.count() == 1+ txn = payment_method.transactions.first()+ assert txn.transaction_type == TransactionType.CHARGE+ assert not txn.is_success