Skip to content

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

Adjust Braintree payment process

Pacu23994c78d4f8e
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 21e15bab6f..5c0e05d9e8 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -20,18 +20,12 @@ class PaymentMethodInput(graphene.InputObjectType):
checkout_id = graphene.ID(description='Checkout ID.')
transaction_token = graphene.String(
required=True, description='One time transaction token.')
- tax = Decimal(
- required=True,
- description='Tax included in the transaction\'s total amount.')
amount = Decimal(
required=True,
description=(
'Total amount of the transaction, including '
'all taxes and discounts.'))
billing_address = AddressInput(description='Billing address')
- store_payment_method = graphene.Boolean(
- default_value=False,
- description='Store card for further usage.')
class CheckoutPaymentMethodCreate(BaseMutation, I18nMixin):
@@ -64,10 +58,8 @@ class CheckoutPaymentMethodCreate(BaseMutation, I18nMixin):
extra_data = cls.get_extra_info(info)
gross = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)
- tax = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)
- net = (gross - tax) or gross
payment_method = create_payment_method(
- total_net=net, total_gross=gross,
+ total_gross=gross,
variant=input['gateway'], billing_email=checkout.email,
extra_data=extra_data, checkout=checkout,
**billing_data)
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index eb59bd10c8..7b5d988366 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -12,6 +12,7 @@ PaymentChargeStatusEnum = graphene.Enum(
class PaymentMethod(CountableDjangoObjectType):
+ #FIXME gateway_response field should be resolved into query-readable format
charge_status = PaymentChargeStatusEnum(
description='Internal payment status.', required=True)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5fe2d1f9a2..0bfb7fbab1 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1255,7 +1255,6 @@ input PaymentMethodInput {
tax: Decimal!
amount: Decimal!
billingAddress: AddressInput
- storePaymentMethod: Boolean = false
}
type PaymentMethodRefund {
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 06e3378c99..fd6c20726e 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -25,7 +25,9 @@ class TransactionType:
CAPTURE = 'capture'
VOID = 'void'
REFUND = 'refund'
-
+ # FIXME we could use another status like WAITING_FOR_AUTH for transactions
+ # Which were authorized, ubt needs to be confirmed manually by staff
+ # eg. Braintree with submit_for_settlement's enabled
CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),
(CHARGE, pgettext_lazy('transaction type', 'Charge')),
(REFUND, pgettext_lazy('transaction type', 'Refund')),
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 4c79c7b8b8..87f0635290 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -21,6 +21,7 @@ class PaymentMethod(models.Model):
Payment methods belong to a customer, one can use several payments method
within a single order.
"""
+ #FIXME we should provide an option to store the card for later usage
variant = models.CharField(max_length=255)
# FIXME probably we should have error/pending/active status instead of
# a bool
diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.py
index f3e4c6134d..958e28baac 100644
--- a/saleor/payment/providers/braintree/__init__.py
+++ b/saleor/payment/providers/braintree/__init__.py
@@ -9,10 +9,30 @@ from ...utils import create_transaction
# FIXME: Move to SiteSettings
-AUTO_CHARGE = False
+# If this option is checked, then one needs to authorize the amount paid
+# manually via the Braintree Dashboard
+CONFIRM_MANUALLY = False
THREE_D_SECURE_REQUIRED = False
+def get_customer_data(payment):
+ return {
+ 'billing': {
+ 'first_name': payment.billing_first_name,
+ 'last_name': payment.billing_last_name,
+ 'postal_code': payment.billing_postal_code,
+ 'street_address': payment.billing_address_1[:255],
+ 'extended_address': payment.billing_address_2[:255],
+ "locality": payment.billing_city,
+ 'region': payment.billing_country_area,
+ 'country_code_alpha2': payment.billing_country_code},
+ 'risk_data': {
+ 'customer_ip': payment.customer_ip_address or ''
+ },
+ 'customer': {
+ 'email': payment.billing_email}}
+
+
def get_error_for_client(errors):
"""Filters all error messages and decides which one is visible for the
client side.
@@ -24,6 +44,8 @@ def get_error_for_client(errors):
'payment error',
'Unable to process transaction. Please try again in a moment')
# FIXME: Provide list of visible errors and messages translations
+ # FIXME: We should also store universal visible errors for all payment
+ # gateways, and parse gateway-specific errors to this unified version
error_codes_whitelist = []
for error in errors:
if error['code'] in error_codes_whitelist:
@@ -38,8 +60,9 @@ def extract_gateway_response(braintree_result) -> Dict:
errors = [
{'code': error.code, 'message': error.message}
for error in braintree_result.errors.deep_errors]
-
bt_transaction = braintree_result.transaction
+ if not bt_transaction:
+ return {'errors': errors}
gateway_response = {
'credit_card': bt_transaction.credit_card,
'additional_processor_response': bt_transaction.additional_processor_response, # noqa
@@ -56,16 +79,7 @@ def extract_gateway_response(braintree_result) -> Dict:
def get_gateway(sandbox_mode, merchant_id, public_key, private_key):
if not all([merchant_id, private_key, public_key]):
- missing = []
- if not merchant_id:
- missing.append('Merchant ID')
- if not public_key:
- missing.append('Public Key')
- if not private_key:
- missing.append('Private Key')
- raise ImproperlyConfigured(
- 'Incorrectly configured Braintree gateway.'
- ' Missing: %s' % ', '.join(missing))
+ raise ImproperlyConfigured('Incorrectly configured Braintree gateway.')
environment = braintree_sdk.Environment.Sandbox
if not sandbox_mode:
environment = braintree_sdk.Environment.Production
@@ -91,8 +105,9 @@ def authorize(payment_method, transaction_token, **client_kwargs):
'amount': str(payment_method.total.gross.amount),
'payment_method_nonce': transaction_token,
'options': {
- 'submit_for_settlement': AUTO_CHARGE,
- 'three_d_secure': {'required': THREE_D_SECURE_REQUIRED}}})
+ 'submit_for_settlement': CONFIRM_MANUALLY,
+ 'three_d_secure': {'required': THREE_D_SECURE_REQUIRED}},
+ **get_customer_data(payment_method)})
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
txn = create_transaction(
@@ -100,7 +115,7 @@ def authorize(payment_method, transaction_token, **client_kwargs):
transaction_type=TransactionType.AUTH,
amount=payment_method.total.gross.amount,
gateway_response=gateway_response,
- token=result.transaction.id,
+ token=getattr(result.transaction, 'id', ''),
is_success=result.is_success)
return txn, error
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index d06fc6f71c..b43554e98d 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -111,13 +111,13 @@ def gateway_capture(
amount: Decimal) -> Transaction:
if amount <= 0:
raise PaymentError('Amount should be a positive number.')
- amount = Money(amount, currency=settings.DEFAULT_CURRENCY)
if payment_method.charge_status not in {
ChargeStatus.CHARGED,
ChargeStatus.NOT_CHARGED}:
raise PaymentError('This payment method cannot be captured.')
- if amount > payment_method.total.gross or amount > (
- payment_method.total.gross - payment_method.captured_amount):
+ if amount > payment_method.total.gross.amount or amount > (
+ payment_method.total.gross.amount -
+ payment_method.captured_amount.amount):
raise PaymentError('Unable to capture more than authorized amount.')
provider, provider_params = get_provider(payment_method.variant)
@@ -126,7 +126,8 @@ def gateway_capture(
payment_method, amount=amount, **provider_params)
if txn.is_success:
payment_method.charge_status = ChargeStatus.CHARGED
- payment_method.captured_amount += txn.amount
+ payment_method.captured_amount += Money(
+ txn.amount, settings.DEFAULT_CURRENCY)
payment_method.save(
update_fields=['charge_status', 'captured_amount'])
order = payment_method.order
@@ -159,8 +160,7 @@ def gateway_refund(
amount: Decimal) -> Transaction:
if amount <= 0:
raise PaymentError('Amount should be a positive number.')
- amount = Money(amount, currency=settings.DEFAULT_CURRENCY)
- if amount > payment_method.captured_amount:
+ if amount > payment_method.captured_amount.amount:
raise PaymentError('Cannot refund more than captured')
if not payment_method.charge_status == ChargeStatus.CHARGED:
raise PaymentError(
@@ -171,7 +171,7 @@ def gateway_refund(
txn, error = provider.refund(payment_method, amount, **provider_params)
if txn.is_success:
changed_fields = ['captured_amount']
- if txn.amount == payment_method.total.gross:
+ if txn.amount == payment_method.total.gross.amount:
payment_method.charge_status = ChargeStatus.FULLY_REFUNDED
payment_method.is_active = False
changed_fields += ['charge_status', 'is_active']
diff --git a/saleor/settings.py b/saleor/settings.py
index b02bd1336d..d99430f3c6 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -182,7 +182,7 @@ MIDDLEWARE = [
'saleor.core.middleware.taxes',
'social_django.middleware.SocialAuthExceptionMiddleware',
'impersonate.middleware.ImpersonateMiddleware',
- 'saleor.graphql.middleware.jwt_middleware'
+ # 'saleor.graphql.middleware.jwt_middleware'
]
INSTALLED_APPS = [
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index 820f80f6dc..6b02371380 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -100,8 +100,7 @@ def test_checkout_add_payment_method(
'transactionToken': 'sample-token',
'amount': str(cart.get_total().gross.amount),
'tax': str(cart.get_total().tax.amount),
- 'billingAddress': graphql_address_data,
- 'storePaymentMethod': False}}
+ 'billingAddress': graphql_address_data}}
response = user_api_client.post_graphql(CREATE_QUERY, variables)
content = get_graphql_content(response)
data = content['data']['checkoutPaymentMethodCreate']