Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extract functions for creating payments and reuse them
Marcin Gębala6193f00a95b4
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 8160fee198..2f42417c0e 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -30,10 +30,9 @@ from ...menu.models import Menufrom ...order.models import Fulfillment, Orderfrom ...order.utils import update_order_statusfrom ...page.models import Page-from ...payment.models import Paymentfrom ...payment.utils import (- gateway_authorize, gateway_capture, gateway_refund, gateway_void,- get_billing_data)+ create_payment, gateway_authorize, gateway_capture, gateway_refund,+ gateway_void)from ...product.models import (Attribute, AttributeValue, Category, Collection, Product, ProductImage,ProductType, ProductVariant)@@ -313,16 +312,16 @@ def create_fake_user():# We don't want to spam the console with payment confirmations sent to# fake customers.@patch('saleor.order.emails.send_payment_confirmation.delay')-def create_payment(mock_email_confirmation, order):- payment = Payment.objects.create(+def create_fake_payment(mock_email_confirmation, order):+ payment = create_payment(gateway=settings.DUMMY,customer_ip_address=fake.ipv4(),- is_active=True,+ email=order.user_email,order=order,- token=str(uuid.uuid4()),+ payment_token=str(uuid.uuid4()),total=order.total.gross.amount,currency=order.total.gross.currency,- **get_billing_data(order))+ billing_address=order.billing_address)# Create authorization transactiongateway_authorize(payment, payment.token)@@ -410,7 +409,7 @@ def create_fake_order(discounts, taxes):order.weight = weightorder.save()- create_payment(order=order)+ create_fake_payment(order=order)create_fulfillments(order)return orderdiff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex ebc49894bd..4b413d7db4 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -3,7 +3,6 @@ from django.conf import settingsfrom django.core.validators import MinValueValidatorfrom django.urls import reverse, reverse_lazyfrom django.utils.translation import npgettext_lazy, pgettext_lazy-from django_prices.forms import MoneyFieldfrom ...account.i18n import (AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField)@@ -19,9 +18,9 @@ from ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,change_order_line_quantity, recalculate_order)from ...payment import ChargeStatus, CustomPaymentChoices, PaymentError-from ...payment.models import Paymentfrom ...payment.utils import (- gateway_capture, gateway_refund, gateway_void, get_billing_data)+ clean_mark_order_as_paid, gateway_capture, gateway_refund, gateway_void,+ mark_order_as_paid)from ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stockfrom ...shipping.models import ShippingMethod@@ -342,26 +341,18 @@ class OrderMarkAsPaidForm(forms.Form):def __init__(self, *args, **kwargs):self.order = kwargs.pop('order')+ self.user = kwargs.pop('user')super().__init__(*args, **kwargs)def clean(self):super().clean()- if self.order.payments.exists():- raise forms.ValidationError(- pgettext_lazy(- 'Mark order as paid form error',- 'Orders with payments can not be manually marked as paid'))+ try:+ clean_mark_order_as_paid(order)+ except PaymentError as e:+ raise forms.ValidationError(str(e))def save(self):- defaults = {- 'total': self.order.total.gross.amount,- 'captured_amount': self.order.total.gross.amount,- 'currency': self.order.total.gross.currency,- **get_billing_data(self.order)}- Payment.objects.get_or_create(- gateway=CustomPaymentChoices.MANUAL,- charge_status=ChargeStatus.CHARGED, order=self.order,- defaults=defaults)+ mark_order_as_paid(self.order, self.user)class CancelOrderLineForm(forms.Form):diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 90fb22b91f..dea22bc9ea 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -533,7 +533,8 @@ def order_invoice(request, order_pk):def mark_order_as_paid(request, order_pk):order = get_object_or_404(Order.objects.confirmed(), pk=order_pk)status = 200- form = OrderMarkAsPaidForm(request.POST or None, order=order)+ form = OrderMarkAsPaidForm(+ request.POST or None, order=order, user=request.user)if form.is_valid():with transaction.atomic():form.save()diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 56ca6c48b5..f79898bc12 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -448,12 +448,13 @@ class CheckoutComplete(BaseMutation):order = graphene.Field(Order, description='Placed order')class Arguments:- checkout_id = graphene.ID(description='Checkout ID')+ checkout_id = graphene.ID(description='Checkout ID', required=True)class Meta:description = (- 'Completes the checkout, creates an order from it and '- 'charges the customer\'s funding source.')+ 'Completes the checkout. As a result a new order is created and '+ 'a payment charge is made. This action requires a succesfull '+ 'payment before it can be performed.')@classmethoddef mutate(cls, root, info, checkout_id):diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex c356694304..bd5a92eb51 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -41,6 +41,7 @@ class Checkout(CountableDjangoObjectType):available_payment_gateways = graphene.List(PaymentGatewayEnum, description='List of available payment gateways.',required=True)+ email = graphene.String(description='Email of a customer', required=True)is_shipping_required = graphene.Boolean(description='Returns True, if checkout requires shipping.',required=True)diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 82aa9d0e3f..00c3278487 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -5,10 +5,10 @@ from ....account.models import Userfrom ....core.utils.taxes import ZERO_TAXED_MONEYfrom ....order import OrderEvents, modelsfrom ....order.utils import cancel_order-from ....payment import ChargeStatus, CustomPaymentChoices, PaymentError-from ....payment.models import Payment+from ....payment import CustomPaymentChoices, PaymentErrorfrom ....payment.utils import (- gateway_capture, gateway_refund, gateway_void, get_billing_data)+ clean_mark_order_as_paid, gateway_capture, gateway_refund, gateway_void,+ mark_order_as_paid)from ....shipping.models import ShippingMethod as ShippingMethodModelfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation@@ -53,16 +53,6 @@ def clean_order_cancel(order, errors):return errors-def clean_order_mark_as_paid(order, errors):- if order and order.payments.exists():- errors.append(- Error(- field='payment',- message='Orders with payments can not be manually '- 'marked as paid.'))- return errors--def clean_order_capture(payment, amount, errors):if not payment:errors.append(@@ -272,22 +262,14 @@ class OrderMarkAsPaid(BaseMutation):def mutate(cls, root, info, id):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)- clean_order_mark_as_paid(order, errors)+ if order is not None:+ try:+ clean_mark_order_as_paid(order)+ except PaymentError as e:+ errors.append(Error(field='payment', message=str(e)))if errors:return OrderMarkAsPaid(errors=errors)- defaults = {- 'total': order.total.gross.amount,- 'captured_amount': order.total.gross.amount,- 'currency': order.total.gross.currency,- **get_billing_data(order)}- Payment.objects.get_or_create(- gateway=CustomPaymentChoices.MANUAL,- charge_status=ChargeStatus.CHARGED, order=order,- defaults=defaults)-- order.events.create(- type=OrderEvents.ORDER_MARKED_AS_PAID.value,- user=info.context.user)+ mark_order_as_paid(order, info.context.user)return OrderMarkAsPaid(order=order)@@ -312,7 +294,6 @@ class OrderCapture(BaseMutation):return OrderCapture(errors=errors)order = cls.get_node_or_error(info, id, errors, 'id', Order)- # FIXME adjust to multiple payments in the futurepayment = order.get_last_payment()clean_order_capture(payment, amount, errors)diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex b7ee858c8f..2a9a809a6c 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -1,9 +1,8 @@-import decimal-import graphenefrom django.conf import settingsfrom graphql_jwt.decorators import permission_required+from ...core.utils import get_client_ipfrom ...core.utils.taxes import get_taxes_for_addressfrom ...payment import PaymentErrorfrom ...payment.utils import (@@ -19,100 +18,73 @@ from .types import Paymentclass PaymentInput(graphene.InputObjectType):- gateway = PaymentGatewayEnum()- checkout_id = graphene.ID(description='Checkout ID.')+ gateway = graphene.Field(+ PaymentGatewayEnum, description='A gateway to use with that payment.',+ required=True)token = graphene.String(required=True,description=(- 'Client-side generated token, representing customer\'s billing'- 'data in secure manner.'))+ 'Client-side generated payment token, representing customer\'s '+ 'billing data in a secure manner.'))amount = Decimal(required=True,description=('Total amount of the transaction, including ''all taxes and discounts.'))- billing_address = AddressInput(description='Billing address')+ billing_address = AddressInput(+ description='Billing address.', required=True)class CheckoutPaymentCreate(BaseMutation, I18nMixin):- payment = graphene.Field(Payment, description='Updated payment')+ checkout = graphene.Field(Checkout, description='Related checkout object.')+ payment = graphene.Field(Payment, description='A newly created payment.')class Arguments:- input = PaymentInput(required=True, description='Payment details')+ checkout_id = graphene.ID(description='Checkout ID.', required=True)+ input = PaymentInput(+ description='Data required to create a new payment.',+ required=True)class Meta:- description = 'Creates credit card transaction.'+ description = 'Create a new payment for given checkout.'@classmethod- def mutate(cls, root, info, input):- # FIXME: improve error handling+ def mutate(cls, root, info, checkout_id, input):errors = []checkout = cls.get_node_or_error(- info,- input['checkout_id'],- errors,- 'checkout_id',- only_type=Checkout)- if not checkout:+ info, checkout_id, errors, 'checkout_id', only_type=Checkout)+ billing_address, errors = cls.validate_address(+ input['billing_address'], errors, 'billing_address')++ if checkout is None or billing_address is None:return CheckoutPaymentCreate(errors=errors)- billing_data = {}- if input['billing_address']:- billing_address, errors = cls.validate_address(- input['billing_address'], errors, 'billing_address')- if not billing_address:- return CheckoutPaymentCreate(errors=errors)- billing_data = cls.clean_billing_address(billing_address)- extra_data = cls.get_extra_info(info)amount = input['amount']checkout_total = checkout.get_total(discounts=info.context.discounts,- taxes=get_taxes_for_address(checkout.shipping_address))-- if decimal.Decimal(str(amount)) != checkout_total.gross.amount:+ taxes=get_taxes_for_address(checkout.billing_address))+ if amount < checkout_total.gross.amount:cls.add_error(errors, 'amount','Partial payments are not allowed, ''amount should be equal checkout\'s total.')return CheckoutPaymentCreate(errors=errors)+ extra_data = {+ 'customer_user_agent': info.context.META.get('HTTP_USER_AGENT')}+payment = create_payment(+ gateway=input['gateway'],+ payment_token=input['token'],total=amount,currency=settings.DEFAULT_CURRENCY,- gateway=input['gateway'],- billing_email=checkout.email,- is_active=True,+ email=checkout.email,+ billing_address=billing_address,extra_data=extra_data,- checkout=checkout,- token=input['token'],- **billing_data)+ customer_ip_address=get_client_ip(info),+ checkout=checkout)return CheckoutPaymentCreate(payment=payment, 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_company_name': billing_address.company_name,- 'billing_address_1': billing_address.street_address_1,- 'billing_address_2': billing_address.street_address_2,- 'billing_city': billing_address.city,- 'billing_postal_code': billing_address.postal_code,- 'billing_country_code': billing_address.country.code,- '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 PaymentAuthorize(BaseMutation):payment = graphene.Field(Payment, description='Updated payment')diff --git a/saleor/order/views.py b/saleor/order/views.pyindex f21754d2c2..0935e6e1f6 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -1,10 +1,9 @@import logging-from django.conf import settingsfrom django.contrib import auth, messagesfrom django.contrib.auth.decorators import login_requiredfrom django.db import transaction-from django.http import Http404, HttpResponseForbidden+from django.http import HttpResponseForbiddenfrom django.shortcuts import get_object_or_404, redirectfrom django.template.response import TemplateResponsefrom django.urls import reverse@@ -16,9 +15,8 @@ from ..account.forms import LoginFormfrom ..account.models import Userfrom ..core.utils import get_client_ipfrom ..payment import ChargeStatus, TransactionKind, get_payment_gateway-from ..payment.models import Paymentfrom ..payment.utils import (- create_payment_information, gateway_process_payment, get_billing_data)+ create_payment, create_payment_information, gateway_process_payment)from .forms import (CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentsForm)from .models import Order@@ -89,32 +87,31 @@ def payment(request, token):@check_order_statusdef start_payment(request, order, gateway):- # FIXME We should test this flow for each payment gateway- defaults = {- 'customer_ip_address': get_client_ip(request),- **get_billing_data(order)}- if gateway not in settings.CHECKOUT_PAYMENT_GATEWAYS:- raise Http404('%r is not a valid payment gateway' % (gateway,))+ payment_gateway, connection_params = get_payment_gateway(gateway)+ client_token = payment_gateway.get_client_token(+ connection_params=connection_params)+ extra_data = {'customer_user_agent': request.META.get('HTTP_USER_AGENT')}+with transaction.atomic():- payment, _ = Payment.objects.get_or_create(+ payment = create_payment(gateway=gateway,- is_active=True,- order=order,- defaults=defaults,+ payment_token=client_token,+ currency=order.total.gross.currency,+ email=order.user_email,+ billing_address=order.billing_address,+ customer_ip_address=get_client_ip(request),total=order.total.gross.amount,- currency=order.total.gross.currency)- if (- order.is_fully_paid()+ order=order,+ extra_data=extra_data)++ if (order.is_fully_paid()or payment.charge_status == ChargeStatus.FULLY_REFUNDED):return redirect(order.get_absolute_url())- payment_gateway, connection_params = get_payment_gateway(- payment.gateway)- client_token = payment_gateway.get_client_token(- connection_params=connection_params)payment_info = create_payment_information(payment)form = payment_gateway.create_form(- data=request.POST or None, payment_information=payment_info,+ data=request.POST or None,+ payment_information=payment_info,connection_params=connection_params)if form.is_valid():try:@@ -126,10 +123,11 @@ def start_payment(request, order, gateway):if order.is_fully_paid():return redirect('order:payment-success', token=order.token)return redirect(order.get_absolute_url())-ctx = {- 'form': form, 'payment': payment,- 'client_token': client_token, 'order': order}+ 'form': form,+ 'payment': payment,+ 'client_token': client_token,+ 'order': order}return TemplateResponse(request, payment_gateway.TEMPLATE_PATH, ctx)diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex c0aec7c14f..c6a089fb62 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -2,21 +2,24 @@ import jsonimport loggingfrom decimal import Decimalfrom functools import wraps-from typing import Dict, List, Optional+from typing import Dictfrom django.conf import settingsfrom django.core.serializers.json import DjangoJSONEncoderfrom django.db import transaction-from django.forms.models import model_to_dict-from prices import Money+from django.utils.translation import pgettext_lazy-from . import (- ChargeStatus, GatewayError, OperationType, PaymentError, TransactionKind,- get_payment_gateway)+from ..account.models import Address, Userfrom ..core import analytics+from ..checkout.models import Cartfrom ..order import OrderEvents, OrderEventsEmailsfrom ..order.emails import send_payment_confirmation+from ..order.models import Orderfrom .models import Payment, Transaction+from . import (+ CustomPaymentChoices, ChargeStatus, GatewayError, OperationType,+ PaymentError, TransactionKind, get_payment_gateway)+logger = logging.getLogger(__name__)@@ -42,24 +45,6 @@ def get_gateway_operation_func(gateway, operation_type):return gateway.refund-def get_billing_data(order):- """Extracts order's billing address into payment-friendly billing data."""- data = {}- if order.billing_address:- data = {- 'billing_first_name': order.billing_address.first_name,- 'billing_last_name': order.billing_address.last_name,- 'billing_company_name': order.billing_address.company_name,- 'billing_address_1': order.billing_address.street_address_1,- 'billing_address_2': order.billing_address.street_address_2,- 'billing_city': order.billing_address.city,- 'billing_postal_code': order.billing_address.postal_code,- 'billing_country_code': order.billing_address.country.code,- 'billing_email': order.user_email,- 'billing_country_area': order.billing_address.country_area}- return data--def create_payment_information(payment: Payment, payment_token: str = None,amount: Decimal = None) -> Dict:@@ -100,10 +85,11 @@ def handle_fully_paid_order(order):def validate_payment(view):- """Decorate a view to check if payment is authorized, so any actions+ """Require an active payment instance.++ Decorate a view to check if payment is authorized, so any actionscan be performed on it."""-@wraps(view)def func(payment: Payment, *args, **kwargs):if not payment.is_active:@@ -112,15 +98,77 @@ def validate_payment(view):return func-def create_payment(**payment_data):- payment, _ = Payment.objects.get_or_create(**payment_data)+def create_payment(+ gateway: str, payment_token: str, total: Decimal,+ currency: str, email: str, billing_address: Address,+ customer_ip_address: str = '',+ extra_data: Dict = None,+ checkout: Cart = None,+ order: Order = None+ ) -> Payment:+ """Create a payment instance.++ This method is responsible for creating payment instances that works for+ both Django views and GraphQL mutations.+ """+ defaults = {+ 'billing_email': email,+ 'billing_first_name': billing_address.first_name,+ 'billing_last_name': billing_address.last_name,+ 'billing_company_name': billing_address.company_name,+ 'billing_address_1': billing_address.street_address_1,+ 'billing_address_2': billing_address.street_address_2,+ 'billing_city': billing_address.city,+ 'billing_postal_code': billing_address.postal_code,+ 'billing_country_code': billing_address.country.code,+ 'billing_country_area': billing_address.country_area,+ 'currency': currency,+ 'customer_ip_address': customer_ip_address,+ 'total': total}++ if extra_data is None:+ extra_data = {}++ data = {+ 'gateway': gateway,+ 'token': payment_token,+ 'extra_data': extra_data}++ if order is not None:+ data['order'] = order+ if checkout is not None:+ data['checkout'] = checkout++ payment, _ = Payment.objects.get_or_create(defaults=defaults, **data)return payment+def mark_order_as_paid(order: Order, request_user: User):+ """Mark order as paid.++ Allows to create a payment for an order without actually performing any+ payment by the gateway.+ """+ payment = create_payment(+ gateway=CustomPaymentChoices.MANUAL,+ payment_token='',+ currency=order.total.gross.currency,+ email=order.user_email,+ billing_address=order.billing_address,+ total=order.total.gross.amount,+ order=order)+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount = order.total.gross.amount+ payment.save(update_fields=['captured_amount', 'charge_status'])+ order.events.create(+ type=OrderEvents.ORDER_MARKED_AS_PAID.value, user=request_user)++def create_transaction(payment: Payment, kind: str, payment_information: Dict,gateway_response: Dict = None, error_msg=None) -> Transaction:- """Creates a Transaction based on transaction kind and gateway response."""+ """Create a transaction based on transaction kind and gateway response."""if gateway_response is None:gateway_response = {}@@ -149,7 +197,7 @@ def gateway_get_client_token(gateway_name: str):def clean_charge(payment: Payment, amount: Decimal):- """Checks if payment can be charged."""+ """Check if payment can be charged."""if amount <= 0:raise PaymentError('Amount should be a positive number.')if not payment.can_charge():@@ -160,7 +208,7 @@ def clean_charge(payment: Payment, amount: Decimal):def clean_capture(payment: Payment, amount: Decimal):- """Checks if payment can be captured."""+ """Check if payment can be captured."""if amount <= 0:raise PaymentError('Amount should be a positive number.')if not payment.can_capture():@@ -171,15 +219,25 @@ def clean_capture(payment: Payment, amount: Decimal):def clean_authorize(payment: Payment):- """Checks if payment can be authorized."""+ """Check if payment can be authorized."""if not payment.can_authorize():raise PaymentError('Charged transactions cannot be authorized again.')+def clean_mark_order_as_paid(order: Order):+ """Check if an order can be marked as paid."""+ if order.payments.exists():+ raise PaymentError(+ pgettext_lazy(+ 'Mark order as paid validation error',+ 'Orders with payments can not be manually marked as paid'))++def call_gateway(operation_type, payment, payment_token, **extra_params):"""Helper that calls the passed gateway function and handles exceptions.- Additionally does validation of the returned gateway response."""+ Additionally does validation of the returned gateway response.+ """gateway, connection_params = get_payment_gateway(payment.gateway)gateway_response = Noneerror_msg = Nonediff --git a/tests/test_payment.py b/tests/test_payment.pyindex b1c90b2444..c406a38d94 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -17,7 +17,7 @@ from saleor.payment.utils import (clean_authorize, clean_capture, clean_charge, create_payment,create_payment_information, create_transaction, gateway_authorize,gateway_capture, gateway_charge, gateway_get_client_token,- gateway_process_payment, gateway_refund, gateway_void, get_billing_data,+ gateway_process_payment, gateway_refund, gateway_void,handle_fully_paid_order, validate_gateway_response, validate_payment)NOT_ACTIVE_PAYMENT_ERROR = 'This payment is no longer active.'@@ -68,28 +68,7 @@ def dummy_response(payment_dummy, transaction_data, transaction_token):'error': EXAMPLE_ERROR,'amount': payment_dummy.total,'currency': payment_dummy.currency,- 'kind': TransactionKind.AUTH,- }---def test_get_billing_data(order):- assert order.billing_address- result = get_billing_data(order)- expected_result = {- 'billing_first_name': order.billing_address.first_name,- 'billing_last_name': order.billing_address.last_name,- 'billing_company_name': order.billing_address.company_name,- 'billing_address_1': order.billing_address.street_address_1,- 'billing_address_2': order.billing_address.street_address_2,- 'billing_city': order.billing_address.city,- 'billing_postal_code': order.billing_address.postal_code,- 'billing_country_code': order.billing_address.country.code,- 'billing_email': order.user_email,- 'billing_country_area': order.billing_address.country_area}- assert result == expected_result-- order.billing_address = None- assert get_billing_data(order) == {}+ 'kind': TransactionKind.AUTH}def test_get_payment_gateway_not_allowed_checkout_choice(settings):