Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add unified Payment Errors, add additional fields to models
Pacu280c4ddac5178
diff --git a/docs/guides/payments.rst b/docs/guides/payments.rstindex 9ac796c2ec..b19d7abddc 100644--- a/docs/guides/payments.rst+++ b/docs/guides/payments.rst@@ -234,3 +234,20 @@ Enabling new payment gatewayLast but not least, if you want to enable your payment gateway in the checkoutprocess, add it's name to the ``CHECKOUT_PAYMENT_GATEWAYS`` setting.++Handling errors+---------------++Gateway-specific errors should be parsed to Saleor's universal format.+More on this can be found at++Tips+----++- Whenever possible, use ``currency`` and ``amount`` as **returned** by the+ payment gateway, not the one that was sent to it. It might happen, that+ gateway (eg. Braintree) is set to different currency than your shop is.+ In such case, you might want to charge the customer 70 dollars, but due+ to gateway misconfiguration, he will be charged 70 euros.+ Such a situation should be handled, and adequate error should be thrown.+diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex 3f74de1191..8ca045dc21 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -19,6 +19,20 @@ class CustomPaymentChoices:(MANUAL, pgettext_lazy('Custom payment choice type', 'Manual'))]+class TransactionError(Enum):+ INCORRECT_NUMBER = 'incorrect_number'+ INVALID_NUMBER = 'invalid_number'+ INCORRECT_CVV = 'incorrect_cvv'+ INVALID_CVV = 'invalid_cvv'+ INCORRECT_ZIP = 'incorrect_zip'+ INCORRECT_ADDRESS = 'incorrect_address'+ INVALID_EXPIRY_DATE = 'invalid_expiry_date'+ EXPIRED = 'expired'+ PROCESSING_ERROR = 'processing_error'+ DECLINED = 'declined'+++class Transactions:"""- Authorization: An amount reserved against the customer's fundingdiff --git a/saleor/payment/forms.py b/saleor/payment/forms.pyindex 0c0b6cd340..06b9827af9 100644--- a/saleor/payment/forms.py+++ b/saleor/payment/forms.py@@ -69,6 +69,7 @@ class BraintreePaymentForm(forms.Form):'payment error','Unable to process transaction. Please try again in a moment')raise ValidationError(msg)+ cleaned_data['payment_method_nonce'] = 'fake-valid-nonce'return cleaned_datadef process_payment(self):diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.pyindex 102213359f..c658a75161 100644--- a/saleor/payment/gateways/braintree/__init__.py+++ b/saleor/payment/gateways/braintree/__init__.py@@ -37,13 +37,14 @@ ERROR_CODES_WHITELIST = {def get_customer_data(payment: Payment) -> Dict:return {+ "order_id": payment.order_id,'billing': {'first_name': payment.billing_first_name,'last_name': payment.billing_last_name,'company': payment.billing_company_name,'postal_code': payment.billing_postal_code,- 'street_address': payment.billing_address_1[:255],- 'extended_address': payment.billing_address_2[:255],+ 'street_address': payment.billing_address_1,+ 'extended_address': payment.billing_address_2,"locality": payment.billing_city,'region': payment.billing_country_area,'country_code_alpha2': payment.billing_country_code},@@ -90,6 +91,7 @@ def transaction_and_incorrect_token_error(def extract_gateway_response(braintree_result) -> Dict:"""Extract data from Braintree response that will be stored locally."""+ import pdb; pdb.set_trace()errors = []if not braintree_result.is_success:errors = [@@ -106,16 +108,7 @@ def extract_gateway_response(braintree_result) -> Dict:gateway_response = {'currency': bt_transaction.currency_iso_code,'amount': bt_transaction.amount, # Decimal type- 'created_at': str(bt_transaction.created_at), # datetime type'credit_card': bt_transaction.credit_card,- 'additional_processor_response': bt_transaction.additional_processor_response, # noqa- 'gateway_rejection_reason': bt_transaction.gateway_rejection_reason,- 'processor_response_code': bt_transaction.processor_response_code,- 'processor_response_text': bt_transaction.processor_response_text,- 'processor_settlement_response_code': bt_transaction.processor_settlement_response_code, # noqa- 'processor_settlement_response_text': bt_transaction.processor_settlement_response_text, # noqa- 'risk_data': bt_transaction.risk_data,- 'status': bt_transaction.status,'errors': errors}return gateway_response@@ -161,6 +154,17 @@ def authorize(payment, type=Transactions.AUTH, token=transaction_token)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])+ credit_card_data = gateway_response.pop('credit_cart')+ if credit_card_data:+ payment.cc_first_digits = credit_card_data.bin+ payment.cc_last_digits = credit_card_data.last_4+ payment.cc_brand = credit_card_data.card_type+ payment.cc_expiry_month = credit_card_data.expiration_month+ payment.cc_expiry_year = credit_card_data.expiration_year+ payment.save(update_fields=[+ 'cc_first_digits', 'cc_last_digits', 'cc_brand',+ 'cc_expiry_month', 'cc_expiry_year'])+txn = create_transaction(payment=payment,kind=Transactions.AUTH,@@ -194,6 +198,7 @@ def capture(txn = create_transaction(payment=payment,+ parent=auth_transaction,kind=Transactions.CAPTURE,amount=gateway_response.pop('amount', amount),currency=gateway_response.pop('currency', payment.currency),@@ -220,6 +225,7 @@ def void(error = get_error_for_client(gateway_response['errors'])txn = create_transaction(payment=payment,+ parent=auth_transaction,kind=Transactions.VOID,amount=gateway_response.pop('amount', payment.total),currency=gateway_response.pop('currency', payment.currency),@@ -249,6 +255,7 @@ def refund(error = get_error_for_client(gateway_response['errors'])txn = create_transaction(payment=payment,+ parent=capture_txn,kind=Transactions.REFUND,amount=gateway_response.pop('amount', amount),currency=gateway_response.pop('currency', payment.currency),diff --git a/saleor/payment/gateways/braintree/errors.py b/saleor/payment/gateways/braintree/errors.pynew file mode 100644index 0000000000..b27ebe067f--- /dev/null+++ b/saleor/payment/gateways/braintree/errors.py@@ -0,0 +1,112 @@+"""We are NOT handling errors from:+- Braintree Marketplace+- Dispute+- Apple Pay+- OAuth+- Venmo+- Search+- Recurring Billing+- 3D Secure+- Customer+as they are not currently supported.++For the full list of errors please refer to:+https://developers.braintreepayments.com/reference/general/validation-errors/all/python#transaction+"""+from ... import TransactionError++INVALID_EXPIRY_DATE_ERRORS = [+ '81709', # Expiration date is required.+ '81710', # Expiration date is invalid.+ '81711', # Expiration year is invalid. It must be between 1975 and 2201.+ '81712', # Expiration month is invalid.+ '81713', # Expiration year is invalid.+]+INCORRECT_ADDRESS_ERRORS = [+ '81801', # Addresses must have at least one field filled in.+ '81802', # Company is too long.+ '81804', # Extended address is too long.+ '81805', # First name is too long.+ '81806', # Last name is too long.+ '81807', # Locality is too long.+ '81810', # Region is too long.+ '81811', # Street address is required.+ '81812', # Street address is too long.+]+INCORRECT_ZIP_ERRORS = [+ '81813', # Postal code can only contain letters, numbers, spaces, and hyphens.+ '81808', # Postal code is required.+ '81809', # Postal code may contain no more than 9 letter or number characters.+ '81737', # Postal code verification failed.+ '91826', # Postal code must be a string.+ '94527', # Billing postal code format is invalid.+ '915164', # Shipping amount is too large.+ '915165', # Ships from postal code is too long.+ '915166', # Ships from postal code must be a string.+ '915167', # Ships from Postal code can only contain letters, numbers, spaces, and hyphens.+]+INCORRECT_CVV_ERRORS = [+ '81706', # CVV is required.+ '81707', # CVV must be 4 digits for American Express and 3 digits for other card types.+]+INVALID_CVV_ERRORS = [+ '81736' # CVV verification failed.+]+INVALID_NUMBER_ERRORS = [+ '81750', # Credit card number is prohibited.+ '81715', # Credit card number is invalid.+]+INCORRECT_NUMBER_ERRORS = [+ '81714', # Credit card number is required.+ '81718', # Credit card number cannot be updated to an unsupported card type when it is associated to subscriptions.+ '81716', # Credit card number must be 12-19 digits.+ '81717', # Credit card number is not an accepted test number.+]+INCORRECT_ADDRESS_ERRORS = [+ '81827', # US state codes must be two characters to meet PayPal Seller Protection requirements.+ '91803', # Country name is not an accepted country.+ '91815', # Provided country information is inconsistent.+ '91816', # Country code (alpha3) is not an accepted country.+ '91817', # Country code (numeric) is not an accepted country.+ '91814', # Country code (alpha2) is not an accepted country.+ '91818', # Customer has already reached the maximum of 50 addresses.+ '91819', # First name must be a string.+ '91820', # Last name must be a string.+ '91821', # Company must be a string.+ '91822', # Street address must be a string.+ '91823', # Extended address must be a string.+ '91824', # Locality must be a string.+ '91825', # Region must be a string.+ '91828', # Address is invalid.+ '918996', # Required attribute is missing+ '918997', # Attribute is not in the required format+ '918998', # Attribute is not in the list of expected values+ '918999', # Attribute is the wrong type+]+EXPIRED_ERRORS = [+ '93108', # Unknown or expired payment_method_nonce.+ '91732', # Unknown or expired payment_method_nonce.+ '92908', # Unknown or expired payment_method_nonce.+ '92911', # PayPal authentication expired.+ '91565', # Unknown or expired payment_method_nonce.+]++DEFAULT_ERROR_TYPE = TransactionError.PROCESSING_ERROR+ERRORS = {+ TransactionError.INCORRECT_NUMBER: INCORRECT_NUMBER_ERRORS,+ TransactionError.INVALID_NUMBER: INVALID_NUMBER_ERRORS,+ TransactionError.INCORRECT_CVV: INCORRECT_CVV_ERRORS,+ TransactionError.INVALID_CVV: INVALID_CVV_ERRORS,+ TransactionError.INCORRECT_ZIP: INCORRECT_ZIP_ERRORS,+ TransactionError.INCORRECT_ADDRESS: INCORRECT_ADDRESS_ERRORS,+ TransactionError.INVALID_EXPIRY_DATE: INVALID_EXPIRY_DATE_ERRORS,+ TransactionError.EXPIRED: EXPIRED_ERRORS,+ TransactionError.PROCESSING_ERROR: [],+ TransactionError.DECLINED: []}+++def get_error_type(error_code):+ for error_type, error_codes in ERRORS:+ if error_code in error_codes+ return error_type+ return DEFAULT_ERROR_TYPEdiff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex a38f1211c6..ecfca43629 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -7,7 +7,8 @@ from django.db import modelsfrom django_prices.models import MoneyFieldfrom prices import Money-from . import ChargeStatus, CustomPaymentChoices, Transactions+from . import (+ ChargeStatus, CustomPaymentChoices, TransactionError, Transactions)from ..checkout.models import Cartfrom ..core.utils.taxes import zero_moneyfrom ..order.models import Order@@ -37,7 +38,6 @@ class Payment(models.Model):choices=ChargeStatus.CHOICES,default=ChargeStatus.NOT_CHARGED)- # FIXME maybe assign it as a separate Address instance?billing_first_name = models.CharField(max_length=256, blank=True)billing_last_name = models.CharField(max_length=256, blank=True)billing_company_name = models.CharField(max_length=256, blank=True)@@ -53,8 +53,8 @@ class Payment(models.Model):extra_data = models.TextField(blank=True, default='')token = models.CharField(max_length=36, blank=True, default='')- #: Currency code (may be gateway-specific)- # FIXME: ISO4217 validator?+ #: Currency code (might be gateway-specific)+ # FIXME: add ISO4217 validator?currency = models.CharField(max_length=10)#: Total amount (gross)total = models.DecimalField(@@ -71,6 +71,13 @@ class Payment(models.Model):order = models.ForeignKey(Order, null=True, related_name='payments', on_delete=models.PROTECT)+ # Credit Card data, if applicable+ cc_first_digits = models.CharField(max_length=6, blank=True, default='')+ cc_last_digits = models.CharField(max_length=4, blank=True, default='')+ cc_brand = models.CharField(max_length=40, blank=True, default='')+ cc_expiry_month = models.CharField(max_length=2, blank=True, default='')+ cc_expiry_year = models.CharField(max_length=4, blank=True, default='')+def __repr__(self):return 'Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)' % (self.gateway, self.is_active, self.created, self.charge_status)@@ -82,14 +89,6 @@ class Payment(models.Model):return Money(self.captured_amount, self.currency or settings.DEFAULT_CURRENCY)- def get_last_transaction(self):- return max(self.transactions.all(), default=None, key=attrgetter('pk'))-- def get_auth_transaction(self):- txn = self.transactions.get(- kind=Transactions.AUTH, is_success=True)- return txn-def authorize(self, transaction_token):from . import utilsreturn utils.gateway_authorize(@@ -123,9 +122,8 @@ class Payment(models.Model):def can_refund(self):return (- self.is_active and- self.charge_status == ChargeStatus.CHARGED and- self.gateway != CustomPaymentChoices.MANUAL)+ self.is_active and self.charge_status == ChargeStatus.CHARGED+ and self.gateway != CustomPaymentChoices.MANUAL)class Transaction(models.Model):@@ -136,8 +134,7 @@ class Transaction(models.Model):payment = models.ForeignKey(Payment, related_name='transactions', on_delete=models.PROTECT)token = models.CharField(max_length=64, blank=True, default='')- kind = models.CharField(- max_length=10, choices=Transactions.CHOICES)+ kind = models.CharField(max_length=10, choices=Transactions.CHOICES)# FIXME probably we should have error/pending/success status instead of# a bool, eg for payments with 3d secureis_success = models.BooleanField(default=False)@@ -149,7 +146,13 @@ class Transaction(models.Model):max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=Decimal('0.0'))-+ # Unified error code across all payment gateways+ error = models.CharField(+ choices=[(tag, tag.value) for tag in TransactionError],+ max_length=256, null=True)+ parent = models.ForeignKey(+ 'payment.Transaction', related_name='+', on_delete=models.PROTECT,+ blank=True, null=True)gateway_response = JSONField()def __repr__(self):diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 85c9f09c58..bcae0f79fa 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -15,20 +15,7 @@ from .models import Payment, Transactionlogger = logging.getLogger(__name__)-# PAYMENT_ERRORS = {-# 'incorrect_number':-# 'invalid_number':-# 'invalid_expiry_date':-# 'invalid_cvc':-# 'expired_card':-# 'incorrect_cvc':-# 'incorrect_zip':-# 'incorrect_address':-# 'card_declined':-# 'processing_error':-# 'call_issuer':-# 'pick_up_card':-# }+def get_billing_data(order):data = {}if order.billing_address:diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.pyindex b7995c962e..a2c75a0732 100644--- a/tests/gateway/test_braintree.py+++ b/tests/gateway/test_braintree.py@@ -33,14 +33,14 @@ def braintree_success_response():spec=Transaction,amount=Decimal('0.20'),created_at='2018-10-20 18:34:22',- credit_card={- 'token': None,- 'bin': '400000',- 'last_4': '0002',- 'card_type': 'Visa',- 'expiration_month': '01',- 'expiration_year': '2020',- 'customer_location': 'International'},+ credit_card=Mock(+ token=None,+ bin='400000',+ last_4='0002',+ card_type='Visa',+ expiration_month='01',+ expiration_year='2020',+ customer_location='International'),additional_processor_response='',gateway_rejection_reason='',processor_response_code='1000',