Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Require order or checkout instance to create a payment

Marcin Gębala4122e04fef53
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 2204f19b5b..55e6e58166 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -427,7 +427,6 @@ def create_fake_payment(mock_email_confirmation, order):
payment_token=str(uuid.uuid4()),
total=order.total.gross.amount,
currency=order.total.gross.currency,
- billing_address=order.billing_address,
)
# Create authorization transaction
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 10be0490fe..5dbf921800 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -325,10 +325,19 @@ class OrderMarkAsPaid(BaseMutation):
error_type_class = OrderError
error_type_field = "order_errors"
+ @classmethod
+ def clean_billing_address(cls, instance):
+ if not instance.billing_address:
+ raise ValidationError(
+ "Order billing address is required to mark order as paid.",
+ code=OrderErrorCode.BILLING_ADDRESS_NOT_SET,
+ )
+
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ cls.clean_billing_address(order)
try_payment_action(
order, info.context.user, None, clean_mark_order_as_paid, order
)
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 4ef37fe75c..6a31c5b37d 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -114,9 +114,8 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
checkout_total = cls.calculate_total(info, checkout)
amount = data.get("amount", checkout_total.gross.amount)
- billing_address = checkout.billing_address
- cls.clean_billing_address(billing_address)
+ cls.clean_billing_address(checkout.billing_address)
cls.clean_payment_amount(info, checkout_total, amount)
extra_data = {"customer_user_agent": info.context.META.get("HTTP_USER_AGENT")}
@@ -127,7 +126,6 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
total=amount,
currency=settings.DEFAULT_CURRENCY,
email=checkout.email,
- billing_address=billing_address,
extra_data=extra_data,
customer_ip_address=get_client_ip(info.context),
checkout=checkout,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 1972d23905..c36cda72c3 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2490,6 +2490,7 @@ type OrderError {
}
enum OrderErrorCode {
+ BILLING_ADDRESS_NOT_SET
CANNOT_CANCEL_FULFILLMENT
CANNOT_CANCEL_ORDER
CANNOT_DELETE
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 180f00be4c..ee2aa5083b 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -181,15 +181,11 @@ def mark_order_as_paid(order: "Order", request_user: "User"):
# pylint: disable=cyclic-import
from ..payment.utils import create_payment
- if not order.billing_address:
- raise Exception("Order does not have billing address")
-
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,
)
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 33b2c85f53..0383d59bcc 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -2,6 +2,7 @@ from enum import Enum
class OrderErrorCode(Enum):
+ BILLING_ADDRESS_NOT_SET = "billing_address_not_set"
CANNOT_CANCEL_FULFILLMENT = "cannot_cancel_fulfillment"
CANNOT_CANCEL_ORDER = "cannot_cancel_order"
CANNOT_DELETE = "cannot_delete"
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 2f5a5d90ed..9f9baa3a9f 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -2,9 +2,10 @@ from enum import Enum
class PaymentError(Exception):
- def __init__(self, message):
- super(PaymentError, self).__init__(message)
+ def __init__(self, message, code=None):
+ super(PaymentError, self).__init__(message, code)
self.message = message
+ self.code = code
class GatewayError(IOError):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 64ca5d658e..a837f0ac42 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -7,11 +7,11 @@ from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
-from ..account.models import Address
from ..checkout.models import Checkout
from ..order.actions import handle_fully_paid_order
from ..order.models import Order
from . import ChargeStatus, GatewayError, PaymentError, TransactionKind
+from .error_codes import PaymentErrorCode
from .interface import AddressData, GatewayResponse, PaymentData
from .models import Payment, Transaction
@@ -67,7 +67,6 @@ def create_payment(
total: Decimal,
currency: str,
email: str,
- billing_address: Address,
customer_ip_address: str = "",
payment_token: str = "",
extra_data: Dict = None,
@@ -79,6 +78,32 @@ def create_payment(
This method is responsible for creating payment instances that works for
both Django views and GraphQL mutations.
"""
+
+ if extra_data is None:
+ extra_data = {}
+
+ data = {
+ "is_active": True,
+ "customer_ip_address": customer_ip_address,
+ "extra_data": extra_data,
+ "token": payment_token,
+ }
+
+ if checkout:
+ data["checkout"] = checkout
+ billing_address = checkout.billing_address
+ elif order:
+ data["order"] = order
+ billing_address = order.billing_address
+ else:
+ raise TypeError("Must provide checkout or order to create a payment.")
+
+ if not billing_address:
+ raise PaymentError(
+ "Order does not have a billing address.",
+ code=PaymentErrorCode.BILLING_ADDRESS_NOT_SET.value,
+ )
+
defaults = {
"billing_email": email,
"billing_first_name": billing_address.first_name,
@@ -95,21 +120,6 @@ def create_payment(
"total": total,
}
- if extra_data is None:
- extra_data = {}
-
- data = {
- "is_active": True,
- "customer_ip_address": customer_ip_address,
- "extra_data": extra_data,
- "token": payment_token,
- }
-
- 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
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 428d901da0..2bd785c9b2 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -1551,6 +1551,32 @@ def test_order_mark_as_paid(
assert event_order_paid.user == staff_user
+def test_order_mark_as_paid_no_billing_address(
+ staff_api_client, permission_manage_orders, order_with_lines, staff_user
+):
+ order = order_with_lines
+ order_with_lines.billing_address = None
+ order_with_lines.save()
+
+ query = """
+ mutation markPaid($id: ID!) {
+ orderMarkAsPaid(id: $id) {
+ orderErrors {
+ code
+ }
+ }
+ }
+ """
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderMarkAsPaid"]["orderErrors"]
+ assert data[0]["code"] == OrderErrorCode.BILLING_ADDRESS_NOT_SET.name
+
+
ORDER_VOID = """
mutation voidOrder($id: ID!) {
orderVoid(id: $id) {
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index 0b1cf8bdf8..dbe73ab0b3 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -6,6 +6,7 @@ from django_countries.fields import Country
from saleor.checkout import calculations
from saleor.graphql.payment.enums import OrderAction, PaymentChargeStatusEnum
+from saleor.payment.error_codes import PaymentErrorCode
from saleor.payment.interface import CreditCardInfo, CustomerSource, TokenConfig
from saleor.payment.models import ChargeStatus, Payment, TransactionKind
from saleor.payment.utils import fetch_customer_id, store_customer_id
@@ -80,9 +81,9 @@ CREATE_QUERY = """
}
chargeStatus
}
- errors {
+ paymentErrors {
+ code
field
- message
}
}
}
@@ -108,7 +109,7 @@ def test_checkout_add_payment(user_api_client, checkout_with_item, address):
content = get_graphql_content(response)
data = content["data"]["checkoutPaymentCreate"]
- assert not data["errors"]
+ assert not data["paymentErrors"]
transactions = data["payment"]["transactions"]
assert not transactions
payment = Payment.objects.get()
@@ -141,7 +142,7 @@ def test_checkout_add_payment_default_amount(
response = user_api_client.post_graphql(CREATE_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["checkoutPaymentCreate"]
- assert not data["errors"]
+ assert not data["paymentErrors"]
transactions = data["payment"]["transactions"]
assert not transactions
payment = Payment.objects.get()
@@ -153,8 +154,10 @@ def test_checkout_add_payment_default_amount(
assert payment.charge_status == ChargeStatus.NOT_CHARGED
-def test_checkout_add_payment_bad_amount(user_api_client, checkout_with_item):
+def test_checkout_add_payment_bad_amount(user_api_client, checkout_with_item, address):
checkout = checkout_with_item
+ checkout.billing_address = address
+ checkout.save()
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {
@@ -170,7 +173,10 @@ def test_checkout_add_payment_bad_amount(user_api_client, checkout_with_item):
response = user_api_client.post_graphql(CREATE_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["checkoutPaymentCreate"]
- assert data["errors"]
+ assert (
+ data["paymentErrors"][0]["code"]
+ == PaymentErrorCode.PARTIAL_PAYMENT_NOT_ALLOWED.name
+ )
def test_use_checkout_billing_address_as_payment_billing(
@@ -192,10 +198,10 @@ def test_use_checkout_billing_address_as_payment_billing(
data = content["data"]["checkoutPaymentCreate"]
# check if proper error is returned if address is missing
- assert data["errors"][0]["field"] == "billingAddress"
+ assert data["paymentErrors"][0]["field"] == "billingAddress"
assert (
- data["errors"][0]["message"]
- == "No billing address associated with this checkout."
+ data["paymentErrors"][0]["code"]
+ == PaymentErrorCode.BILLING_ADDRESS_NOT_SET.name
)
# assign the address and try again
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 968353724f..5e3c8588e4 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -3,6 +3,7 @@ from unittest.mock import Mock, patch
import pytest
+from saleor.checkout.calculations import checkout_total
from saleor.payment import (
ChargeStatus,
GatewayError,
@@ -10,6 +11,7 @@ from saleor.payment import (
TransactionKind,
gateway,
)
+from saleor.payment.error_codes import PaymentErrorCode
from saleor.payment.interface import CreditCardInfo, GatewayConfig, GatewayResponse
from saleor.payment.models import Payment
from saleor.payment.utils import (
@@ -78,7 +80,7 @@ def transaction_token():
@pytest.fixture
-def dummy_response(payment_dummy, transaction_data, transaction_token, card_details):
+def dummy_response(payment_dummy, transaction_token, card_details):
return GatewayResponse(
is_success=True,
action_required=False,
@@ -92,15 +94,18 @@ def dummy_response(payment_dummy, transaction_data, transaction_token, card_deta
)
-def test_create_payment(address, settings):
+def test_create_payment(checkout_with_item, address):
+ checkout_with_item.billing_address = address
+ checkout_with_item.save()
+
data = {
"gateway": "Dummy",
"payment_token": "token",
- "total": 10,
- "currency": settings.DEFAULT_CURRENCY,
+ "total": checkout_total(checkout_with_item).gross.amount,
+ "currency": checkout_with_item.currency,
"email": "[email protected]",
- "billing_address": address,
"customer_ip_address": "127.0.0.1",
+ "checkout": checkout_with_item,
}
payment = create_payment(**data)
assert payment.gateway == "Dummy"
@@ -109,6 +114,106 @@ def test_create_payment(address, settings):
assert payment == same_payment
+def test_create_payment_requires_order_or_checkout(settings):
+ data = {
+ "gateway": "Dummy",
+ "payment_token": "token",
+ "total": 10,
+ "currency": settings.DEFAULT_CURRENCY,
+ "email": "[email protected]",
+ }
+ with pytest.raises(TypeError) as e:
+ create_payment(**data)
+ assert e.value.args[0] == "Must provide checkout or order to create a payment."
+
+
+def test_create_payment_from_checkout_requires_billing_address(
+ checkout_with_item, settings
+):
+ checkout_with_item.billing_address = None
+ checkout_with_item.save()
+
+ data = {
+ "gateway": "Dummy",
+ "payment_token": "token",
+ "total": checkout_total(checkout_with_item),
+ "currency": checkout_with_item.currency,
+ "email": "[email protected]",
+ "checkout": checkout_with_item,
+ }
+ with pytest.raises(PaymentError) as e:
+ create_payment(**data)
+ assert e.value.code == PaymentErrorCode.BILLING_ADDRESS_NOT_SET.value
+
+
+def test_create_payment_from_order_requires_billing_address(draft_order, settings):
+ draft_order.billing_address = None
+ draft_order.save()
+
+ data = {
+ "gateway": "Dummy",
+ "payment_token": "token",
+ "total": draft_order.total.gross.amount,
+ "currency": draft_order.currency,
+ "email": "[email protected]",
+ "order": draft_order,
+ }
+ with pytest.raises(PaymentError) as e:
+ create_payment(**data)
+ assert e.value.code == PaymentErrorCode.BILLING_ADDRESS_NOT_SET.value
+
+
+def test_create_payment_information_for_checkout_payment(address, checkout_with_item):
+ checkout_with_item.billing_address = address
+ checkout_with_item.shipping_address = address
+ checkout_with_item.save()
+ data = {
+ "gateway": "Dummy",
+ "payment_token": "token",
+ "total": checkout_total(checkout_with_item).gross.amount,
+ "currency": checkout_with_item.currency,
+ "email": "[email protected]",
+ "customer_ip_address": "127.0.0.1",
+ "checkout": checkout_with_item,
+ }
+
+ payment = create_payment(**data)
+ payment_data = create_payment_information(payment, "token", payment.total)
+
+ billing = payment_data.billing
+ shipping = payment_data.shipping
+ assert billing
+ assert billing.first_name == address.first_name
+ assert billing.last_name == address.last_name
+ assert billing.street_address_1 == address.street_address_1
+ assert billing.city == address.city
+ assert shipping == billing
+
+
+def test_create_payment_information_for_draft_order(draft_order):
+ data = {
+ "gateway": "Dummy",
+ "payment_token": "token",
+ "total": draft_order.total.gross.amount,
+ "currency": draft_order.currency,
+ "email": "[email protected]",
+ "customer_ip_address": "127.0.0.1",
+ "order": draft_order,
+ }
+
+ payment = create_payment(**data)
+ payment_data = create_payment_information(payment, "token", payment.total)
+
+ billing = payment_data.billing
+ shipping = payment_data.shipping
+ assert billing
+ assert billing.first_name == draft_order.billing_address.first_name
+ assert billing.last_name == draft_order.billing_address.last_name
+ assert billing.street_address_1 == draft_order.billing_address.street_address_1
+ assert billing.city == draft_order.billing_address.city
+ assert shipping == billing
+
+
def test_create_transaction(transaction_data):
txn = create_transaction(**transaction_data)