Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add API for calling payment confirmation
Jakub Draganek888b639b5c82
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 7e6b19233c..d131aefa51 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -8,6 +8,7 @@ from ...payment import PaymentError, modelsfrom ...payment.utils import (create_payment,gateway_capture,+ gateway_confirm,gateway_refund,gateway_void,)@@ -171,3 +172,24 @@ class PaymentVoid(BaseMutation):except PaymentError as e:raise ValidationError(str(e))return PaymentVoid(payment=payment)+++class PaymentSecureConfirm(BaseMutation):+ payment = graphene.Field(Payment, description="Updated payment")++ class Arguments:+ payment_id = graphene.ID(required=True, description="Payment ID")++ class Meta:+ description = "Confirms payment in two step process like 3D secure"++ @classmethod+ def perform_mutation(cls, _root, info, payment_id):+ payment = cls.get_node_or_error(+ info, payment_id, field="payment_id", only_type=Payment+ )+ try:+ gateway_confirm(payment)+ except PaymentError as e:+ raise ValidationError(str(e))+ return PaymentSecureConfirm(payment=payment)diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.pyindex e38fd7ec78..07d561b69e 100644--- a/saleor/graphql/payment/schema.py+++ b/saleor/graphql/payment/schema.py@@ -3,7 +3,7 @@ from graphql_jwt.decorators import permission_requiredfrom ..core.fields import PrefetchingConnectionFieldfrom .enums import PaymentGatewayEnum-from .mutations import PaymentCapture, PaymentRefund, PaymentVoid+from .mutations import PaymentCapture, PaymentRefund, PaymentVoid, PaymentSecureConfirmfrom .resolvers import resolve_payment_client_token, resolve_paymentsfrom .types import Payment@@ -32,3 +32,4 @@ class PaymentMutations(graphene.ObjectType):payment_capture = PaymentCapture.Field()payment_refund = PaymentRefund.Field()payment_void = PaymentVoid.Field()+ payment_secure_confirm = PaymentSecureConfirm.Field()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1b2d873b74..feda4d4b41 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1869,6 +1869,7 @@ type Mutations {paymentCapture(amount: Decimal, paymentId: ID!): PaymentCapturepaymentRefund(amount: Decimal, paymentId: ID!): PaymentRefundpaymentVoid(paymentId: ID!): PaymentVoid+ paymentSecureConfirm(paymentId: ID!): PaymentSecureConfirmpageCreate(input: PageInput!): PageCreatepageDelete(id: ID!): PageDeletepageBulkDelete(ids: [ID]!): PageBulkDelete@@ -2406,6 +2407,11 @@ type PaymentRefund {payment: Payment}+type PaymentSecureConfirm {+ errors: [Error!]+ payment: Payment+}+type PaymentSource {gateway: String!creditCardInfo: CreditCard@@ -3416,6 +3422,7 @@ enum TransactionKind {REFUNDCAPTUREVOID+ CONFIRM}union TranslatableItem = Product | Category | Collection | Attribute | AttributeValue | ProductVariant | Page | ShippingMethod | Sale | Voucher | MenuItemdiff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex 422a42ebee..10f862ae55 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -64,6 +64,7 @@ class TransactionKind:CAPTURE = "capture"VOID = "void"REFUND = "refund"+ CONFIRM = "confirm"# FIXME we could use another status like WAITING_FOR_AUTH for transactions# Which were authorized, but needs to be confirmed manually by staff# eg. Braintree with "submit_for_settlement" enabled@@ -72,6 +73,7 @@ class TransactionKind:(REFUND, pgettext_lazy("transaction kind", "Refund")),(CAPTURE, pgettext_lazy("transaction kind", "Capture")),(VOID, pgettext_lazy("transaction kind", "Void")),+ (CONFIRM, pgettext_lazy("transaction kind", "Confirm")),]diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.pyindex d0292115d9..dfa7e8484b 100644--- a/saleor/payment/gateways/dummy/__init__.py+++ b/saleor/payment/gateways/dummy/__init__.py@@ -69,6 +69,24 @@ def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayR)+def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ """Perform confirm transaction."""+ error = None+ success = dummy_success()+ if not success:+ error = "Unable to process capture"++ return GatewayResponse(+ is_success=success,+ action_required=False,+ kind=TransactionKind.CAPTURE,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_information.token,+ error=error,+ )++def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:error = Nonesuccess = dummy_success()diff --git a/saleor/payment/gateways/stripe_new/__init__.py b/saleor/payment/gateways/stripe_new/__init__.pyindex 4eb675ecd8..066932c911 100644--- a/saleor/payment/gateways/stripe_new/__init__.py+++ b/saleor/payment/gateways/stripe_new/__init__.py@@ -89,12 +89,12 @@ def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayRintent.confirm()response = _success_response(intent=intent,- kind=TransactionKind.CAPTURE,+ kind=TransactionKind.CONFIRM,success=intent.status == "succeeded",)except stripe.error.StripeError as exc:response = _error_response(- kind=TransactionKind.CAPTURE, exc=exc, payment_info=payment_information+ kind=TransactionKind.CONFIRM, exc=exc, payment_info=payment_information)return responsediff --git a/saleor/payment/migrations/0013_auto_20190813_0735.py b/saleor/payment/migrations/0013_auto_20190813_0735.pynew file mode 100644index 0000000000..f812735302--- /dev/null+++ b/saleor/payment/migrations/0013_auto_20190813_0735.py@@ -0,0 +1,25 @@+# Generated by Django 2.2.4 on 2019-08-13 12:35++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [("payment", "0012_transaction_customer_id")]++ operations = [+ migrations.AlterField(+ model_name="transaction",+ name="kind",+ field=models.CharField(+ choices=[+ ("auth", "Authorization"),+ ("refund", "Refund"),+ ("capture", "Capture"),+ ("void", "Void"),+ ("confirm", "Confirm"),+ ],+ max_length=10,+ ),+ )+ ]diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex c7e9cf1879..4fa867f0da 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -374,7 +374,7 @@ def validate_gateway_response(response: GatewayResponse):def _gateway_postprocess(transaction, payment):transaction_kind = transaction.kind- if transaction_kind == TransactionKind.CAPTURE:+ if transaction_kind in {TransactionKind.CAPTURE, TransactionKind.CONFIRM}:payment.captured_amount += transaction.amount# Set payment charge status to fully charged@@ -401,6 +401,15 @@ def _gateway_postprocess(transaction, payment):payment.is_active = Falsechanged_fields += ["charge_status", "is_active"]payment.save(update_fields=changed_fields)+ elif transaction_kind == TransactionKind.CONFIRM:+ payment.captured_amount += transaction.amount+ payment.charge_status = ChargeStatus.PARTIALLY_CHARGED+ if payment.get_charge_amount() <= 0:+ payment.charge_status = ChargeStatus.FULLY_CHARGED+ payment.save(update_fields=["charge_status", "captured_amount"])+ order = payment.order+ if order and order.is_fully_paid():+ handle_fully_paid_order(order)@require_active_payment@@ -481,6 +490,28 @@ def gateway_void(payment) -> Transaction:return transaction+@require_active_payment+def gateway_confirm(payment) -> Transaction:+ if not payment.can_void():+ raise PaymentError("Only pre-authorized transactions can be voided.")++ auth_transaction = payment.transactions.filter(+ kind=TransactionKind.AUTH, is_success=True+ ).first()+ if auth_transaction is None:+ raise PaymentError("Cannot void unauthorized transaction")+ payment_token = auth_transaction.token++ transaction = call_gateway(+ operation_type=OperationType.CONFIRM,+ payment=payment,+ payment_token=payment_token,+ )++ _gateway_postprocess(transaction, payment)+ return transaction++@require_active_paymentdef gateway_refund(payment, amount: Decimal = None) -> Transaction:"""Refund the charged funds back to the customer.diff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex b4f1f28f8c..1cfa17acd9 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -324,6 +324,39 @@ def test_payment_refund_error(assert not txn.is_success+CONFIRM_QUERY = """+ mutation PaymentConfirm($paymentId: ID!) {+ paymentSecureConfirm(paymentId: $paymentId) {+ payment {+ id,+ chargeStatus+ }+ errors {+ field+ message+ }+ }+ }+"""+++def test_payment_confirmation_success(+ user_api_client, payment_txn_preauth, graphql_address_data+):+ payment_id = graphene.Node.to_global_id("Payment", payment_txn_preauth.pk)+ variables = {"paymentId": payment_id}+ response = user_api_client.post_graphql(CONFIRM_QUERY, variables)+ content = get_graphql_content(response)+ data = content["data"]["paymentSecureConfirm"]+ assert not data["errors"]++ payment_txn_preauth.refresh_from_db()+ assert payment_txn_preauth.charge_status == ChargeStatus.FULLY_CHARGED+ assert payment_txn_preauth.transactions.count() == 2+ txn = payment_txn_preauth.transactions.last()+ assert txn.kind == TransactionKind.CAPTURE++def test_payments_query(payment_txn_captured, permission_manage_orders, staff_api_client):diff --git a/tests/gateway/stripe/test_stripe.py b/tests/gateway/stripe/test_stripe.pyindex 9e243c951d..15e7918637 100644--- a/tests/gateway/stripe/test_stripe.py+++ b/tests/gateway/stripe/test_stripe.py@@ -188,7 +188,7 @@ def test_capture_3d_secure(stripe_payment, sandbox_gateway_config):PAYMENT_INTENT = "pi_1F6YmgIUmJaD6Oqv77HUh6qq"ERROR = ("This PaymentIntent could not be captured because it"- "has a status of requires_action."+ " has a status of requires_action."" Only a PaymentIntent with one of the following ""statuses may be captured: requires_capture.")@@ -301,7 +301,7 @@ def test_confirm__intent(stripe_payment, sandbox_gateway_config):payment_info = create_payment_information(stripe_payment, PAYMENT_INTENT)response = confirm(payment_info, sandbox_gateway_config)assert not response.error- assert response.kind == TransactionKind.CAPTURE+ assert response.kind == TransactionKind.CONFIRMassert isclose(response.amount, 45.0)assert response.currency == TRANSACTION_CURRENCYassert response.is_success@@ -317,7 +317,7 @@ def test_confirm_error_response(stripe_payment, sandbox_gateway_config):assert response.error == "No such payment_intent: " + INVALID_INTENTassert response.transaction_id == INVALID_INTENT- assert response.kind == TransactionKind.CAPTURE+ assert response.kind == TransactionKind.CONFIRMassert not response.is_successassert response.amount == stripe_payment.totalassert response.currency == stripe_payment.currency