Skip to content

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

Remove old stripe implementation

Jakub Draganeke01af8a0afaa
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index 07d561b69e..07bb928f9a 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -3,7 +3,7 @@ from graphql_jwt.decorators import permission_required
from ..core.fields import PrefetchingConnectionField
from .enums import PaymentGatewayEnum
-from .mutations import PaymentCapture, PaymentRefund, PaymentVoid, PaymentSecureConfirm
+from .mutations import PaymentCapture, PaymentRefund, PaymentSecureConfirm, PaymentVoid
from .resolvers import resolve_payment_client_token, resolve_payments
from .types import Payment
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index feda4d4b41..881b9d7b9b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1447,7 +1447,6 @@ enum GatewaysEnum {
BRAINTREE
RAZORPAY
STRIPE
- STRIPE_NEW
}
scalar GenericScalar
diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.py
index c8950ea3da..9f017568fe 100644
--- a/saleor/payment/gateways/stripe/__init__.py
+++ b/saleor/payment/gateways/stripe/__init__.py
@@ -1,25 +1,27 @@
-from typing import Dict
+from typing import List
import stripe
from ... import TransactionKind
-from ...interface import GatewayConfig, GatewayResponse, PaymentData
-from .forms import StripePaymentModalForm
+from ...interface import (
+ CreditCardInfo,
+ CustomerSource,
+ GatewayConfig,
+ GatewayResponse,
+ PaymentData,
+)
from .utils import (
get_amount_for_stripe,
get_amount_from_stripe,
get_currency_for_stripe,
get_currency_from_stripe,
- get_payment_billing_fullname,
shipping_to_stripe_dict,
)
def get_client_token(**_):
- """Not implemented for Stripe gateway currently.
-
- The client token can be automatically generated by
- Stripe's checkout.js or stripe.js.
+ """Not implemented for stripe gateway currently. The client token can be
+ generated by Stripe's checkout.js or stripe.js automatically.
"""
return
@@ -27,201 +29,207 @@ def get_client_token(**_):
def authorize(
payment_information: PaymentData, config: GatewayConfig
) -> GatewayResponse:
- client, error = _get_client(**config.connection_params), None
+ kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
+ client = _get_client(**config.connection_params)
+ capture_method = "automatic" if config.auto_capture else "manual"
+ currency = get_currency_for_stripe(payment_information.currency)
+ stripe_amount = get_amount_for_stripe(payment_information.amount, currency)
+ future_use = "off_session" if config.store_customer else "on_session"
+ customer_id = PaymentData.customer_id if payment_information.reuse_source else None
+ shipping = (
+ shipping_to_stripe_dict(payment_information.shipping)
+ if payment_information.shipping
+ else None
+ )
try:
- # Authorize with/without capture
- response = _create_stripe_charge(
- client=client,
- payment_information=payment_information,
- should_capture=config.auto_capture,
+ intent = client.PaymentIntent.create(
+ payment_method=payment_information.token,
+ amount=stripe_amount,
+ currency=currency,
+ confirmation_method="manual",
+ confirm=True,
+ capture_method=capture_method,
+ setup_future_usage=future_use,
+ customer=customer_id,
+ shipping=shipping,
)
+ if config.store_customer and not customer_id:
+ customer = client.Customer.create(payment_method=intent.payment_method)
+ customer_id = customer.id
+ success = intent.status in ("succeeded", "requires_capture", "requires_action")
+ response = _success_response(
+ intent=intent, kind=kind, success=success, customer_id=customer_id
+ )
+ response = fill_card_details(intent, response)
except stripe.error.StripeError as exc:
- response = _get_error_response_from_exc(exc)
- error = exc.user_message
-
- kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
-
- # Create response
- return _create_response(
- payment_information=payment_information,
- kind=kind,
- response=response,
- error=error,
- )
+ response = _error_response(kind=kind, exc=exc, payment_info=payment_information)
+ return response
def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client, error = _get_client(**config.connection_params), None
+ client = _get_client(**config.connection_params)
+ intent = None
+ try:
+ intent = client.PaymentIntent.retrieve(id=payment_information.token)
+ capture = intent.capture()
+ response = _success_response(
+ intent=intent,
+ kind=TransactionKind.CAPTURE,
+ success=capture.status in ("succeeded", "requires_action"),
+ )
+ response = fill_card_details(intent, response)
+ except stripe.error.StripeError as exc:
+ action_required = intent.status == "requires_action" if intent else False
+ response = _error_response(
+ kind=TransactionKind.CAPTURE,
+ exc=exc,
+ payment_info=payment_information,
+ action_required=action_required,
+ )
+ return response
- # Get amount from argument or payment, and convert to stripe's amount
- amount = payment_information.amount
- stripe_amount = get_amount_for_stripe(amount, payment_information.currency)
+def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
+ client = _get_client(**config.connection_params)
try:
- # Retrieve stripe charge and capture specific amount
- stripe_charge = client.Charge.retrieve(payment_information.token)
- response = stripe_charge.capture(amount=stripe_amount)
+ intent = client.PaymentIntent(id=payment_information.token)
+ intent.confirm()
+ response = _success_response(
+ intent=intent,
+ kind=TransactionKind.CONFIRM,
+ success=intent.status == "succeeded",
+ )
+ response = fill_card_details(intent, response)
except stripe.error.StripeError as exc:
- response = _get_error_response_from_exc(exc)
- error = exc.user_message
-
- # Create response
- return _create_response(
- payment_information=payment_information,
- kind=TransactionKind.CAPTURE,
- response=response,
- error=error,
- )
+ response = _error_response(
+ kind=TransactionKind.CONFIRM, exc=exc, payment_info=payment_information
+ )
+ return response
def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client, error = _get_client(**config.connection_params), None
-
- # Get amount from payment, and convert to stripe's amount
- amount = payment_information.amount
- stripe_amount = get_amount_for_stripe(amount, payment_information.currency)
-
+ client = _get_client(**config.connection_params)
+ currency = get_currency_for_stripe(payment_information.currency)
+ stripe_amount = get_amount_for_stripe(payment_information.amount, currency)
try:
- # Retrieve stripe charge and refund specific amount
- stripe_charge = client.Charge.retrieve(payment_information.token)
- response = client.Refund.create(charge=stripe_charge.id, amount=stripe_amount)
+ intent = client.PaymentIntent.retrieve(id=payment_information.token)
+ refund = intent["charges"]["data"][0].refund(amount=stripe_amount)
+ response = _success_response(
+ intent=intent,
+ kind=TransactionKind.REFUND,
+ success=refund.status == "succeeded",
+ amount=payment_information.amount,
+ currency=get_currency_from_stripe(refund.currency),
+ )
except stripe.error.StripeError as exc:
- response = _get_error_response_from_exc(exc)
- error = exc.user_message
-
- # Create response
- return _create_response(
- payment_information=payment_information,
- kind=TransactionKind.REFUND,
- response=response,
- error=error,
- )
+ response = _error_response(
+ kind=TransactionKind.REFUND, exc=exc, payment_info=payment_information
+ )
+ return response
def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client, error = _get_client(**config.connection_params), None
-
+ client = _get_client(**config.connection_params)
try:
- # Retrieve stripe charge and refund all
- stripe_charge = client.Charge.retrieve(payment_information.token)
- response = client.Refund.create(charge=stripe_charge.id)
+ intent = client.PaymentIntent.retrieve(id=payment_information.token)
+ refund = intent["charges"]["data"][0].refund()
+ response = _success_response(
+ intent=intent,
+ kind=TransactionKind.VOID,
+ currency=get_currency_from_stripe(refund.currency),
+ raw_response=refund,
+ )
except stripe.error.StripeError as exc:
- response = _get_error_response_from_exc(exc)
- error = exc.user_message
-
- # Create response
- return _create_response(
- payment_information=payment_information,
- kind=TransactionKind.VOID,
- response=response,
- error=error,
- )
+ response = _error_response(
+ kind=TransactionKind.VOID, exc=exc, payment_info=payment_information
+ )
+ return response
+
+
+def list_client_sources(
+ config: GatewayConfig, customer_id: str
+) -> List[CustomerSource]:
+ client = _get_client(**config.connection_params)
+ cards = client.PaymentMethod.list(customer=customer_id, type="card")["data"]
+ return [
+ CustomerSource(
+ id=c.id,
+ gateway="stripe",
+ credit_card_info=CreditCardInfo(
+ exp_year=c.card.exp_year,
+ exp_month=c.card.exp_month,
+ last_4=c.card.last4,
+ name_on_card=None,
+ ),
+ )
+ for c in cards
+ ]
def process_payment(
payment_information: PaymentData, config: GatewayConfig
) -> GatewayResponse:
- # Stripe supports capture during authorize process. No need to run other steps.
- # If 'config.auto_capture is True', it will also capture funds from the card.
return authorize(payment_information, config)
-def create_form(
- data: Dict, payment_information: PaymentData, connection_params: Dict
-) -> StripePaymentModalForm:
- return StripePaymentModalForm(
- data=data,
- payment_information=payment_information,
- gateway_params=connection_params,
- )
-
-
def _get_client(**connection_params):
stripe.api_key = connection_params.get("secret_key")
return stripe
-def _get_stripe_charge_payload(
- payment_information: PaymentData, should_capture: bool
-) -> Dict:
- shipping = payment_information.shipping
-
- # Get currency
- currency = get_currency_for_stripe(payment_information.currency)
-
- # Get appropriate amount for stripe
- stripe_amount = get_amount_for_stripe(payment_information.amount, currency)
-
- # Get billing name from payment
- name = get_payment_billing_fullname(payment_information)
-
- # Construct the charge payload from the data
- charge_payload = {
- "capture": should_capture,
- "amount": stripe_amount,
- "currency": currency,
- "source": payment_information.token,
- "description": name,
- }
-
- if shipping:
- # Update shipping address to prevent fraud in Stripe
- charge_payload["shipping"] = {
- "name": name,
- "address": shipping_to_stripe_dict(shipping),
- }
-
- return charge_payload
-
-
-def _create_stripe_charge(client, payment_information, should_capture: bool):
- """Create a charge with specific amount, ignoring payment's total."""
- charge_payload = _get_stripe_charge_payload(payment_information, should_capture)
- return client.Charge.create(**charge_payload)
-
-
-def _create_response(
- payment_information: PaymentData, kind: str, response: Dict, error: str
+def _error_response(
+ kind: TransactionKind,
+ exc: Exception,
+ payment_info: PaymentData,
+ action_required: bool = False,
) -> GatewayResponse:
- # Get currency from response or payment
- currency = get_currency_from_stripe(
- response.get("currency", payment_information.currency)
+ return GatewayResponse(
+ is_success=False,
+ action_required=action_required,
+ transaction_id=payment_info.token,
+ amount=payment_info.amount,
+ currency=payment_info.currency,
+ error=exc.user_message,
+ kind=kind,
+ raw_response=exc.json_body or {},
+ customer_id=payment_info.customer_id,
)
- amount = payment_information.amount
- # Get amount from response or payment
- if "amount" in response:
- stripe_amount = response.get("amount")
- if "amount_refunded" in response:
- # This happens for partial catpure which will refund the left
- # Then the actual amount should minus refunded amount
- stripe_amount -= response.get("amount_refunded")
- amount = get_amount_from_stripe(stripe_amount, currency)
-
- # Get token from response or use provided one
- token = response.get("id", payment_information.token)
-
- # Check if the response's status is flagged as succeeded
- is_success = response.get("status") == "succeeded"
+
+def _success_response(
+ intent: stripe.PaymentIntent,
+ kind: TransactionKind,
+ success: bool = True,
+ amount=None,
+ currency=None,
+ customer_id=None,
+ raw_response=None,
+):
+ currency = currency or get_currency_from_stripe(intent.currency)
return GatewayResponse(
- is_success=is_success,
- action_required=False,
- transaction_id=token,
- kind=kind,
- amount=amount,
+ is_success=success,
+ action_required=intent.status == "requires_action",
+ transaction_id=intent.id,
+ amount=amount or get_amount_from_stripe(intent.amount, currency),
currency=currency,
- error=error,
- raw_response=response,
+ error=None,
+ kind=kind,
+ raw_response=raw_response or intent,
+ customer_id=customer_id,
)
-def _get_error_response_from_exc(exc):
- response = exc.json_body
-
- # Some errors from stripe don't json_body as None
- # such as stripe.error.InvalidRequestError
- if response is None:
- response = dict()
+def fill_card_details(intent: stripe.PaymentIntent, response: GatewayResponse):
+ charges = intent.charges["data"]
+ if not charges:
+ return response
+ card = intent.charges["data"][-1]["payment_method_details"]["card"]
+ response.card_info = CreditCardInfo(
+ last_4=card["last4"],
+ exp_year=card["exp_year"],
+ exp_month=card["exp_month"],
+ brand=card["brand"],
+ )
return response
diff --git a/saleor/payment/gateways/stripe/errors.py b/saleor/payment/gateways/stripe/errors.py
deleted file mode 100644
index 90d803b32e..0000000000
--- a/saleor/payment/gateways/stripe/errors.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from django.utils.translation import pgettext_lazy
-
-ORDER_NOT_AUTHORIZED = pgettext_lazy(
- "Stripe payment error", "Order was not authorized."
-)
-ORDER_NOT_CHARGED = pgettext_lazy("Stripe payment error", "Order was not charged.")
diff --git a/saleor/payment/gateways/stripe/forms.py b/saleor/payment/gateways/stripe/forms.py
deleted file mode 100644
index 93f8ea0ac3..0000000000
--- a/saleor/payment/gateways/stripe/forms.py
+++ /dev/null
@@ -1,85 +0,0 @@
-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 ...interface import PaymentData
-from .utils import get_amount_for_stripe
-
-CHECKOUT_SCRIPT_URL = "https://checkout.stripe.com/checkout.js"
-CHECKOUT_DESCRIPTION = pgettext_lazy(
- "Stripe payment gateway description", "Total payment"
-)
-
-
-class StripeCheckoutWidget(HiddenInput):
- def __init__(
- self, payment_information: PaymentData, 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
- ),
- "data-name": gateway_params.get("store_name"),
- "data-image": gateway_params.get("store_image"),
- "data-description": CHECKOUT_DESCRIPTION,
- "data-currency": payment_information.currency,
- "data-locale": gateway_params.get("locale"),
- "data-allow-remember-me": "true"
- if gateway_params.get("remember_me")
- else "false",
- "data-billing-address": "true"
- if gateway_params.get("enable_billing_address")
- else "false",
- "data-zip-code": "true"
- if gateway_params.get("enable_billing_address")
- else "false",
- "data-shipping-address": "true"
- if gateway_params.get("enable_shipping_address")
- else "false",
- }
-
- if gateway_params.get("prefill"):
- kwargs["attrs"].update({"data-email": payment_information.customer_email})
-
- kwargs["attrs"].update(attrs)
- super(StripeCheckoutWidget, self).__init__(*args, **kwargs)
-
- def render(self, name=None, value=None, attrs=None, renderer=None):
- attrs = attrs or {}
- attrs.update(self.attrs)
- attrs.pop("id", None)
- return format_html("<script{0}></script>", flatatt(attrs))
-
-
-class StripePaymentModalForm(forms.Form):
- """The modal form of the Stripe payment provider.
-
- At this moment partial-payment is not supported, but there is no need to
- validate amount, which may be manually adjusted in the template,
- since checkout.js can do that automatically.
- """
-
- stripeToken = forms.CharField(required=True, widget=HiddenInput)
-
- def __init__(
- self, payment_information: PaymentData, gateway_params: Dict, *args, **kwargs
- ):
- super().__init__(*args, **kwargs)
-
- self.fields["stripe"] = forms.CharField(
- widget=StripeCheckoutWidget(
- payment_information=payment_information, gateway_params=gateway_params
- ),
- required=False,
- )
-
- def get_payment_token(self):
- return self.cleaned_data["stripeToken"]
diff --git a/saleor/payment/gateways/stripe/utils.py b/saleor/payment/gateways/stripe/utils.py
index 7732dd9313..ca4a068629 100644
--- a/saleor/payment/gateways/stripe/utils.py
+++ b/saleor/payment/gateways/stripe/utils.py
@@ -31,7 +31,6 @@ ZERO_DECIMAL_CURRENCIES = [
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
-
Stripe is using currency's smallest unit such as cents for USD and
stripe requires integer instead of decimal, so multiplying by 100
and converting to integer is required. But for zero-decimal currencies,
@@ -61,7 +60,6 @@ def get_amount_from_stripe(amount, currency):
def get_currency_for_stripe(currency):
"""Convert Saleor's currency format to Stripe's currency format.
-
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.lower()
@@ -69,7 +67,6 @@ def get_currency_for_stripe(currency):
def get_currency_from_stripe(currency):
"""Convert Stripe's currency format to Saleor's currency format.
-
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.upper()
@@ -85,10 +82,14 @@ def get_payment_billing_fullname(payment_information: PaymentData) -> str:
def shipping_to_stripe_dict(shipping: AddressData) -> Dict:
return {
- "line1": shipping.street_address_1,
- "line2": shipping.street_address_2,
- "city": shipping.city,
- "state": shipping.country_area,
- "postal_code": shipping.postal_code,
- "country": dict(countries).get(shipping.country, ""),
+ "name": shipping.first_name + " " + shipping.last_name,
+ "phone": shipping.phone,
+ "address": {
+ "line1": shipping.street_address_1,
+ "line2": shipping.street_address_2,
+ "city": shipping.city,
+ "state": shipping.country_area,
+ "postal_code": shipping.postal_code,
+ "country": dict(countries).get(shipping.country, ""),
+ },
}
diff --git a/saleor/payment/gateways/stripe_new/__init__.py b/saleor/payment/gateways/stripe_new/__init__.py
deleted file mode 100644
index f2473d8e4f..0000000000
--- a/saleor/payment/gateways/stripe_new/__init__.py
+++ /dev/null
@@ -1,246 +0,0 @@
-from typing import Dict, List
-
-import stripe
-
-from ... import TransactionKind
-from ...interface import (
- CustomerSource,
- CreditCardInfo,
- GatewayConfig,
- GatewayResponse,
- PaymentData,
-)
-from .forms import StripePaymentModalForm
-from .utils import (
- get_amount_for_stripe,
- get_amount_from_stripe,
- get_currency_for_stripe,
- get_currency_from_stripe,
- shipping_to_stripe_dict,
-)
-
-
-def get_client_token(**_):
- """Not implemented for stripe gateway currently. The client token can be
- generated by Stripe's checkout.js or stripe.js automatically.
- """
- return
-
-
-def authorize(
- payment_information: PaymentData, config: GatewayConfig
-) -> GatewayResponse:
- kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
- client = _get_client(**config.connection_params)
- capture_method = "automatic" if config.auto_capture else "manual"
- currency = get_currency_for_stripe(payment_information.currency)
- stripe_amount = get_amount_for_stripe(payment_information.amount, currency)
- future_use = "off_session" if config.store_customer else "on_session"
- customer_id = PaymentData.customer_id if payment_information.reuse_source else None
- shipping = (
- shipping_to_stripe_dict(payment_information.shipping)
- if payment_information.shipping
- else None
- )
-
- try:
- intent = client.PaymentIntent.create(
- payment_method=payment_information.token,
- amount=stripe_amount,
- currency=currency,
- confirmation_method="manual",
- confirm=True,
- capture_method=capture_method,
- setup_future_usage=future_use,
- customer=customer_id,
- shipping=shipping,
- )
- if config.store_customer and not customer_id:
- customer = client.Customer.create(payment_method=intent.payment_method)
- customer_id = customer.id
- success = intent.status in ("succeeded", "requires_capture", "requires_action")
- response = _success_response(
- intent=intent, kind=kind, success=success, customer_id=customer_id
- )
- response = fill_card_details(intent, response)
- except stripe.error.StripeError as exc:
- response = _error_response(kind=kind, exc=exc, payment_info=payment_information)
- return response
-
-
-def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client = _get_client(**config.connection_params)
- intent = None
- try:
- intent = client.PaymentIntent.retrieve(id=payment_information.token)
- capture = intent.capture()
- response = _success_response(
- intent=intent,
- kind=TransactionKind.CAPTURE,
- success=capture.status in ("succeeded", "requires_action"),
- )
- response = fill_card_details(intent, response)
- except stripe.error.StripeError as exc:
- action_required = intent.status == "requires_action" if intent else False
- response = _error_response(
- kind=TransactionKind.CAPTURE,
- exc=exc,
- payment_info=payment_information,
- action_required=action_required,
- )
- return response
-
-
-def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client = _get_client(**config.connection_params)
- try:
- intent = client.PaymentIntent(id=payment_information.token)
- intent.confirm()
- response = _success_response(
- intent=intent,
- kind=TransactionKind.CONFIRM,
- success=intent.status == "succeeded",
- )
- response = fill_card_details(intent, response)
- except stripe.error.StripeError as exc:
- response = _error_response(
- kind=TransactionKind.CONFIRM, exc=exc, payment_info=payment_information
- )
- return response
-
-
-def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client = _get_client(**config.connection_params)
- currency = get_currency_for_stripe(payment_information.currency)
- stripe_amount = get_amount_for_stripe(payment_information.amount, currency)
- try:
- intent = client.PaymentIntent.retrieve(id=payment_information.token)
- refund = intent["charges"]["data"][0].refund(amount=stripe_amount)
- response = _success_response(
- intent=intent,
- kind=TransactionKind.REFUND,
- success=refund.status == "succeeded",
- amount=payment_information.amount,
- currency=get_currency_from_stripe(refund.currency),
- )
- except stripe.error.StripeError as exc:
- response = _error_response(
- kind=TransactionKind.REFUND, exc=exc, payment_info=payment_information
- )
- return response
-
-
-def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:
- client = _get_client(**config.connection_params)
- try:
- intent = client.PaymentIntent.retrieve(id=payment_information.token)
- refund = intent["charges"]["data"][0].refund()
- response = _success_response(
- intent=intent,
- kind=TransactionKind.VOID,
- currency=get_currency_from_stripe(refund.currency),
- raw_response=refund,
- )
- except stripe.error.StripeError as exc:
- response = _error_response(
- kind=TransactionKind.VOID, exc=exc, payment_info=payment_information
- )
- return response
-
-
-def list_client_sources(
- config: GatewayConfig, customer_id: str
-) -> List[CustomerSource]:
- client = _get_client(**config.connection_params)
- cards = client.PaymentMethod.list(customer=customer_id, type="card")["data"]
- return [
- CustomerSource(
- id=c.id,
- gateway="stripe",
- credit_card_info=CreditCardInfo(
- exp_year=c.card.exp_year,
- exp_month=c.card.exp_month,
- last_4=c.card.last4,
- name_on_card=None,
- ),
- )
- for c in cards
- ]
-
-
-def process_payment(
- payment_information: PaymentData, config: GatewayConfig
-) -> GatewayResponse:
- return authorize(payment_information, config)
-
-
-def create_form(
- data: Dict, payment_information: PaymentData, connection_params: Dict
-) -> StripePaymentModalForm:
- return StripePaymentModalForm(
- data=data,
- payment_information=payment_information,
- gateway_params=connection_params,
- )
-
-
-def _get_client(**connection_params):
- stripe.api_key = connection_params.get("secret_key")
- return stripe
-
-
-def _error_response(
- kind: TransactionKind,
- exc: Exception,
- payment_info: PaymentData,
- action_required: bool = False,
-) -> GatewayResponse:
- return GatewayResponse(
- is_success=False,
- action_required=action_required,
- transaction_id=payment_info.token,
- amount=payment_info.amount,
- currency=payment_info.currency,
- error=exc.user_message,
- kind=kind,
- raw_response=exc.json_body or {},
- customer_id=payment_info.customer_id,
- )
-
-
-def _success_response(
- intent: stripe.PaymentIntent,
- kind: TransactionKind,
- success: bool = True,
- amount=None,
- currency=None,
- customer_id=None,
- raw_response=None,
-):
- currency = currency or get_currency_from_stripe(intent.currency)
- return GatewayResponse(
- is_success=success,
- action_required=intent.status == "requires_action",
- transaction_id=intent.id,
- amount=amount or get_amount_from_stripe(intent.amount, currency),
- currency=currency,
- error=None,
- kind=kind,
- raw_response=raw_response or intent,
- customer_id=customer_id,
- )
-
-
-def fill_card_details(intent: stripe.PaymentIntent, response: GatewayResponse):
- charges = intent.charges["data"]
- if not charges:
- return response
-
- card = intent.charges["data"][-1]["payment_method_details"]["card"]
- response.card_info = CreditCardInfo(
- last_4=card["last4"],
- exp_year=card["exp_year"],
- exp_month=card["exp_month"],
- brand=card["brand"],
- )
- return response
diff --git a/saleor/payment/gateways/stripe_new/utils.py b/saleor/payment/gateways/stripe_new/utils.py
deleted file mode 100644
index ca4a068629..0000000000
--- a/saleor/payment/gateways/stripe_new/utils.py
+++ /dev/null
@@ -1,95 +0,0 @@
-from decimal import Decimal
-from typing import Dict
-
-from django_countries import countries
-
-# List of zero-decimal currencies
-# 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 ...interface import AddressData, PaymentData
-
-ZERO_DECIMAL_CURRENCIES = [
- "BIF",
- "CLP",
- "DJF",
- "GNF",
- "JPY",
- "KMF",
- "KRW",
- "MGA",
- "PYG",
- "RWF",
- "UGX",
- "VND",
- "VUV",
- "XAF",
- "XOF",
- "XPF",
-]
-
-
-def get_amount_for_stripe(amount, currency):
- """Get appropriate amount for stripe.
- Stripe is using currency's smallest unit such as cents for USD and
- stripe requires integer instead of decimal, so multiplying by 100
- and converting to integer is required. But for zero-decimal currencies,
- multiplying by 100 is not needed.
- """
- # Multiply by 100 for non-zero-decimal currencies
- if currency.upper() not in ZERO_DECIMAL_CURRENCIES:
- amount *= 100
-
- # Using int(Decimal) directly may yield wrong result
- # such as int(Decimal(24.24)*100) will equal to 2423
- return int(amount.to_integral_value())
-
-
-def get_amount_from_stripe(amount, currency):
- """Get appropriate amount from stripe."""
- amount = Decimal(amount)
-
- # Divide by 100 for non-zero-decimal currencies
- if currency.upper() not in ZERO_DECIMAL_CURRENCIES:
- # Using Decimal(amount / 100.0) will convert to decimal from float
- # where precision may be lost
- amount /= Decimal(100)
-
- return amount
-
-
-def get_currency_for_stripe(currency):
- """Convert Saleor's currency format to Stripe's currency format.
- Stripe's currency is using lowercase while Saleor is using uppercase.
- """
- return currency.lower()
-
-
-def get_currency_from_stripe(currency):
- """Convert Stripe's currency format to Saleor's currency format.
- Stripe's currency is using lowercase while Saleor is using uppercase.
- """
- return currency.upper()
-
-
-def get_payment_billing_fullname(payment_information: PaymentData) -> str:
- # Get billing name from payment
- return "%s %s" % (
- payment_information.billing.last_name,
- payment_information.billing.first_name,
- )
-
-
-def shipping_to_stripe_dict(shipping: AddressData) -> Dict:
- return {
- "name": shipping.first_name + " " + shipping.last_name,
- "phone": shipping.phone,
- "address": {
- "line1": shipping.street_address_1,
- "line2": shipping.street_address_2,
- "city": shipping.city,
- "state": shipping.country_area,
- "postal_code": shipping.postal_code,
- "country": dict(countries).get(shipping.country, ""),
- },
- }
diff --git a/saleor/settings.py b/saleor/settings.py
index fb7ca5c45b..6066567624 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -606,7 +606,6 @@ DUMMY = "dummy"
BRAINTREE = "braintree"
RAZORPAY = "razorpay"
STRIPE = "stripe"
-STRIPE_NEW = "stripe_new"
CHECKOUT_PAYMENT_GATEWAYS = {
DUMMY: pgettext_lazy("Payment method name", "Dummy gateway")
diff --git a/tests/api/test_gift_card.py b/tests/api/test_gift_card.py
index e5852be015..915b1f7216 100644
--- a/tests/api/test_gift_card.py
+++ b/tests/api/test_gift_card.py
@@ -1,6 +1,7 @@
from datetime import date
import graphene
+
from tests.api.utils import get_graphql_content
from .utils import assert_no_permission
diff --git a/tests/gateway/stripe/test_stripe.py b/tests/gateway/stripe/test_stripe.py
index 459291a71c..d11a5c2167 100644
--- a/tests/gateway/stripe/test_stripe.py
+++ b/tests/gateway/stripe/test_stripe.py
@@ -1,16 +1,16 @@
+import os
from decimal import Decimal
from math import isclose
-import os
import pytest
from saleor.payment import ChargeStatus
-from saleor.payment.gateways.stripe_new import (
+from saleor.payment.gateways.stripe import (
TransactionKind,
+ _get_client,
authorize,
capture,
confirm,
- _get_client,
get_client_token,
list_client_sources,
refund,
@@ -35,7 +35,7 @@ RECORD = False
@pytest.fixture()
def gateway_config():
return GatewayConfig(
- gateway_name="stripe_new",
+ gateway_name="stripe",
auto_capture=True,
template_path="template.html",
connection_params={
diff --git a/tests/gateway/stripe/test_utils.py b/tests/gateway/stripe/test_utils.py
index b20c4a3c8f..87fcd40768 100644
--- a/tests/gateway/stripe/test_utils.py
+++ b/tests/gateway/stripe/test_utils.py
@@ -3,11 +3,11 @@ from math import isclose
from django_countries import countries
-from saleor.payment.gateways.stripe_new.utils import (
+from saleor.payment.gateways.stripe.utils import (
get_amount_for_stripe,
get_amount_from_stripe,
- get_currency_from_stripe,
get_currency_for_stripe,
+ get_currency_from_stripe,
get_payment_billing_fullname,
shipping_to_stripe_dict,
)
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index b334a450f3..08ea5d205c 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -27,10 +27,10 @@ from saleor.payment.gateways.braintree.errors import (
)
from saleor.payment.gateways.braintree.forms import BraintreePaymentForm
from saleor.payment.interface import (
+ CreditCardInfo,
+ CustomerSource,
GatewayConfig,
TokenConfig,
- CustomerSource,
- CreditCardInfo,
)
from saleor.payment.utils import create_payment_information
diff --git a/tests/gateway/test_stripe.py b/tests/gateway/test_stripe.py
deleted file mode 100644
index 574aa96bb3..0000000000
--- a/tests/gateway/test_stripe.py
+++ /dev/null
@@ -1,652 +0,0 @@
-from decimal import Decimal
-from math import isclose
-from unittest.mock import Mock, patch
-
-import pytest
-import stripe
-from django_countries import countries
-
-from saleor.payment import ChargeStatus
-from saleor.payment.gateways.stripe import (
- TransactionKind,
- _create_response,
- _get_client,
- _get_error_response_from_exc,
- _get_stripe_charge_payload,
- authorize,
- capture,
- create_form,
- get_amount_for_stripe,
- get_amount_from_stripe,
- get_client_token,
- get_currency_for_stripe,
- get_currency_from_stripe,
- refund,
- void,
-)
-from saleor.payment.gateways.stripe.forms import (
- StripeCheckoutWidget,
- StripePaymentModalForm,
-)
-from saleor.payment.gateways.stripe.utils import (
- get_payment_billing_fullname,
- shipping_to_stripe_dict,
-)
-from saleor.payment.interface import AddressData, GatewayConfig
-from saleor.payment.utils import create_payment_information
-
-TRANSACTION_AMOUNT = Decimal(42.42)
-TRANSACTION_REFUND_AMOUNT = Decimal(24.24)
-TRANSACTION_CURRENCY = "USD"
-TRANSACTION_TOKEN = "fake-stripe-id"
-FAKE_TOKEN = "fake-token"
-ERROR_MESSAGE = "error-message"
-
-
-def gateway_config():
- return GatewayConfig(
- gateway_name="stripe",
- auto_capture=False,
- template_path="template.html",
- connection_params={
- "public_key": "public",
- "secret_key": "secret",
- "store_name": "Saleor",
- "store_image": "image.gif",
- "prefill": True,
- "remember_me": True,
- "locale": "auto",
- "enable_billing_address": False,
- "enable_shipping_address": False,
- },
- )
-
-
-def client_token():
- return FAKE_TOKEN
-
-
-def stripe_payment(payment_dummy):
- payment_dummy.total = TRANSACTION_AMOUNT
- payment_dummy.currency = TRANSACTION_CURRENCY
- return payment_dummy
-
-
-def stripe_authorized_payment(stripe_payment):
- stripe_payment.charge_status = ChargeStatus.NOT_CHARGED
- stripe_payment.save(update_fields=["charge_status"])
-
- return stripe_payment
-
-
-def stripe_captured_payment(stripe_payment):
- stripe_payment.captured_amount = stripe_payment.total
- stripe_payment.charge_status = ChargeStatus.FULLY_CHARGED
- stripe_payment.save(update_fields=["captured_amount", "charge_status"])
- stripe_payment.transactions.create(
- amount=stripe_payment.total,
- kind=TransactionKind.CAPTURE,
- gateway_response={},
- is_success=True,
- )
- return stripe_payment
-
-
-def stripe_charge_success_response():
- return {
- "id": TRANSACTION_TOKEN,
- "amount": get_amount_for_stripe(TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
- "amount_refunded": 0,
- "currency": get_currency_for_stripe(TRANSACTION_CURRENCY),
- "status": "succeeded",
- }
-
-
-def stripe_partial_charge_success_response(stripe_charge_success_response):
- response = stripe_charge_success_response.copy()
- response["amount_refunded"] = get_amount_for_stripe(
- TRANSACTION_REFUND_AMOUNT, TRANSACTION_CURRENCY
- )
- return response
-
-
-def stripe_refund_success_response(stripe_charge_success_response):
- response = stripe_charge_success_response.copy()
- response.pop("amount_refunded")
- response["amount"] = get_amount_for_stripe(
- TRANSACTION_REFUND_AMOUNT, TRANSACTION_CURRENCY
- )
- return response
-
-
-def test_get_amount_for_stripe():
- assert get_amount_for_stripe(Decimal(1), "USD") == 100
- assert get_amount_for_stripe(Decimal(1), "usd") == 100
-
- assert get_amount_for_stripe(Decimal(0.01), "USD") == 1
- assert get_amount_for_stripe(Decimal(24.24), "USD") == 2424
- assert get_amount_for_stripe(Decimal(42.42), "USD") == 4242
-
- assert get_amount_for_stripe(Decimal(1), "JPY") == 1
- assert get_amount_for_stripe(Decimal(1), "jpy") == 1
-
-
-def test_get_amount_from_stripe():
- assert get_amount_from_stripe(100, "USD") == Decimal(1)
- assert get_amount_from_stripe(100, "usd") == Decimal(1)
-
- assert isclose(get_amount_from_stripe(1, "USD"), Decimal(0.01))
- assert isclose(get_amount_from_stripe(2424, "USD"), Decimal(24.24))
- assert isclose(get_amount_from_stripe(4242, "USD"), Decimal(42.42))
-
- assert get_amount_from_stripe(1, "JPY") == Decimal(1)
- assert get_amount_from_stripe(1, "jpy") == Decimal(1)
-
-
-def test_get_currency_for_stripe():
- assert get_currency_for_stripe("USD") == "usd"
- assert get_currency_for_stripe("usd") == "usd"
- assert get_currency_for_stripe("uSd") == "usd"
-
-
-def test_get_currency_from_stripe():
- assert get_currency_from_stripe("USD") == "USD"
- assert get_currency_from_stripe("usd") == "USD"
- assert get_currency_from_stripe("uSd") == "USD"
-
-
-def test_get_payment_billing_fullname(payment_dummy):
- payment_info = create_payment_information(payment_dummy)
-
- expected_fullname = "%s %s" % (
- payment_dummy.billing_last_name,
- payment_dummy.billing_first_name,
- )
- assert get_payment_billing_fullname(payment_info) == expected_fullname
-
-
-def test_shipping_address_to_stripe_dict(address):
- address_data = AddressData(**address.as_data())
- expected_address_dict = {
- "line1": address.street_address_1,
- "line2": address.street_address_2,
- "city": address.city,
- "state": address.country_area,
- "postal_code": address.postal_code,
- "country": dict(countries).get(address.country, ""),
- }
- assert shipping_to_stripe_dict(address_data) == expected_address_dict
-
-
-def test_widget_with_default_options(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment)
- widget = StripeCheckoutWidget(payment_info, gateway_config.connection_params)
- assert widget.render() == (
- '<script class="stripe-button" data-allow-remember-me="true" '
- 'data-amount="4242" data-billing-address="false" data-currency="USD" '
- 'data-description="Total payment" data-email="[email protected]" '
- 'data-image="image.gif" data-key="public" data-locale="auto" '
- 'data-name="Saleor" data-shipping-address="false" '
- 'data-zip-code="false" src="https://checkout.stripe.com/checkout.js">'
- "</script>"
- )
-
-
-def test_widget_with_additional_attr(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment)
-
- widget = StripeCheckoutWidget(
- payment_info,
- gateway_config.connection_params,
- attrs={"data-custom": "custom-data"},
- )
- assert 'data-custom="custom-data"' in widget.render()
-
-
-def test_widget_with_prefill_option(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment)
- connection_params = gateway_config.connection_params
- connection_params["prefill"] = True
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-email="[email protected]"' in widget.render()
-
- connection_params["prefill"] = False
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-email="[email protected]"' not in widget.render()
-
-
-def test_widget_with_remember_me_option(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment)
- connection_params = gateway_config.connection_params
-
- connection_params["remember_me"] = True
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-allow-remember-me="true"' in widget.render()
-
- connection_params["remember_me"] = False
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-allow-remember-me="false"' in widget.render()
-
-
-def test_widget_with_enable_billing_address_option(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
- connection_params = gateway_config.connection_params
-
- connection_params["enable_billing_address"] = True
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-billing-address="true"' in widget.render()
- assert 'data-zip-code="true"' in widget.render()
-
- connection_params["enable_billing_address"] = False
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-billing-address="false"' in widget.render()
- assert 'data-zip-code="false"' in widget.render()
-
-
-def test_widget_with_enable_shipping_address_option(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
- connection_params = gateway_config.connection_params
-
- connection_params["enable_shipping_address"] = True
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-shipping-address="true"' in widget.render()
-
- connection_params["enable_shipping_address"] = False
- widget = StripeCheckoutWidget(payment_info, connection_params)
- assert 'data-shipping-address="false"' in widget.render()
-
-
-def test_stripe_payment_form(stripe_payment, gateway_config):
- payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
- form = create_form(
- None,
- payment_information=payment_info,
- connection_params=gateway_config.connection_params,
- )
- assert isinstance(form, StripePaymentModalForm)
- assert not form.is_valid()
-
- form = create_form(
- data={"stripeToken": FAKE_TOKEN},
- payment_information=payment_info,
- connection_params=gateway_config.connection_params,
- )
- assert isinstance(form, StripePaymentModalForm)
- assert form.is_valid()
-
-
-def test_get_client(gateway_config):
- assert _get_client(**gateway_config.connection_params).api_key == "secret"
-
-
-def test_get_client_token():
- assert get_client_token() is None
-
-
-def test_get_error_response_from_exc():
- stripe_error = stripe.error.StripeError(json_body={"message": ERROR_MESSAGE})
- invalid_request_error = stripe.error.InvalidRequestError(
- message=ERROR_MESSAGE, param=None
- )
-
- assert _get_error_response_from_exc(stripe_error) == {"message": ERROR_MESSAGE}
- assert _get_error_response_from_exc(invalid_request_error) == {}
-
-
-def test_get_stripe_charge_payload_with_shipping(stripe_payment):
- payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
- billing_name = get_payment_billing_fullname(payment_info)
- expected_payload = {
- "capture": True,
- "amount": get_amount_for_stripe(TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
- "currency": get_currency_for_stripe(TRANSACTION_CURRENCY),
- "source": FAKE_TOKEN,
- "description": billing_name,
- "shipping": {
- "name": billing_name,
- "address": shipping_to_stripe_dict(payment_info.shipping),
- },
- }
-
- charge_payload = _get_stripe_charge_payload(payment_info, True)
-
- assert charge_payload == expected_payload
-
-
-def test_get_stripe_charge_payload_without_shipping(stripe_payment):
- stripe_payment.order.shipping_address = None
- payment_info = create_payment_information(stripe_payment, FAKE_TOKEN)
- billing_name = get_payment_billing_fullname(payment_info)
- expected_payload = {
- "capture": True,
- "amount": get_amount_for_stripe(TRANSACTION_AMOUNT, TRANSACTION_CURRENCY),
- "currency": get_currency_for_stripe(TRANSACTION_CURRENCY),
- "source": FAKE_TOKEN,
- "description": billing_name,
- }
-
- charge_payload = _get_stripe_charge_payload(payment_info, True)
-
- assert charge_payload == expected_payload
-
-
-def test_create_transaction_with_charge_success_response(
- stripe_payment, stripe_charge_success_response
-):
- payment_info = create_payment_information(stripe_payment)
-
- response = _create_response(
- payment_information=payment_info,
- kind="ANYKIND",
- response=stripe_charge_success_response,
- error=None,
- )
-
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.is_success is True
- assert isclose(response.amount, TRANSACTION_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
-
-
-def test_create_transaction_with_partial_charge_success_response(
- stripe_payment, stripe_partial_charge_success_response
-):
- payment_info = create_payment_information(stripe_payment)
-
- response = _create_response(
- payment_information=payment_info,
- kind="ANYKIND",
- response=stripe_partial_charge_success_response,
- error=None,
- )
-
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.is_success is True
- assert isclose(response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
-
-
-def test_create_transaction_with_refund_success_response(
- stripe_payment, stripe_refund_success_response
-):
- payment_info = create_payment_information(stripe_payment)
-
- response = _create_response(
- payment_information=payment_info,
- kind="ANYKIND",
- response=stripe_refund_success_response,
- error=None,
- )
-
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.is_success is True
- assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
-
-
-def test_create_response_with_error_response(stripe_payment):
- payment = stripe_payment
- payment_info = create_payment_information(payment, FAKE_TOKEN)
- stripe_error_response = {}
-
- response = _create_response(
- payment_information=payment_info,
- kind="ANYKIND",
- response=stripe_error_response,
- error=None,
- )
-
- assert response.transaction_id == FAKE_TOKEN
- assert response.is_success is False
- assert response.amount == payment.total
- assert response.currency == payment.currency
-
-
-@patch("stripe.Charge.create")
-def test_authorize(
- mock_charge_create, stripe_payment, gateway_config, stripe_charge_success_response
-):
- payment = stripe_payment
- payment_info = create_payment_information(payment, FAKE_TOKEN)
- response = stripe_charge_success_response
- mock_charge_create.return_value = response
-
- response = authorize(payment_info, gateway_config)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.AUTH
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_charge_success_response
-
-
-@patch("stripe.Charge.create")
-def test_authorize_error_response(mock_charge_create, stripe_payment, gateway_config):
- payment = stripe_payment
- payment_info = create_payment_information(payment, FAKE_TOKEN)
- stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
- mock_charge_create.side_effect = stripe_error
-
- response = authorize(payment_info, gateway_config)
-
- assert response.error == ERROR_MESSAGE
- assert response.transaction_id == FAKE_TOKEN
- assert response.kind == TransactionKind.AUTH
- assert not response.is_success
- assert response.amount == payment.total
- assert response.currency == payment.currency
- assert response.raw_response == _get_error_response_from_exc(stripe_error)
-
-
-@patch("stripe.Charge.retrieve")
-def test_capture(
- mock_charge_retrieve,
- stripe_authorized_payment,
- gateway_config,
- stripe_charge_success_response,
-):
- payment = stripe_authorized_payment
- payment_info = create_payment_information(payment, amount=TRANSACTION_AMOUNT)
- response = stripe_charge_success_response
- mock_charge_retrieve.return_value = Mock(capture=Mock(return_value=response))
-
- response = capture(payment_info, gateway_config)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.CAPTURE
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_charge_success_response
-
-
-@patch("stripe.Charge.retrieve")
-def test_partial_capture(
- mock_charge_retrieve,
- stripe_authorized_payment,
- gateway_config,
- stripe_partial_charge_success_response,
-):
- payment = stripe_authorized_payment
- payment_info = create_payment_information(payment, amount=TRANSACTION_AMOUNT)
- response = stripe_partial_charge_success_response
- mock_charge_retrieve.return_value = Mock(capture=Mock(return_value=response))
-
- response = capture(payment_info, gateway_config)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.CAPTURE
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_partial_charge_success_response
-
-
-@patch("stripe.Charge.retrieve")
-def test_capture_error_response(
- mock_charge_retrieve, stripe_authorized_payment, gateway_config
-):
- payment = stripe_authorized_payment
- payment_info = create_payment_information(
- payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT
- )
- stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
- mock_charge_retrieve.side_effect = stripe_error
-
- response = capture(payment_info, gateway_config)
-
- assert response.error == ERROR_MESSAGE
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.CAPTURE
- assert not response.is_success
- assert response.amount == payment.total
- assert response.currency == payment.currency
- assert response.raw_response == _get_error_response_from_exc(stripe_error)
-
-
-@patch("stripe.Refund.create")
-@patch("stripe.Charge.retrieve")
-def test_refund_charged(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_captured_payment,
- gateway_config,
- stripe_refund_success_response,
-):
- payment = stripe_captured_payment
- payment_info = create_payment_information(
- payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT
- )
- response = stripe_refund_success_response
- mock_charge_retrieve.return_value = Mock(id="")
- mock_refund_create.return_value = response
-
- response = refund(payment_info, gateway_config)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.REFUND
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_refund_success_response
-
-
-@patch("stripe.Refund.create")
-@patch("stripe.Charge.retrieve")
-def test_refund_captured(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_captured_payment,
- gateway_config,
- stripe_refund_success_response,
-):
- payment = stripe_captured_payment
- payment_info = create_payment_information(payment, amount=TRANSACTION_AMOUNT)
- response = stripe_refund_success_response
- mock_charge_retrieve.return_value = Mock(id="")
- mock_refund_create.return_value = response
-
- response = refund(payment_info, gateway_config)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.REFUND
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_refund_success_response
-
-
-@patch("stripe.Refund.create")
-@patch("stripe.Charge.retrieve")
-def test_refund_error_response(
- mock_charge_retrieve, mock_refund_create, stripe_captured_payment, gateway_config
-):
- payment = stripe_captured_payment
- payment_info = create_payment_information(
- payment, TRANSACTION_TOKEN, amount=TRANSACTION_AMOUNT
- )
- mock_charge_retrieve.return_value = Mock(id="")
- stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
- mock_refund_create.side_effect = stripe_error
-
- response = refund(payment_info, gateway_config)
-
- assert response.error == ERROR_MESSAGE
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.REFUND
- assert not response.is_success
- assert response.amount == payment.total
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == _get_error_response_from_exc(stripe_error)
-
-
-@patch("stripe.Refund.create")
-@patch("stripe.Charge.retrieve")
-def test_void(
- mock_charge_retrieve,
- mock_refund_create,
- stripe_authorized_payment,
- gateway_config,
- stripe_refund_success_response,
-):
- payment = stripe_authorized_payment
- payment_info = create_payment_information(payment, TRANSACTION_TOKEN)
- response = stripe_refund_success_response
- mock_charge_retrieve.return_value = Mock(id="")
- mock_refund_create.return_value = response
-
- response = void(payment_info, gateway_config)
-
- assert not response.error
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.VOID
- assert response.is_success
- assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == stripe_refund_success_response
-
-
-@patch("stripe.Refund.create")
-@patch("stripe.Charge.retrieve")
-def test_void_error_response(
- mock_charge_retrieve, mock_refund_create, stripe_authorized_payment, gateway_config
-):
- payment = stripe_authorized_payment
- payment_info = create_payment_information(payment, TRANSACTION_TOKEN)
- mock_charge_retrieve.return_value = Mock(id="")
- stripe_error = stripe.error.InvalidRequestError(message=ERROR_MESSAGE, param=None)
- mock_refund_create.side_effect = stripe_error
-
- response = void(payment_info, gateway_config)
-
- assert response.error == ERROR_MESSAGE
- assert response.transaction_id == TRANSACTION_TOKEN
- assert response.kind == TransactionKind.VOID
- assert not response.is_success
- assert response.amount == payment.total
- assert response.currency == TRANSACTION_CURRENCY
- assert response.raw_response == {}
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 68de13090b..f8f6303266 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -14,10 +14,10 @@ from saleor.payment import (
get_payment_gateway,
)
from saleor.payment.interface import (
+ CreditCardInfo,
GatewayConfig,
GatewayResponse,
TokenConfig,
- CreditCardInfo,
)
from saleor.payment.models import Payment
from saleor.payment.utils import (