Skip to content

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

Clean up code. Add basic braintree provider

Artur Smęt665078cd9556
diff --git a/saleor/checkout/__init__.py b/saleor/checkout/__init__.py
index 1577315920..1bcfaa8ba6 100644
--- a/saleor/checkout/__init__.py
+++ b/saleor/checkout/__init__.py
@@ -15,27 +15,3 @@ class AddressType:
SHIPPING,
pgettext_lazy('Type of address used to fulfill order',
'Shipping'))]
-
-
-class TransactionType:
- AUTH = 'auth'
- CHARGE = 'charge'
- VOID = 'void'
- REFUND = 'refund'
-
- CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),
- (CHARGE, pgettext_lazy('transaction type', 'Charge')),
- (REFUND, pgettext_lazy('transaction type', 'Refund')),
- (VOID, pgettext_lazy('transaction type', 'Void'))]
-
-
-class PaymentMethodChargeStatus:
- CHARGED = 'charged'
- NOT_CHARGED = 'not-charged'
- FULLY_REFUNDED = 'fully-refunded'
-
- CHOICES = [
- (CHARGED, pgettext_lazy('payment method status', 'Charged')),
- (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')), (
- FULLY_REFUNDED,
- pgettext_lazy('payment method status', 'Fully refunded'))]
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 57f334cb9f..5c702c733a 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,24 +1,10 @@
import graphene
from ..core.mutations import BaseMutation
-from ..core.types.common import Decimal
+from ..core.types.common import Decimal, Error
from .types import PaymentGatewayEnum
+from ...payment import PaymentError
from ...payment.utils import create_payment_method, gateway_authorize
-
-class BraintreeBillingAddressInput(graphene.InputObjectType):
- company = graphene.String(description='Company name')
- country_code_alpha2 = graphene.String(description='2 letter ountry code')
- country_name = graphene.String(desccription='Country name')
- first_name = graphene.String(desccription='First name')
- last_name = graphene.String(desccription='Last name')
- locality = graphene.String(desccription='Locality/city')
- postal_code = graphene.String(desccription='Postal code')
- street_address = graphene.String(desccription='Street address')
-
-
-class BraintreeCustomerInput(graphene.InputObjectType):
- company = graphene.String(description='Company name')
- email = graphene.String(description='Email')
-
+from ..account.types import AddressInput
class CompleteCheckoutWithCreditCard(BaseMutation):
class Arguments:
@@ -29,14 +15,14 @@ class CompleteCheckoutWithCreditCard(BaseMutation):
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')
transaction_id = graphene.String()
- transaction_status = graphene.String()
- transaction_rejection_reason = graphene.String()
+ transaction_success = graphene.String()
class Meta:
description = 'Creates credit card transaction.'
@@ -44,23 +30,51 @@ class CompleteCheckoutWithCreditCard(BaseMutation):
def mutate(
self,
info,
- client_token,
+ gateway,
+ transaction_token,
amount,
store_payment_method,
- billing_address=None,
- customer=None):
-
+ billing_address=None):
+ # FIXME: This mutation should also fetch cart
+
+ 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}
# create payment method
payment_method = create_payment_method(
-
- )
+ variant=gateway,
+ billing_email='',
+ extra_data=extra_data,
+ total=amount,
+ **billing_data)
# authorize payment
- transaction = gateway_authorize(payment_method)
+ try:
+ transaction = gateway_authorize(payment_method, transaction_token)
+ except PaymentError as exc:
+ field = 'transaction_token'
+ msg = str(exc)
+ return CompleteCheckoutWithCreditCard(
+ errors=[Error(field=field, message=msg)])
return CompleteCheckoutWithCreditCard(
- transaction_id='',
- transaction_status='',
- transaction_rejection_reason='')
+ transaction_id=transaction.token,
+ transaction_success=transaction.is_success)
# class PaymentMethodCreate(BaseMutation):
diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.py
index 54a6a956a2..11928ee36e 100644
--- a/saleor/graphql/payment/resolvers.py
+++ b/saleor/graphql/payment/resolvers.py
@@ -3,7 +3,6 @@ from graphql_jwt.decorators import login_required
from ...order import models
from ..utils import filter_by_query_param, get_node
from .types import Payment
-from ...payments import braintree
PAYMENT_SEARCH_FIELDS = ['id']
@@ -23,4 +22,5 @@ def resolve_payment(info, id):
def resolve_payment_client_token(customer_id=None):
+ return
return braintree.create_client_token(customer_id=customer_id)
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 3b0f716f47..94483307cd 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -1,6 +1,7 @@
import importlib
from enum import Enum
from django.core.exceptions import ImproperlyConfigured
+from django.conf import settings
from django.utils.translation import pgettext_lazy
@@ -32,31 +33,15 @@ class PaymentMethodChargeStatus:
pgettext_lazy('payment method status', 'Fully refunded'))]
-# FIXME: move to settings
-PROVIDERS_MAP = {
- 'dummy': {
- 'module': 'saleor.payment.providers.dummy',
- 'params': {}},
-
- 'braintree': {
- 'module': 'saleor.payment.providers.braintree',
- 'params': {
- 'sandbox_mode': True,
- 'merchant_id': '',
- 'public_key': '',
- 'private_key': ''
- }
- }
-
-}
-
PROVIDERS_ENUM = Enum(
- 'ProvidersEnum', {key.upper(): key.lower() for key in PROVIDERS_MAP})
+ 'ProvidersEnum',
+ {key.upper(): key.lower() for key in settings.PAYMENT_PROVIDERS})
def get_provider(provider_name):
- if provider_name not in PROVIDERS_MAP:
+ if provider_name not in settings.PAYMENT_PROVIDERS:
raise ImproperlyConfigured(
f'Payment provider {provider_name} is not configured.')
- provider_module = importlib.import_module(PROVIDERS_MAP[provider_name]['module'])
- provider_params = PROVIDERS_MAP[provider_name]['params']
+ provider_module = importlib.import_module(
+ settings.PAYMENT_PROVIDERS[provider_name]['module'])
+ provider_params = settings.PAYMENT_PROVIDERS[provider_name]['connection_params']
return provider_module, provider_params
diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.py
new file mode 100644
index 0000000000..a44fa40f21
--- /dev/null
+++ b/saleor/payment/providers/braintree/__init__.py
@@ -0,0 +1,119 @@
+from typing import Dict
+import uuid
+from django.db import transaction
+import braintree
+
+from ... import TransactionType, PaymentMethodChargeStatus
+from ...models import Transaction
+
+#FIXME: Move to SiteSettings
+
+AUTO_CHARGE = False
+THREE_D_SECURE_REQUIRED = False
+
+def extract_gateway_response(braintree_result) -> Dict:
+ """
+ Extract data from Braintree response that will be stored locally
+ """
+ errors = {}
+ if not braintree_result.is_success:
+ errors = [
+ {'code': error.code, 'message': error.message}
+ for error in braintree_result.errors.deep_errors
+ ]
+
+ transaction = braintree_result.transaction
+ gateway_response = {
+ 'credit_card': braintree_result.transaction.credit_card,
+ 'additional_processor_response': transaction.additional_processor_response,
+ 'gateway_rejection_reason': transaction.gateway_rejection_reason,
+ 'processor_response_code': transaction.processor_response_code,
+ 'processor_response_text': transaction.processor_response_text,
+ 'processor_settlement_response_code': transaction.processor_settlement_response_code,
+ 'processor_settlement_response_text': transaction.processor_settlement_response_text,
+ 'risk_data': transaction.risk_data,
+ 'status': transaction.status,
+ 'errors': errors}
+ return gateway_response
+
+def get_gateway(sandbox_mode, merchant_id, public_key, private_key):
+ environment = braintree.Environment.Sandbox
+ if not sandbox_mode:
+ environment = braintree.Environment.Production
+
+ gateway = braintree.BraintreeGateway(
+ braintree.Configuration(
+ environment=environment,
+ merchant_id=merchant_id,
+ public_key=public_key,
+ private_key=private_key
+ )
+ )
+ return gateway
+
+
+def authorize(payment_method, transaction_token, **client_kwargs):
+ gateway = get_gateway(**client_kwargs)
+ result = gateway.transaction.sale({
+ 'amount': payment_method.total,
+ 'payment_method_nonce': transaction_token,
+ 'options': {
+ 'submit_for_settlement': AUTO_CHARGE,
+ 'three_d_secure': {
+ 'required': THREE_D_SECURE_REQUIRED
+ }}})
+ gateway_response = extract_gateway_response(result)
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.AUTH,
+ amount=payment_method.total,
+ gateway_response=gateway_response,
+ token=result.transaction.id,
+ is_success=result.is_success)[0]
+ return txn
+
+def charge(payment_method, amount=None, **client_kwargs):
+ gateway = get_gateway(**client_kwargs)
+ auth_transaction = payment_method.transactions.filter(
+ transaction_type=TransactionType.AUTH).first()
+ if not amount:
+ amount = payment_method.total
+ result = gateway.transaction.submit_for_settlement(
+ transaction_id=auth_transaction.token,
+ amount=amount)
+ gateway_response = extract_gateway_response(result)
+
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.CHARGE,
+ amount=amount,
+ token=result.transaction.id,
+ is_success=result.is_success,
+ gateway_response=gateway_response)
+ return txn
+
+def void(payment_method, **client_kwargs):
+ gateway = get_gateway(**client_kwargs)
+
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.VOID,
+ amount=payment_method.total,
+ gateway_response={},
+ defaults={
+ 'token': str(uuid.uuid4()),
+ 'is_success': dummy_success()})[0]
+ return txn
+
+def refund(payment_method, amount=None, **client_kwargs):
+ gateway = get_gateway(**client_kwargs)
+
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.REFUND,
+ amount=amount,
+ defaults={
+ 'token': str(uuid.uuid4()),
+ 'gateway_response': {},
+ 'is_success': dummy_success()})[0]
+ return txn
diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.py
index 4a5a93f985..13ba6d46af 100644
--- a/saleor/payment/providers/dummy/__init__.py
+++ b/saleor/payment/providers/dummy/__init__.py
@@ -8,7 +8,7 @@ def dummy_success():
return True
-def authorize(payment_method):
+def authorize(payment_method, transaction_token):
txn = create_transaction(
payment_method=payment_method,
transaction_type=TransactionType.AUTH,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 98a265fd1d..a14a4ea2b1 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -30,7 +30,7 @@ def create_transaction(
return txn
-def gateway_authorize(payment_method):
+def gateway_authorize(payment_method, transaction_token) -> Transaction:
if not payment_method.is_active:
raise PaymentError('This payment method is no longer active')
if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:
@@ -38,7 +38,7 @@ def gateway_authorize(payment_method):
provider, provider_params = get_provider(payment_method.variant)
with transaction.atomic():
- txn = provider.authorize(payment_method, **provider_params)
+ txn = provider.authorize(payment_method, transaction_token, **provider_params)
if txn.is_success:
payment_method.charge_status = PaymentMethodChargeStatus.NOT_CHARGED
payment_method.save(update_fields=['charge_status'])
@@ -48,7 +48,7 @@ def gateway_authorize(payment_method):
return txn
-def gateway_charge(payment_method, amount):
+def gateway_charge(payment_method, amount) -> Transaction:
if not payment_method.is_active:
raise PaymentError('This payment method is no longer active')
if not payment_method.charge_status in {
@@ -73,7 +73,7 @@ def gateway_charge(payment_method, amount):
return txn
-def gateway_void(payment_method):
+def gateway_void(payment_method) -> Transaction:
if not payment_method.is_active:
raise PaymentError('This payment method is no longer active')
if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:
@@ -89,7 +89,7 @@ def gateway_void(payment_method):
return txn
-def gateway_refund(payment_method, amount):
+def gateway_refund(payment_method, amount) -> Transaction:
if not payment_method.is_active:
raise PaymentError('This payment method is no longer active')
if amount > payment_method.captured_amount:
diff --git a/saleor/settings.py b/saleor/settings.py
index f4e5f62eaa..acd1e716a2 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -547,3 +547,21 @@ if SENTRY_DSN:
SERIALIZATION_MODULES = {
'json': 'saleor.core.utils.json_serializer'}
+
+
+PAYMENT_PROVIDERS = {
+ 'dummy': {
+ 'module': 'saleor.payment.providers.dummy',
+ 'connection_params': {}},
+
+ 'braintree': {
+ 'module': 'saleor.payment.providers.braintree',
+ 'connection_params': {
+ 'sandbox_mode': True,
+ 'merchant_id': os.environ.get('BRAINTREE_MERCHANT_ID'),
+ 'public_key': os.environ.get('BRAINTREE_PUBLIC_KEY'),
+ 'private_key': os.environ.get('BRAINTREE_PRIVATE_KEY')
+ }
+ }
+
+}