Skip to content

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

Add payment details to order webhook payload

Maciej Korycinski9c7a1c53c444
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index 1349a49131..b3e6252fdd 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -10,7 +10,7 @@ from ....payment.gateways.dummy_credit_card import (
TOKEN_EXPIRED,
TOKEN_VALIDATION_MAPPING,
)
-from ....payment.interface import CreditCardInfo, CustomerSource, TokenConfig
+from ....payment.interface import CustomerSource, PaymentMethodInfo, TokenConfig
from ....payment.models import ChargeStatus, Payment, TransactionKind
from ....payment.utils import fetch_customer_id, store_customer_id
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -774,9 +774,7 @@ def test_list_payment_sources(
}
}
"""
- card = CreditCardInfo(
- last_4="5678", exp_year=2020, exp_month=12, name_on_card="JohnDoe"
- )
+ card = PaymentMethodInfo(last_4="5678", exp_year=2020, exp_month=12, name="JohnDoe")
source = CustomerSource(id="test1", gateway=gateway, credit_card_info=card)
mock_get_source_list = mocker.patch(
"saleor.graphql.account.resolvers.gateway.list_payment_sources",
@@ -795,9 +793,7 @@ def test_stored_payment_sources_restriction(
mocker, staff_api_client, customer_user, permission_manage_users
):
# Only owner of storedPaymentSources can fetch it.
- card = CreditCardInfo(
- last_4="5678", exp_year=2020, exp_month=12, name_on_card="JohnDoe"
- )
+ card = PaymentMethodInfo(last_4="5678", exp_year=2020, exp_month=12, name="JohnDoe")
source = CustomerSource(id="test1", gateway="dummy", credit_card_info=card)
mocker.patch(
"saleor.graphql.account.resolvers.gateway.list_payment_sources",
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 06e4b6708a..0d2fd2bb6b 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -12,7 +12,7 @@ from .utils import (
create_payment_information,
create_transaction,
gateway_postprocess,
- update_card_details,
+ update_payment_method_details,
validate_gateway_response,
)
@@ -68,6 +68,8 @@ def process_payment(
plugin_manager.process_payment, payment.gateway, payment_data
)
action_required = response is not None and response.action_required
+ if response and response.payment_method_info:
+ update_payment_method_details(payment, response)
return create_transaction(
payment=payment,
kind=TransactionKind.CAPTURE,
@@ -90,6 +92,8 @@ def authorize(payment: Payment, token: str, store_source: bool = False) -> Trans
response, error = _fetch_gateway_response(
plugin_manager.authorize_payment, payment.gateway, payment_data
)
+ if response and response.payment_method_info:
+ update_payment_method_details(payment, response)
return create_transaction(
payment=payment,
kind=TransactionKind.AUTH,
@@ -116,8 +120,8 @@ def capture(
response, error = _fetch_gateway_response(
plugin_manager.capture_payment, payment.gateway, payment_data
)
- if response.card_info:
- update_card_details(payment, response)
+ if response and response.payment_method_info:
+ update_payment_method_details(payment, response)
return create_transaction(
payment=payment,
kind=TransactionKind.CAPTURE,
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 12ccb9ec0f..f0cd61eefb 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -5,11 +5,11 @@ from django.core.exceptions import ImproperlyConfigured
from ... import TransactionKind
from ...interface import (
- CreditCardInfo,
CustomerSource,
GatewayConfig,
GatewayResponse,
PaymentData,
+ PaymentMethodInfo,
TokenConfig,
)
from .errors import DEFAULT_ERROR_MESSAGE, BraintreeException
@@ -135,6 +135,7 @@ def authorize(
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response["errors"])
kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
+ credit_card = gateway_response.get("credit_card", {})
return GatewayResponse(
is_success=result.is_success,
action_required=False,
@@ -146,6 +147,14 @@ def authorize(
"transaction_id", payment_information.token
),
error=error,
+ payment_method_info=PaymentMethodInfo(
+ last_4=credit_card.get("last_4"),
+ exp_year=credit_card.get("expiration_year"),
+ exp_month=credit_card.get("expiration_month"),
+ brand=credit_card.get("card_type", "").lower(),
+ name=credit_card.get("cardholder_name"),
+ type="card",
+ ),
raw_response=gateway_response,
)
@@ -283,11 +292,11 @@ def list_client_sources(
def extract_credit_card_data(card, gateway_name):
- credit_card = CreditCardInfo(
+ credit_card = PaymentMethodInfo(
exp_year=int(card.expiration_year),
exp_month=int(card.expiration_month),
last_4=card.last_4,
- name_on_card=card.cardholder_name,
+ name=card.cardholder_name,
)
return CustomerSource(
id=card.unique_number_identifier,
diff --git a/saleor/payment/gateways/braintree/tests/test_braintree.py b/saleor/payment/gateways/braintree/tests/test_braintree.py
index 8f5b67d45b..e061733316 100644
--- a/saleor/payment/gateways/braintree/tests/test_braintree.py
+++ b/saleor/payment/gateways/braintree/tests/test_braintree.py
@@ -7,7 +7,7 @@ from braintree.errors import Errors
from braintree.validation_error import ValidationError
from django.core.exceptions import ImproperlyConfigured
-from ....interface import CreditCardInfo, CustomerSource, GatewayConfig, TokenConfig
+from ....interface import CustomerSource, GatewayConfig, PaymentMethodInfo, TokenConfig
from ....utils import create_payment_information
from .. import (
TransactionKind,
@@ -274,6 +274,11 @@ def test_authorize_one_time(
assert response.amount == braintree_success_response.transaction.amount
assert response.currency == braintree_success_response.transaction.currency_iso_code
assert response.is_success is True
+ assert response.payment_method_info.last_4 == "1881"
+ assert response.payment_method_info.brand == "visa"
+ assert response.payment_method_info.type == "card"
+ assert response.payment_method_info.exp_month == "12"
+ assert response.payment_method_info.exp_year == "2020"
@pytest.mark.integration
@@ -396,8 +401,8 @@ def test_void_incorrect_token(payment_txn_preauth, sandbox_braintree_gateway_con
@pytest.mark.vcr(filter_headers=["authorization"])
def test_list_customer_sources(sandbox_braintree_gateway_config):
CUSTOMER_ID = "595109854" # retrieved from sandbox
- expected_credit_card = CreditCardInfo(
- last_4="1881", exp_year=2020, exp_month=12, name_on_card=None
+ expected_credit_card = PaymentMethodInfo(
+ last_4="1881", exp_year=2020, exp_month=12, name=None
)
expected_customer_source = CustomerSource(
id="d0b52c80b648ae8e5a14eddcaf24d254",
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index ee4eae71c5..0e59048d4c 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -1,7 +1,7 @@
import uuid
from ... import ChargeStatus, TransactionKind
-from ...interface import GatewayConfig, GatewayResponse, PaymentData
+from ...interface import GatewayConfig, GatewayResponse, PaymentData, PaymentMethodInfo
def dummy_success():
@@ -27,6 +27,14 @@ def authorize(
currency=payment_information.currency,
transaction_id=payment_information.token,
error=error,
+ payment_method_info=PaymentMethodInfo(
+ last_4="1234",
+ exp_year=2222,
+ exp_month=12,
+ brand="dummy_visa",
+ name="Holder name",
+ type="card",
+ ),
)
diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.py
index 2ae597404a..76253932ab 100644
--- a/saleor/payment/gateways/stripe/__init__.py
+++ b/saleor/payment/gateways/stripe/__init__.py
@@ -4,11 +4,11 @@ import stripe
from ... import TransactionKind
from ...interface import (
- CreditCardInfo,
CustomerSource,
GatewayConfig,
GatewayResponse,
PaymentData,
+ PaymentMethodInfo,
)
from .utils import (
get_amount_for_stripe,
@@ -163,11 +163,11 @@ def list_client_sources(
CustomerSource(
id=c.id,
gateway="stripe",
- credit_card_info=CreditCardInfo(
+ credit_card_info=PaymentMethodInfo(
exp_year=c.card.exp_year,
exp_month=c.card.exp_month,
last_4=c.card.last4,
- name_on_card=None,
+ name=None,
),
)
for c in cards
@@ -231,10 +231,13 @@ def fill_card_details(intent: stripe.PaymentIntent, response: GatewayResponse):
charges = intent.charges["data"]
if charges:
card = intent.charges["data"][-1]["payment_method_details"]["card"]
- response.card_info = CreditCardInfo(
+ brand = card["brand"] or ""
+
+ response.payment_method_info = PaymentMethodInfo(
last_4=card["last4"],
exp_year=card["exp_year"],
exp_month=card["exp_month"],
- brand=card["brand"],
+ brand=brand.lower(),
+ type="card",
)
return response
diff --git a/saleor/payment/gateways/stripe/tests/test_stripe.py b/saleor/payment/gateways/stripe/tests/test_stripe.py
index 38c37b487d..9f937c310d 100644
--- a/saleor/payment/gateways/stripe/tests/test_stripe.py
+++ b/saleor/payment/gateways/stripe/tests/test_stripe.py
@@ -5,7 +5,7 @@ from math import isclose
import pytest
from .... import ChargeStatus
-from ....interface import CreditCardInfo, CustomerSource, GatewayConfig
+from ....interface import CustomerSource, GatewayConfig, PaymentMethodInfo
from ....utils import create_payment_information
from .. import (
TransactionKind,
@@ -23,8 +23,8 @@ TRANSACTION_AMOUNT = Decimal(42.42)
TRANSACTION_REFUND_AMOUNT = Decimal(24.24)
TRANSACTION_CURRENCY = "USD"
PAYMENT_METHOD_CARD_SIMPLE = "pm_card_pl"
-CARD_SIMPLE_DETAILS = CreditCardInfo(
- last_4="0005", exp_year=2020, exp_month=8, brand="visa"
+CARD_SIMPLE_DETAILS = PaymentMethodInfo(
+ last_4="0005", exp_year=2020, exp_month=8, brand="visa", type="card"
)
PAYMENT_METHOD_CARD_3D_SECURE = "pm_card_threeDSecure2Required"
@@ -82,7 +82,7 @@ def test_authorize(sandbox_gateway_config, stripe_payment):
assert isclose(response.amount, TRANSACTION_AMOUNT)
assert response.currency == TRANSACTION_CURRENCY
assert response.is_success is True
- assert response.card_info == CARD_SIMPLE_DETAILS
+ assert response.payment_method_info == CARD_SIMPLE_DETAILS
assert not response.action_required
@@ -186,7 +186,7 @@ def test_capture(stripe_authorized_payment, sandbox_gateway_config):
assert response.is_success
assert isclose(response.amount, TRANSACTION_AMOUNT)
assert response.currency == TRANSACTION_CURRENCY
- assert response.card_info == CARD_SIMPLE_DETAILS
+ assert response.payment_method_info == CARD_SIMPLE_DETAILS
@pytest.mark.integration
@@ -334,8 +334,8 @@ def test_confirm_error_response(stripe_payment, sandbox_gateway_config):
@pytest.mark.vcr(filter_headers=["authorization"])
def test_list_customer_sources(sandbox_gateway_config):
CUSTOMER_ID = "cus_FbquUfgBnLdlsY" # retrieved from sandbox
- expected_credit_card = CreditCardInfo(
- last_4="0005", exp_year=2020, exp_month=8, name_on_card=None
+ expected_credit_card = PaymentMethodInfo(
+ last_4="0005", exp_year=2020, exp_month=8, name=None
)
expected_customer_source = CustomerSource(
id="pm_1F6dCWIUmJaD6OqvCtcAnPSq",
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index bbb78c7fde..ad908b9578 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -4,14 +4,15 @@ from typing import Any, Dict, List, Optional
@dataclass
-class CreditCardInfo:
- """Uniform way to represent Credit Card information."""
+class PaymentMethodInfo:
+ """Uniform way to represent payment method information."""
- last_4: str
- exp_year: int
- exp_month: int
+ last_4: Optional[str] = None
+ exp_year: Optional[int] = None
+ exp_month: Optional[int] = None
brand: Optional[str] = None
- name_on_card: Optional[str] = None
+ name: Optional[str] = None
+ type: Optional[str] = None
@dataclass
@@ -30,7 +31,7 @@ class GatewayResponse:
transaction_id: Optional[str]
error: Optional[str]
customer_id: Optional[str] = None
- card_info: Optional[CreditCardInfo] = None
+ payment_method_info: Optional[PaymentMethodInfo] = None
raw_response: Optional[Dict[str, str]] = None
@@ -100,7 +101,7 @@ class CustomerSource:
id: str
gateway: str
- credit_card_info: Optional[CreditCardInfo] = None
+ credit_card_info: Optional[PaymentMethodInfo] = None
@dataclass
diff --git a/saleor/payment/migrations/0017_payment_payment_method_type.py b/saleor/payment/migrations/0017_payment_payment_method_type.py
new file mode 100644
index 0000000000..ada9260d82
--- /dev/null
+++ b/saleor/payment/migrations/0017_payment_payment_method_type.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.0.6 on 2020-08-06 09:13
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0016_auto_20200423_0314"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="payment",
+ name="payment_method_type",
+ field=models.CharField(blank=True, max_length=256),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index d28df4bead..200ea6400a 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -81,6 +81,8 @@ class Payment(models.Model):
validators=[MinValueValidator(1000)], null=True, blank=True
)
+ payment_method_type = models.CharField(max_length=256, blank=True)
+
customer_ip_address = models.GenericIPAddressField(blank=True, null=True)
extra_data = models.TextField(blank=True, default="")
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index 1961e44c67..772d1f909f 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -6,7 +6,7 @@ import pytest
from ...checkout.calculations import checkout_total
from .. import ChargeStatus, GatewayError, PaymentError, TransactionKind, gateway
from ..error_codes import PaymentErrorCode
-from ..interface import CreditCardInfo, GatewayResponse
+from ..interface import GatewayResponse, PaymentMethodInfo
from ..models import Payment
from ..utils import (
ALLOWED_GATEWAY_KINDS,
@@ -24,14 +24,14 @@ EXAMPLE_ERROR = "Example dummy error"
@pytest.fixture
-def card_details():
- return CreditCardInfo(
- last_4="1234", exp_year=2020, exp_month=8, brand="visa", name_on_card="Joe Doe"
+def payment_method_details():
+ return PaymentMethodInfo(
+ last_4="1234", exp_year=2020, exp_month=8, brand="visa", name="Joe Doe"
)
@pytest.fixture
-def gateway_response(settings, card_details):
+def gateway_response(settings, payment_method_details):
return GatewayResponse(
is_success=True,
action_required=False,
@@ -44,7 +44,7 @@ def gateway_response(settings, card_details):
"credit_card_four": "1234",
"transaction-id": "transaction-token",
},
- card_info=card_details,
+ payment_method_info=payment_method_details,
)
@@ -66,7 +66,7 @@ def transaction_token():
@pytest.fixture
-def dummy_response(payment_dummy, transaction_token, card_details):
+def dummy_response(payment_dummy, transaction_token, payment_method_details):
return GatewayResponse(
is_success=True,
action_required=False,
@@ -76,7 +76,7 @@ def dummy_response(payment_dummy, transaction_token, card_details):
currency=payment_dummy.currency,
kind=TransactionKind.AUTH,
raw_response=None,
- card_info=card_details,
+ payment_method_info=payment_method_details,
)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 9bda393a87..bca00b917a 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -254,20 +254,29 @@ def prepare_key_for_gateway_customer_id(gateway_name: str) -> str:
return (gateway_name.strip().upper()) + ".customer_id"
-def update_card_details(payment, gateway_response):
- payment.cc_brand = gateway_response.card_info.brand or ""
- payment.cc_last_digits = gateway_response.card_info.last_4
- payment.cc_exp_year = gateway_response.card_info.exp_year
- payment.cc_exp_month = gateway_response.card_info.exp_month
- payment.save(
- update_fields=[
- "cc_brand",
- "cc_last_digits",
- "cc_exp_year",
- "cc_exp_month",
- "modified",
- ]
- )
+def update_payment_method_details(
+ payment: "Payment", gateway_response: "GatewayResponse"
+):
+ changed_fields = []
+ if not gateway_response.payment_method_info:
+ return
+ if gateway_response.payment_method_info.brand:
+ payment.cc_brand = gateway_response.payment_method_info.brand
+ changed_fields.append("cc_brand")
+ if gateway_response.payment_method_info.last_4:
+ payment.cc_last_digits = gateway_response.payment_method_info.last_4
+ changed_fields.append("cc_last_digits")
+ if gateway_response.payment_method_info.exp_year:
+ payment.cc_exp_year = gateway_response.payment_method_info.exp_year
+ changed_fields.append("cc_exp_year")
+ if gateway_response.payment_method_info.exp_month:
+ payment.cc_exp_month = gateway_response.payment_method_info.exp_month
+ changed_fields.append("cc_exp_month")
+ if gateway_response.payment_method_info.type:
+ payment.payment_method_type = gateway_response.payment_method_info.type
+ changed_fields.append("payment_method_type")
+ if changed_fields:
+ payment.save(update_fields=changed_fields)
def get_payment_token(payment: Payment):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index d12d9d36c7..ddf96f9dab 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1918,7 +1918,7 @@ def payment_dummy(db, order_with_lines):
is_active=True,
cc_first_digits="4111",
cc_last_digits="1111",
- cc_brand="VISA",
+ cc_brand="visa",
cc_exp_month=12,
cc_exp_year=2027,
total=order_with_lines.total.gross.amount,
@@ -1944,7 +1944,7 @@ def payment_dummy_credit_card(db, order_with_lines):
is_active=True,
cc_first_digits="4111",
cc_last_digits="1111",
- cc_brand="VISA",
+ cc_brand="visa",
cc_exp_month=12,
cc_exp_year=2027,
total=order_with_lines.total.gross.amount,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 755170d3a6..3d74759538 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -60,6 +60,8 @@ def generate_order_payload(order: "Order"):
fulfillment_fields = ("status", "tracking_number", "created")
payment_fields = (
"gateway",
+ "payment_method_type",
+ "cc_brand",
"is_active",
"created",
"modified",