Skip to content

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

Add PaymentInformation structure

Maciej Korycinski43c9bab7b457
diff --git a/saleor/payment/gateway_dataclasses.py b/saleor/payment/gateway_dataclasses.py
index 35f455fa9c..7841def8ba 100644
--- a/saleor/payment/gateway_dataclasses.py
+++ b/saleor/payment/gateway_dataclasses.py
@@ -14,3 +14,16 @@ class GatewayResponse:
transaction_id: str
error: Optional[str]
raw_response: Optional[Dict[str, str]] = None
+
+@dataclass
+class PaymentInformation:
+ """Dataclass for storing all payment information"""
+
+ token: str
+ amount: Decimal
+ currency: str
+ billing: Optional[Dict[str, str]]
+ shipping: Optional[Dict[str, str]]
+ order_id: int
+ customer_ip_address: str
+ customer_email: str
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index e88d559adc..ce12e2eaa7 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -5,7 +5,7 @@ import braintree as braintree_sdk
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
-from ...gateway_dataclasses import GatewayResponse
+from ...gateway_dataclasses import GatewayResponse, PaymentInformation
from .errors import DEFAULT_ERROR_MESSAGE, BraintreeException
from .forms import BraintreePaymentForm
@@ -39,10 +39,10 @@ class TransactionKind:
VOID = 'void'
-def get_customer_data(payment_information: Dict) -> Dict:
- billing = payment_information['billing']
+def get_customer_data(payment_information: PaymentInformation) -> Dict:
+ billing = payment_information.billing
return {
- 'order_id': payment_information['order_id'],
+ 'order_id': payment_information.order_id,
'billing': {
'first_name': billing['first_name'],
'last_name': billing['last_name'],
@@ -54,8 +54,8 @@ def get_customer_data(payment_information: Dict) -> Dict:
'region': billing['country_area'],
'country_code_alpha2': billing['country']},
'risk_data': {
- 'customer_ip': payment_information['customer_ip_address'] or ''},
- 'customer': {'email': payment_information['customer_email']}}
+ 'customer_ip': payment_information.customer_ip_address or ''},
+ 'customer': {'email': payment_information.customer_email}}
def get_error_for_client(errors: List) -> str:
@@ -121,13 +121,14 @@ def get_client_token(connection_params: Dict) -> str:
def authorize(
- payment_information: Dict, connection_params: Dict) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
result = gateway.transaction.sale({
- 'amount': str(payment_information['amount']),
- 'payment_method_nonce': payment_information['token'],
+ 'amount': str(payment_information.amount),
+ 'payment_method_nonce': payment_information.token,
'options': {
'submit_for_settlement': CONFIRM_MANUALLY,
'three_d_secure': {
@@ -142,24 +143,25 @@ def authorize(
is_success=result.is_success,
kind=TransactionKind.AUTH,
amount=gateway_response.get(
- 'amount', payment_information['amount']),
+ 'amount', payment_information.amount),
currency=gateway_response.get(
- 'currency', payment_information['currency']),
+ 'currency', payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information['token']),
+ 'transaction_id', payment_information.token),
error=error,
raw_response=gateway_response
)
def capture(
- payment_information: Dict, connection_params: Dict) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
result = gateway.transaction.submit_for_settlement(
- transaction_id=payment_information['token'],
- amount=str(payment_information['amount']))
+ transaction_id=payment_information.token,
+ amount=str(payment_information.amount))
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
@@ -170,23 +172,24 @@ def capture(
is_success=result.is_success,
kind=TransactionKind.CAPTURE,
amount=gateway_response.get(
- 'amount', payment_information['amount']),
+ 'amount', payment_information.amount),
currency=gateway_response.get(
- 'currency', payment_information['currency']),
+ 'currency', payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information['token']),
+ 'transaction_id', payment_information.token),
error=error,
raw_response=gateway_response
)
def void(
- payment_information: Dict, connection_params: Dict) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
result = gateway.transaction.void(
- transaction_id=payment_information['token'])
+ transaction_id=payment_information.token)
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
@@ -197,11 +200,11 @@ def void(
is_success=result.is_success,
kind=TransactionKind.VOID,
amount=gateway_response.get(
- 'amount', payment_information['amount']),
+ 'amount', payment_information.amount),
currency=gateway_response.get(
- 'currency', payment_information['currency']),
+ 'currency', payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information['token']),
+ 'transaction_id', payment_information.token),
error=error,
raw_response=gateway_response
)
@@ -213,8 +216,8 @@ def refund(
try:
result = gateway.transaction.refund(
- transaction_id=payment_information['token'],
- amount_or_options=str(payment_information['amount']))
+ transaction_id=payment_information.token,
+ amount_or_options=str(payment_information.amount))
except braintree_sdk.exceptions.NotFoundError:
raise BraintreeException(DEFAULT_ERROR_MESSAGE)
@@ -225,11 +228,11 @@ def refund(
is_success=result.is_success,
kind=TransactionKind.REFUND,
amount=gateway_response.get(
- 'amount', payment_information['amount']),
+ 'amount', payment_information.amount),
currency=gateway_response.get(
- 'currency', payment_information['currency']),
+ 'currency', payment_information.currency),
transaction_id=gateway_response.get(
- 'transaction_id', payment_information['token']),
+ 'transaction_id', payment_information.token),
error=error,
raw_response=gateway_response
@@ -237,9 +240,10 @@ def refund(
def process_payment(
- payment_information: Dict, connection_params: Dict) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
auth_resp = authorize(payment_information, connection_params)
if auth_resp.is_success:
- payment_information['token'] = auth_resp.transaction_id
+ payment_information.token = auth_resp.transaction_id
return capture(payment_information, connection_params)
return auth_resp
diff --git a/saleor/payment/gateways/braintree/forms.py b/saleor/payment/gateways/braintree/forms.py
index a67c64f104..99b8aa9983 100644
--- a/saleor/payment/gateways/braintree/forms.py
+++ b/saleor/payment/gateways/braintree/forms.py
@@ -2,6 +2,8 @@ from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import pgettext_lazy
+from ...gateway_dataclasses import PaymentInformation
+
class BraintreePaymentForm(forms.Form):
amount = forms.DecimalField()
@@ -13,10 +15,10 @@ class BraintreePaymentForm(forms.Form):
# response
payment_method_nonce = forms.CharField()
- def __init__(self, payment_information, *args, **kwargs):
+ def __init__(self, payment_information: PaymentInformation, *args, **kwargs):
super().__init__(*args, **kwargs)
self.payment_information = payment_information
- self.fields['amount'].initial = payment_information['amount']
+ self.fields['amount'].initial = payment_information.amount
def clean(self):
cleaned_data = super().clean()
@@ -25,7 +27,7 @@ class BraintreePaymentForm(forms.Form):
# when manually adjusting the template value as we do not allow
# partial-payments at this moment, error is returned instead.
amount = cleaned_data.get('amount')
- if amount and amount != self.payment_information['amount']:
+ if amount and amount != self.payment_information.amount:
msg = pgettext_lazy(
'payment error',
'Unable to process transaction. Please try again in a moment')
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index e8bdd187c9..b85f4ec3a3 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -37,9 +37,9 @@ def authorize(
return GatewayResponse(
is_success=success,
kind=TransactionKind.AUTH,
- amount=payment_information['amount'],
- currency=payment_information['currency'],
- transaction_id=payment_information['token'],
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=payment_information.token,
error=error
)
@@ -53,9 +53,9 @@ def void(
return GatewayResponse(
is_success=success,
kind=TransactionKind.VOID,
- amount=payment_information['amount'],
- currency=payment_information['currency'],
- transaction_id=payment_information['token'],
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=payment_information.token,
error=error
)
@@ -71,9 +71,9 @@ def capture(
return GatewayResponse(
is_success=success,
kind=TransactionKind.CAPTURE,
- amount=payment_information['amount'],
- currency=payment_information['currency'],
- transaction_id=payment_information['token'],
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=payment_information.token,
error=error
)
@@ -87,9 +87,9 @@ def refund(
return GatewayResponse(
is_success=success,
kind=TransactionKind.REFUND,
- amount=payment_information['amount'],
- currency=payment_information['currency'],
- transaction_id=payment_information['token'],
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=payment_information.token,
error=error
)
@@ -106,7 +106,7 @@ def charge(
def process_payment(
payment_information: Dict, connection_params) -> GatewayResponse:
"""Process the payment."""
- token = payment_information.get('token')
+ token = payment_information.token
# Process payment normally if payment token is valid
if token not in dict(ChargeStatus.CHOICES):
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index 098713e188..8d72d00c5a 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -1,12 +1,12 @@
import logging
import uuid
from decimal import Decimal
-from typing import Dict, List
+from typing import Dict
import razorpay
import razorpay.errors
-from ...gateway_dataclasses import GatewayResponse
+from ...gateway_dataclasses import GatewayResponse, PaymentInformation
from . import errors
from .forms import RazorPaymentForm
from .utils import get_amount_for_razorpay, get_error_response
@@ -37,25 +37,26 @@ class TransactionKind:
def _generate_response(
- payment_information: Dict, kind: str, data: Dict) -> GatewayResponse:
+ payment_information: PaymentInformation, kind: str, data: Dict
+) -> GatewayResponse:
"""Generate Saleor transaction information from
Razorpay's success payload or from passed data."""
return GatewayResponse(
- transaction_id=data.get('id', payment_information['token']),
+ transaction_id=data.get('id', payment_information.token),
kind=kind,
- amount=data.get('amount', payment_information['amount']),
- currency=data.get('currency', payment_information['currency']),
+ amount=data.get('amount', payment_information.amount),
+ currency=data.get('currency', payment_information.currency),
error=data.get('error'),
is_success=data.get('is_success', True),
raw_response=data
)
-def check_payment_supported(payment_information: Dict):
+def check_payment_supported(payment_information: PaymentInformation):
"""Checks that a given payment is supported."""
- if payment_information['currency'] not in SUPPORTED_CURRENCIES:
+ if payment_information.currency not in SUPPORTED_CURRENCIES:
return errors.UNSUPPORTED_CURRENCY % {
- 'currency': payment_information['currency']}
+ 'currency': payment_information.currency}
def get_error_message_from_razorpay_error(exc: BaseException):
@@ -68,7 +69,7 @@ def get_error_message_from_razorpay_error(exc: BaseException):
return errors.SERVER_ERROR
-def clean_razorpay_response(response: dict):
+def clean_razorpay_response(response: Dict):
"""As the Razorpay response payload contains the final amount
in Indian rupees, we convert the amount to paisa (by dividing by 100)."""
response['amount'] = Decimal(response['amount']) / 100
@@ -94,7 +95,8 @@ def get_client_token(**_):
def charge(
- payment_information: Dict, connection_params: Dict) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
"""Charge a authorized payment using the razorpay client.
But it first check if the given payment instance is supported
@@ -106,22 +108,22 @@ def charge(
after logging the error to stderr."""
error = check_payment_supported(payment_information=payment_information)
razorpay_client = get_client(**connection_params)
- razorpay_amount = get_amount_for_razorpay(payment_information['amount'])
+ razorpay_amount = get_amount_for_razorpay(payment_information.amount)
if not error:
try:
response = razorpay_client.payment.capture(
- payment_information['token'], razorpay_amount)
+ payment_information.token, razorpay_amount)
clean_razorpay_response(response)
except RAZORPAY_EXCEPTIONS as exc:
error = get_error_message_from_razorpay_error(exc)
response = get_error_response(
- payment_information['amount'], error=error,
- id=payment_information['token'])
+ payment_information.amount, error=error,
+ id=payment_information.token)
else:
response = get_error_response(
- payment_information['amount'], error=error,
- id=payment_information['token'])
+ payment_information.amount, error=error,
+ id=payment_information.token)
return _generate_response(
payment_information=payment_information,
@@ -129,7 +131,8 @@ def charge(
def refund(
- payment_information: Dict, connection_params) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params
+) -> GatewayResponse:
"""Refund a payment using the razorpay client.
But it first check if the given payment instance is supported
@@ -143,19 +146,19 @@ def refund(
if error:
response = get_error_response(
- payment_information['amount'], error=error)
+ payment_information.amount, error=error)
else:
razorpay_client = get_client(**connection_params)
razorpay_amount = get_amount_for_razorpay(
- payment_information['amount'])
+ payment_information.amount)
try:
response = razorpay_client.payment.refund(
- payment_information['token'], razorpay_amount)
+ payment_information.token, razorpay_amount)
clean_razorpay_response(response)
except RAZORPAY_EXCEPTIONS as exc:
error = get_error_message_from_razorpay_error(exc)
response = get_error_response(
- payment_information['amount'], error=error)
+ payment_information.amount, error=error)
return _generate_response(
payment_information=payment_information,
@@ -163,7 +166,8 @@ def refund(
def process_payment(
- payment_information: Dict, connection_params) -> GatewayResponse:
+ payment_information: PaymentInformation, connection_params
+) -> GatewayResponse:
return charge(
payment_information=payment_information,
connection_params=connection_params)
diff --git a/saleor/payment/gateways/razorpay/forms.py b/saleor/payment/gateways/razorpay/forms.py
index b6665f2612..8e19601b29 100644
--- a/saleor/payment/gateways/razorpay/forms.py
+++ b/saleor/payment/gateways/razorpay/forms.py
@@ -6,6 +6,7 @@ from django.forms.widgets import HiddenInput
from django.utils.html import format_html
from django.utils.translation import pgettext_lazy
+from ...gateway_dataclasses import PaymentInformation
from .utils import get_amount_for_razorpay
CHECKOUT_SCRIPT_URL = 'https://checkout.razorpay.com/v1/checkout.js'
@@ -20,7 +21,7 @@ class RazorPayCheckoutWidget(HiddenInput):
def __init__(
self, *,
- payment_information: Dict,
+ payment_information: PaymentInformation,
public_key: str,
prefill: bool,
store_name: str,
@@ -35,16 +36,16 @@ class RazorPayCheckoutWidget(HiddenInput):
'data-name': store_name,
'data-description': SECONDARY_TITLE,
'data-amount': get_amount_for_razorpay(
- payment_information['amount']),
- 'data-currency': payment_information['currency']}
+ payment_information.amount),
+ 'data-currency': payment_information.currency}
if prefill:
customer_name = '%s %s' % (
- payment_information['billing']['last_name'],
- payment_information['billing']['first_name'])
+ payment_information.billing['last_name'],
+ payment_information.billing['first_name'])
base_attrs.update({
'data-prefill.name': customer_name,
- 'data-prefill.email': payment_information['customer_email']})
+ 'data-prefill.email': payment_information.customer_email})
if override_attrs:
base_attrs.update(override_attrs)
diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.py
index 3394285958..2410fd0bfb 100644
--- a/saleor/payment/gateways/stripe/__init__.py
+++ b/saleor/payment/gateways/stripe/__init__.py
@@ -2,7 +2,7 @@ from typing import Dict
import stripe
-from ...gateway_dataclasses import GatewayResponse
+from ...gateway_dataclasses import GatewayResponse, PaymentInformation
from .forms import StripePaymentModalForm
from .utils import (
get_amount_for_stripe, get_amount_from_stripe, get_currency_for_stripe,
@@ -27,7 +27,9 @@ def get_client_token(**_):
return
-def authorize(payment_information, connection_params) -> GatewayResponse:
+def authorize(
+ payment_information: PaymentInformation, connection_params:Dict
+) -> GatewayResponse:
client, error = _get_client(**connection_params), None
try:
@@ -45,17 +47,19 @@ def authorize(payment_information, connection_params) -> GatewayResponse:
kind=TransactionKind.AUTH, response=response, error=error)
-def capture(payment_information, connection_params) -> GatewayResponse:
+def capture(
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
client, error = _get_client(**connection_params), None
# Get amount from argument or payment, and convert to stripe's amount
- amount = payment_information['amount']
+ amount = payment_information.amount
stripe_amount = get_amount_for_stripe(
- amount, payment_information['currency'])
+ amount, payment_information.currency)
try:
# Retrieve stripe charge and capture specific amount
- stripe_charge = client.Charge.retrieve(payment_information['token'])
+ stripe_charge = client.Charge.retrieve(payment_information.token)
response = stripe_charge.capture(amount=stripe_amount)
except stripe.error.StripeError as exc:
response = _get_error_response_from_exc(exc)
@@ -67,7 +71,9 @@ def capture(payment_information, connection_params) -> GatewayResponse:
kind=TransactionKind.CAPTURE, response=response, error=error)
-def charge(payment_information, connection_params) -> GatewayResponse:
+def charge(
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
client, error = _get_client(**connection_params), None
try:
@@ -85,17 +91,19 @@ def charge(payment_information, connection_params) -> GatewayResponse:
kind=TransactionKind.CHARGE, response=response, error=error)
-def refund(payment_information, connection_params) -> GatewayResponse:
+def refund(
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
client, error = _get_client(**connection_params), None
# Get amount from payment, and convert to stripe's amount
- amount = payment_information['amount']
+ amount = payment_information.amount
stripe_amount = get_amount_for_stripe(
- amount, payment_information['currency'])
+ amount, payment_information.currency)
try:
# Retrieve stripe charge and refund specific amount
- stripe_charge = client.Charge.retrieve(payment_information['token'])
+ stripe_charge = client.Charge.retrieve(payment_information.token)
response = client.Refund.create(
charge=stripe_charge.id, amount=stripe_amount)
except stripe.error.StripeError as exc:
@@ -108,12 +116,14 @@ def refund(payment_information, connection_params) -> GatewayResponse:
kind=TransactionKind.REFUND, response=response, error=error)
-def void(payment_information, connection_params) -> GatewayResponse:
+def void(
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
client, error = _get_client(**connection_params), None
try:
# Retrieve stripe charge and refund all
- stripe_charge = client.Charge.retrieve(payment_information['token'])
+ stripe_charge = client.Charge.retrieve(payment_information.token)
response = client.Refund.create(charge=stripe_charge.id)
except stripe.error.StripeError as exc:
response = _get_error_response_from_exc(exc)
@@ -125,11 +135,15 @@ def void(payment_information, connection_params) -> GatewayResponse:
kind=TransactionKind.VOID, response=response, error=error)
-def process_payment(payment_information, connection_params) -> GatewayResponse:
+def process_payment(
+ payment_information: PaymentInformation, connection_params: Dict
+) -> GatewayResponse:
return charge(payment_information, connection_params)
-def create_form(data, payment_information, connection_params):
+def create_form(
+ data: Dict, payment_information: PaymentInformation,
+ connection_params: Dict) -> StripePaymentModalForm:
return StripePaymentModalForm(
data=data, payment_information=payment_information,
gateway_params=connection_params)
@@ -141,15 +155,15 @@ def _get_client(**connection_params):
def _get_stripe_charge_payload(
- payment_information: Dict, should_capture: bool):
- shipping = payment_information['shipping']
+ payment_information: PaymentInformation, should_capture: bool) -> Dict:
+ shipping = payment_information.shipping
# Get currency
- currency = get_currency_for_stripe(payment_information['currency'])
+ currency = get_currency_for_stripe(payment_information.currency)
# Get appropriate amount for stripe
stripe_amount = get_amount_for_stripe(
- payment_information['amount'], currency)
+ payment_information.amount, currency)
# Get billing name from payment
name = get_payment_billing_fullname(payment_information)
@@ -159,7 +173,7 @@ def _get_stripe_charge_payload(
'capture': should_capture,
'amount': stripe_amount,
'currency': currency,
- 'source': payment_information['token'],
+ 'source': payment_information.token,
'description': name}
if shipping:
@@ -179,12 +193,13 @@ def _create_stripe_charge(client, payment_information, should_capture: bool):
def _create_response(
- payment_information, kind, response, error) -> GatewayResponse:
+ payment_information: PaymentInformation, kind: str, response: Dict,
+ error: str) -> GatewayResponse:
# Get currency from response or payment
currency = get_currency_from_stripe(
- response.get('currency', payment_information['currency']))
+ response.get('currency', payment_information.currency))
- amount = payment_information.get('amount')
+ amount = payment_information.amount
# Get amount from response or payment
if 'amount' in response:
stripe_amount = response.get('amount')
@@ -195,7 +210,7 @@ def _create_response(
amount = get_amount_from_stripe(stripe_amount, currency)
# Get token from response or use provided one
- token = response.get('id', payment_information['token'])
+ token = response.get('id', payment_information.token)
# Check if the response's status is flagged as succeeded
is_success = (response.get('status') == 'succeeded')
diff --git a/saleor/payment/gateways/stripe/forms.py b/saleor/payment/gateways/stripe/forms.py
index e600e1658a..99530777fe 100644
--- a/saleor/payment/gateways/stripe/forms.py
+++ b/saleor/payment/gateways/stripe/forms.py
@@ -1,9 +1,12 @@
+from typing import Dict
+
from django import forms
from django.forms.utils import flatatt
from django.forms.widgets import HiddenInput
from django.utils.html import format_html
from django.utils.translation import pgettext_lazy
+from ...gateway_dataclasses import PaymentInformation
from .utils import get_amount_for_stripe
CHECKOUT_SCRIPT_URL = 'https://checkout.stripe.com/checkout.js'
@@ -13,19 +16,21 @@ CHECKOUT_DESCRIPTION = pgettext_lazy(
class StripeCheckoutWidget(HiddenInput):
- def __init__(self, payment_information, gateway_params, *args, **kwargs):
+ def __init__(
+ self, payment_information: PaymentInformation,
+ gateway_params: Dict, *args, **kwargs):
attrs = kwargs.get('attrs', {})
kwargs['attrs'] = {
'class': 'stripe-button',
'src': CHECKOUT_SCRIPT_URL,
'data-key': gateway_params.get('public_key'),
'data-amount': get_amount_for_stripe(
- payment_information['amount'],
- payment_information['currency']),
+ payment_information.amount,
+ payment_information.currency),
'data-name': gateway_params.get('store_name'),
'data-image': gateway_params.get('store_image'),
'data-description': CHECKOUT_DESCRIPTION,
- 'data-currency': payment_information['currency'],
+ 'data-currency': payment_information.currency,
'data-locale': gateway_params.get('locale'),
'data-allow-remember-me': 'true' if gateway_params.get(
'remember_me') else 'false',
@@ -39,7 +44,7 @@ class StripeCheckoutWidget(HiddenInput):
if gateway_params.get('prefill'):
kwargs['attrs'].update({
- 'data-email': payment_information['customer_email']})
+ 'data-email': payment_information.customer_email})
kwargs['attrs'].update(attrs)
super(StripeCheckoutWidget, self).__init__(*args, **kwargs)
@@ -59,7 +64,9 @@ class StripePaymentModalForm(forms.Form):
"""
stripeToken = forms.CharField(required=True, widget=HiddenInput)
- def __init__(self, payment_information, gateway_params, *args, **kwargs):
+ def __init__(
+ self, payment_information: PaymentInformation,
+ gateway_params: Dict, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['stripe'] = forms.CharField(
diff --git a/saleor/payment/gateways/stripe/utils.py b/saleor/payment/gateways/stripe/utils.py
index fcf1faf751..90bd7d5e81 100644
--- a/saleor/payment/gateways/stripe/utils.py
+++ b/saleor/payment/gateways/stripe/utils.py
@@ -7,6 +7,8 @@ from django_countries import countries
# Since there is no public API in Stripe backend or helper function
# in Stripe's Python library, this list is straight out of Stripe's docs
# https://stripe.com/docs/currencies#zero-decimal
+from ...gateway_dataclasses import PaymentInformation
+
ZERO_DECIMAL_CURRENCIES = [
'BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA',
'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']
@@ -55,11 +57,12 @@ def get_currency_from_stripe(currency):
return currency.upper()
-def get_payment_billing_fullname(payment_information: Dict):
+def get_payment_billing_fullname(
+ payment_information: PaymentInformation) -> str:
# Get billing name from payment
return '%s %s' % (
- payment_information['billing']['last_name'],
- payment_information['billing']['first_name'])
+ payment_information.billing['last_name'],
+ payment_information.billing['first_name'])
def shipping_to_stripe_dict(shipping: Dict):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 253e1395d6..0285725d33 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -19,7 +19,7 @@ from ..order.models import Order
from . import (
ChargeStatus, CustomPaymentChoices, GatewayError, OperationType,
PaymentError, TransactionKind, get_payment_gateway)
-from .gateway_dataclasses import GatewayResponse
+from .gateway_dataclasses import GatewayResponse, PaymentInformation
from .models import Payment, Transaction
logger = logging.getLogger(__name__)
@@ -48,25 +48,30 @@ def get_gateway_operation_func(gateway, operation_type):
def create_payment_information(
payment: Payment, payment_token: str = None,
- amount: Decimal = None) -> Dict:
+ amount: Decimal = None) -> PaymentInformation:
"""Extracts order information along with payment details.
Returns information required to process payment and additional
billing/shipping addresses for optional fraud-prevention mechanisms.
"""
- return {
- 'token': payment_token,
- 'amount': amount or payment.total,
- 'currency': payment.currency,
- 'billing': (
- payment.order.billing_address.as_data()
- if payment.order.billing_address else None),
- 'shipping': (
- payment.order.shipping_address.as_data()
- if payment.order.shipping_address else None),
- 'order_id': payment.order.id,
- 'customer_ip_address': payment.customer_ip_address,
- 'customer_email': payment.billing_email}
+ billing, shipping = None, None
+
+ if payment.order.billing_address:
+ billing = payment.order.billing_address.as_data()
+
+ if payment.order.shipping_address:
+ shipping = payment.order.shipping_address.as_data()
+
+ return PaymentInformation(
+ token=payment_token,
+ amount=amount or payment.total,
+ currency=payment.currency,
+ billing=billing,
+ shipping=shipping,
+ order_id=payment.order.id,
+ customer_ip_address=payment.customer_ip_address,
+ customer_email=payment.billing_email
+ )
def handle_fully_paid_order(order):
@@ -184,10 +189,10 @@ def create_transaction(
if not gateway_response:
gateway_response = GatewayResponse(
kind=kind,
- transaction_id=payment_information['token'],
+ transaction_id=payment_information.token,
is_success=False,
- amount=payment_information['amount'],
- currency=payment_information['currency'],
+ amount=payment_information.amount,
+ currency=payment_information.currency,
error=error_msg,
)
gateway_response_dict = {}
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index 1ecbde6e43..e55cc132bb 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -2,8 +2,7 @@ from decimal import Decimal
from unittest.mock import Mock, patch
import pytest
-from braintree import (
- CreditCard, Environment, ErrorResult, SuccessfulResult, Transaction)
+from braintree import Environment, ErrorResult, SuccessfulResult, Transaction
from braintree.errors import Errors
from braintree.exceptions import NotFoundError
from braintree.validation_error import ValidationError
@@ -302,7 +301,7 @@ def test_refund(
assert response.transaction_id == braintree_success_response.transaction.id
assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(
- amount_or_options=str(amount), transaction_id=payment_info['token'])
+ amount_or_options=str(amount), transaction_id=payment_info.token)
@pytest.mark.integration
@@ -363,7 +362,7 @@ def test_capture(
assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(
- amount=str(amount), transaction_id=payment_info['token'])
+ amount=str(amount), transaction_id=payment_info.token)
@pytest.mark.integration
@@ -419,7 +418,7 @@ def test_void(
assert response.currency == braintree_success_response.transaction.currency_iso_code
assert response.transaction_id == braintree_success_response.transaction.id
assert response.is_success == braintree_success_response.is_success
- mock_response.assert_called_once_with(transaction_id=payment_info['token'])
+ mock_response.assert_called_once_with(transaction_id=payment_info.token)
@pytest.mark.integration
diff --git a/tests/gateway/test_stripe.py b/tests/gateway/test_stripe.py
index d634aa5812..b89babe2f8 100644
--- a/tests/gateway/test_stripe.py
+++ b/tests/gateway/test_stripe.py
@@ -289,7 +289,7 @@ def test_get_stripe_charge_payload_with_shipping(stripe_payment):
'description': billing_name,
'shipping': {
'name': billing_name,
- 'address': shipping_to_stripe_dict(payment_info['shipping'])}}
+ 'address': shipping_to_stripe_dict(payment_info.shipping)}}
charge_payload = _get_stripe_charge_payload(payment_info, True)