Skip to content

Commit

Permalink
example project
Browse files Browse the repository at this point in the history
  • Loading branch information
nwolff committed Aug 3, 2019
1 parent 733ed72 commit d1bdcd8
Show file tree
Hide file tree
Showing 15 changed files with 275 additions and 143 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Run the migrations:
./manage.py migrate


Configure the CHECKOUT_PAYMENT_GATEWAYS and PAYMENT_GATEWAYS settings. See [tests/settings.py](tests/settings.py)
Configure the CHECKOUT_PAYMENT_GATEWAYS and PAYMENT_GATEWAYS settings. See [example settings.py](example_project/settings.py)

Development
-----------
Expand Down
File renamed without changes.
11 changes: 11 additions & 0 deletions example_project/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env python
import os
import sys


if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
113 changes: 113 additions & 0 deletions example_project/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# flake8: noqa

import os
import sys

abspath = lambda *p: os.path.abspath(os.path.join(*p))

PROJECT_ROOT = abspath(os.path.dirname(__file__))
PAYMENT_MODULE_PATH = abspath(PROJECT_ROOT, '..')
sys.path.insert(0, PAYMENT_MODULE_PATH)

DEBUG = True

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db'
},
}

SECRET_KEY = 'not_so_secret'

USE_TZ = True

# Use a fast hasher to speed up tests.
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.contenttypes',
'django_fsm',
'djmoney',
'tests',
'payment.apps.PaymentConfig',
]

MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')

STATICFILES_DIRS = [os.path.join(PROJECT_ROOT, 'project/static')]

ROOT_URLCONF = 'urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.request',
'django.template.context_processors.static',
'django.contrib.messages.context_processors.messages',
],
},
},
]

DUMMY = "dummy"
STRIPE = "stripe"

CHECKOUT_PAYMENT_GATEWAYS = {
DUMMY: "Dummy gateway",
STRIPE: "Stripe",
}

PAYMENT_GATEWAYS = {
DUMMY: {
"module": "payment.gateways.dummy",
"config": {
"auto_capture": True,
"connection_params": {},
"template_path": "payment/dummy.html",
},
},
STRIPE: {
"module": "payment.gateways.stripe",
"config": {
"auto_capture": True,
"template_path": "payment/stripe.html",
"connection_params": {
"public_key": os.environ.get("STRIPE_PUBLIC_KEY"),
"secret_key": os.environ.get("STRIPE_SECRET_KEY"),
"store_name": os.environ.get("STRIPE_STORE_NAME", "skioo shop"),
"store_image": os.environ.get("STRIPE_STORE_IMAGE", None),
"prefill": os.environ.get("STRIPE_PREFILL", True),
"remember_me": os.environ.get("STRIPE_REMEMBER_ME", False),
"locale": os.environ.get("STRIPE_LOCALE", "auto"),
"enable_billing_address": os.environ.get(
"STRIPE_ENABLE_BILLING_ADDRESS", False
),
"enable_shipping_address": os.environ.get(
"STRIPE_ENABLE_SHIPPING_ADDRESS", False
),
},
},
},
}
21 changes: 21 additions & 0 deletions example_project/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django.contrib import admin
from django.urls import path

from views.stripe import view_payment, checkout, elements_token, payment_intents_manual_flow, \
payment_intents_confirm_payment, capture

urlpatterns = [
path('admin/', admin.site.urls),

path('<payment_id>', view_payment, name='view_payment'),

path('<payment_id>/stripe/checkout', checkout, name='stripe_checkout'),
path('<payment_id>/stripe/elements_token', elements_token, name='stripe_elements_token'),

path('<payment_id>/stripe/payment_intents_manual_flow', payment_intents_manual_flow,
name='stripe_payment_intents_manual_flow'),
path('<payment_id>/stripe/payment_intents_confirm_payment', payment_intents_confirm_payment,
name='stripe_payment_intents_confirm_payment'),

path('<payment_id>/stripe/capture', capture, name='strip_capture'),
]
File renamed without changes.
115 changes: 1 addition & 114 deletions paymenttest/views/stripe.py → example_project/views/stripe.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from dataclasses import asdict
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
Expand All @@ -11,7 +10,7 @@
from payment import get_payment_gateway
from payment.gateways.stripe import get_amount_for_stripe, get_currency_for_stripe
from payment.models import Payment
from payment.utils import gateway_process_payment, create_payment_information, gateway_authorize, gateway_capture
from payment.utils import gateway_authorize, gateway_capture

logger = get_logger()

Expand All @@ -21,57 +20,13 @@ def view_payment(request: HttpRequest, payment_id: int) -> HttpResponse:
return TemplateResponse(request, 'paymenttest/stripe/operation_list.html', {'payment': payment})


def authorize_and_capture_old_checkout(request: HttpRequest, payment_id: int) -> HttpResponse:
return _pay(request, payment_id, True)


def authorize_old_checkout(request: HttpRequest, payment_id: int) -> HttpResponse:
return _pay(request, payment_id, False)


def capture(request: HttpRequest, payment_id: int) -> HttpResponse:
payment = get_object_or_404(Payment, id=payment_id)
capture_result = gateway_capture(payment=payment)
logger.info('paymenttest capture', payment=payment, capture_result=capture_result)
return redirect('paymenttest:view_payment', payment_id=payment_id)


def _pay(request: HttpRequest, payment_id: int, also_capture: bool) -> HttpResponse:
payment = get_object_or_404(Payment, id=payment_id)
payment_data = create_payment_information(payment)

logger.debug('paymenttest payment-data', **asdict(payment_data))

payment_gateway, gateway_config = get_payment_gateway(payment.gateway)

connection_params = gateway_config.connection_params
form = payment_gateway.create_form(
request.POST or None,
payment_information=payment_data,
connection_params=connection_params,
)
if form.is_valid():
try:
if also_capture:
logger.info('paymenttest gateway-process-payment', payment=payment)
gateway_process_payment(payment=payment, payment_token=form.get_payment_token())
else:
logger.info('paymenttest authorize', payment=payment)
gateway_authorize(payment=payment, payment_token=form.get_payment_token())
except Exception as exc:
form.add_error(None, str(exc))
else:
return redirect('paymenttest:view_payment', payment_id=payment.pk)

client_token = payment_gateway.get_client_token(connection_params=connection_params)
ctx = {
"form": form,
"payment": payment,
"client_token": client_token,
}
return TemplateResponse(request, gateway_config.template_path, ctx)


def checkout(request, payment_id: int) -> HttpResponse:
"""
Takes the user to the stripe checkout page.
Expand Down Expand Up @@ -100,74 +55,6 @@ def checkout(request, payment_id: int) -> HttpResponse:
return TemplateResponse(request, 'paymenttest/stripe/checkout.html', {'CHECKOUT_SESSION_ID': session.id})


@csrf_exempt
def authorize_old_checkout_ajax(request, payment_id: int) -> HttpResponse:
if request.method == 'GET':
payment_params_endpoint = reverse('paymenttest:payment_params', args=[payment_id])
return TemplateResponse(
request,
'paymenttest/stripe/old_checkout_ajax.html',
{'payment_params_endpoint': payment_params_endpoint})
elif request.method == 'POST':
payment = get_object_or_404(Payment, id=payment_id)
payment_data = create_payment_information(payment)
logger.debug('paymenttest payment-data', **asdict(payment_data))
payment_gateway, gateway_config = get_payment_gateway(payment.gateway)
connection_params = gateway_config.connection_params
form = payment_gateway.create_form(
request.POST,
payment_information=payment_data,
connection_params=connection_params)
if form.is_valid():
try:
logger.info('paymenttest authorize', payment=payment)
gateway_authorize(payment=payment, payment_token=form.get_payment_token())
except Exception as exc:
form.add_error(None, str(exc))
logger.error('paymenttest authorize', exc_info=exc)
return HttpResponse('Error authorizing {}: {}'.format(payment_id, exc))
else:
return redirect('paymenttest:view_payment', payment_id=payment.pk)


@api_view(['GET'])
def payment_params(request, payment_id: int) -> HttpResponse:
"""
Returns a data representation of the parameters that are needed to initiate a stripe payment.
This is not part of the gateway abstraction, so we implement it directly using the stripe API
"""
payment = get_object_or_404(Payment, id=payment_id)

_, gateway_config = get_payment_gateway(payment.gateway)
gateway_params = gateway_config.connection_params

amount = payment.total.amount
currency = payment.total.currency.code

stripe_payment_params = {
"key": gateway_params.get("public_key"),
"amount": get_amount_for_stripe(amount, currency),
"name": gateway_params.get("store_name"),
"currency": currency,
"locale": "auto",
"allow-remember-me": "false",
"billing-address": "false",
"zip-code": "false",
"email": payment.customer_email
}

image = gateway_params.get("store_image")
if image:
payment_params["image"] = image

result = {
"gateway": payment.gateway,
"params": stripe_payment_params,
}

return JsonResponse(result)


@csrf_exempt
def elements_token(request, payment_id: int) -> HttpResponse:
payment = get_object_or_404(Payment, id=payment_id)
Expand Down
Loading

0 comments on commit d1bdcd8

Please sign in to comment.