Skip to content

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

Serve customer source list through API

Jakub Draganek645a574de9a7
diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.py
index 0a8b1149aa..1bcd5ca6a7 100644
--- a/saleor/graphql/payment/resolvers.py
+++ b/saleor/graphql/payment/resolvers.py
@@ -1,8 +1,16 @@
+from itertools import chain
+
import graphene_django_optimizer as gql_optimizer
+from saleor.payment import get_payment_gateway
+
from ...payment import models
from ...payment.interface import TokenConfig
-from ...payment.utils import extract_id_for_payment_gateway, gateway_get_client_token
+from ...payment.utils import (
+ extract_id_for_payment_gateway,
+ gateway_get_client_token,
+ list_enabled_gateways,
+)
from ..utils import filter_by_query_param
PAYMENT_SEARCH_FIELDS = ["id"]
@@ -16,6 +24,26 @@ def resolve_payments(info, query):
def resolve_payment_client_token(gateway=None, user=None):
token_config = TokenConfig()
- if user:
+ if user is not None:
token_config.customer_id = extract_id_for_payment_gateway(user, gateway)
return gateway_get_client_token(gateway, token_config)
+
+
+def resolve_payment_sources(user):
+ def retrieve_sources(gateway_name, customer_id):
+ gateway, config = get_payment_gateway(gateway_name)
+ return gateway.list_client_sources(config, customer_id)
+
+ stored_customer_accounts = {
+ gateway: extract_id_for_payment_gateway(user, gateway)
+ for gateway in list_enabled_gateways()
+ }
+ return [
+ chain(
+ *[
+ retrieve_sources(gateway, customer_id)
+ for gateway, customer_id in stored_customer_accounts
+ if customer_id is not None
+ ]
+ )
+ ]
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index cfd944a2c6..1fd498d836 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -1,10 +1,14 @@
import graphene
-from graphql_jwt.decorators import permission_required
+from graphql_jwt.decorators import permission_required, login_required
from ..core.fields import PrefetchingConnectionField
from .enums import PaymentGatewayEnum
from .mutations import PaymentCapture, PaymentRefund, PaymentVoid
-from .resolvers import resolve_payment_client_token, resolve_payments
+from .resolvers import (
+ resolve_payment_client_token,
+ resolve_payments,
+ resolve_payment_sources,
+)
from .types import Payment, PaymentSource
@@ -26,12 +30,13 @@ class PaymentQueries(graphene.ObjectType):
def resolve_payments(self, info, query=None, **_kwargs):
return resolve_payments(info, query)
+ @login_required
def resolve_payment_sources(self, info):
- return []
+ return resolve_payment_sources(info.context.user)
- def resolve_payment_client_token(self, _info, gateway=None):
- if _info.context.user.is_authenticated:
- return resolve_payment_client_token(gateway, user=_info.context.user)
+ def resolve_payment_client_token(self, info, gateway=None):
+ if info.context.user.is_authenticated:
+ return resolve_payment_client_token(gateway, user=info.context.user)
return resolve_payment_client_token(gateway)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 7f65a881a8..cf98d869f2 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -2,7 +2,7 @@ import json
import logging
from decimal import Decimal
from functools import wraps
-from typing import Dict
+from typing import Dict, List
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
@@ -42,6 +42,10 @@ REQUIRED_GATEWAY_KEYS = {
ALLOWED_GATEWAY_KINDS = {choices[0] for choices in TransactionKind.CHOICES}
+def list_enabled_gateways() -> List[str]:
+ return list(settings.CHECKOUT_PAYMENT_GATEWAYS.keys())
+
+
def get_gateway_operation_func(gateway, operation_type):
"""Return gateway method based on the operation type to be performed."""
if operation_type == OperationType.PROCESS_PAYMENT:
@@ -517,12 +521,13 @@ GATEWAYS_LABEL = "gateways"
def extract_id_for_payment_gateway(user, gateway):
+ key = gateway.strip().upper()
gateway_meta = user.get_private_meta(label=GATEWAYS_LABEL)
if not gateway_meta:
return None
- if gateway not in gateway_meta:
+ if key not in gateway_meta:
return None
- gateway_config = gateway_meta[gateway]
+ gateway_config = gateway_meta[key]
if "customer_id" not in gateway_config:
return None
return gateway_config["customer_id"]
@@ -530,6 +535,8 @@ def extract_id_for_payment_gateway(user, gateway):
def store_id_for_payment_gateway(user, gateway, customer_id):
user.store_private_meta(
- label=GATEWAYS_LABEL, key=gateway, value={"customer_id": customer_id}
+ label=GATEWAYS_LABEL,
+ key=gateway.strip().upper(),
+ value={"customer_id": customer_id},
)
user.save()
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index 79d94b9e7d..5116eaea68 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -12,12 +12,12 @@ from saleor.graphql.payment.enums import (
PaymentChargeStatusEnum,
PaymentGatewayEnum,
)
+from saleor.payment.interface import CustomerSource, CreditCardInfo, TokenConfig
+from saleor.payment.models import ChargeStatus, Payment, TransactionKind
from saleor.payment.utils import (
extract_id_for_payment_gateway,
store_id_for_payment_gateway,
)
-from saleor.payment.interface import TokenConfig
-from saleor.payment.models import ChargeStatus, Payment, TransactionKind
VOID_QUERY = """
mutation PaymentVoid($paymentId: ID!) {
@@ -472,7 +472,7 @@ def braintree_customer_id():
def test_store_payment_gateway_meta(customer_user, braintree_customer_id):
gateway_name = PaymentGatewayEnum.BRAINTREE.name
- META = {"gateways": {gateway_name: {"customer_id": braintree_customer_id}}}
+ META = {"gateways": {gateway_name.upper(): {"customer_id": braintree_customer_id}}}
store_id_for_payment_gateway(customer_user, gateway_name, braintree_customer_id)
assert customer_user.private_meta == META
customer_user.refresh_from_db()
@@ -495,7 +495,7 @@ def test_query_payment_client_token(mock_get_client_token, user_api_client):
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
- assert mock_get_client_token.called_once_with(PaymentGatewayEnum.BRAINTREE.name)
+ assert mock_get_client_token.assert_called_once_with("braintree")
token = content["data"]["paymentClientToken"]
assert token == example_token
@@ -507,9 +507,8 @@ def token_config_with_customer(braintree_customer_id):
@pytest.fixture
def set_braintree_customer_id(customer_user, braintree_customer_id):
- gateway_name = PaymentGatewayEnum.BRAINTREE.name
+ gateway_name = "braintree"
store_id_for_payment_gateway(customer_user, gateway_name, braintree_customer_id)
- customer_user.save()
return customer_user
@@ -521,20 +520,28 @@ def test_use_customer_id_from_meta_on_client_token_generation(
paymentClientToken(gateway: $gateway)
}
"""
- mock_get_client_token = mocker.patch(
+ TOKEN = "sample_token"
+ mocker.patch(
"saleor.graphql.payment.resolvers.gateway_get_client_token",
- return_value="sample_token",
+ return_value=TOKEN,
+ autospec=True,
)
variables = {"gateway": PaymentGatewayEnum.BRAINTREE.name}
response = user_api_client.post_graphql(query, variables)
- get_graphql_content(response)
- assert mock_get_client_token.called_once_with(
- PaymentGatewayEnum.BRAINTREE.name, token_config=token_config_with_customer
- )
+ content = get_graphql_content(response)
+ assert content["data"]["paymentClientToken"] == TOKEN
+
+
+def enable_braintree(settings):
+ settings.CHECKOUT_PAYMENT_GATEWAYS = {"braintree": None}
+ return settings
-def test_list_payment_sources(mocker, set_braintree_customer_id, user_api_client):
+def test_list_payment_sources(
+ mocker, enable_braintree, set_braintree_customer_id, user_api_client
+):
query = """
{
paymentStoredSources {
@@ -545,5 +552,24 @@ def test_list_payment_sources(mocker, set_braintree_customer_id, user_api_client
}
}
"""
+ card = CreditCardInfo(
+ last4="5678", exp_year=2020, exp_month=12, name_on_card="John Doe"
+ )
+ source = CustomerSource(id="test1", credit_card_info=card)
+ mock_get_source_list = mocker.patch(
+ "saleor.payment.gateways.braintree.list_client_sources",
+ return_value=[source],
+ autospec=True,
+ )
+
response = user_api_client.post_graphql(query)
- get_graphql_content(response)
+ assert mock_get_source_list.assert_called_once()
+
+ content = get_graphql_content(response)["data"]["paymentStoredSources"]
+ assert content is not None and len(content) == 1
+ assert content[0] == [
+ {
+ "gateway": PaymentGatewayEnum.BRAINTREE.name,
+ "credit_card": {"lastDigits": "5678"},
+ }
+ ]