lfs-paypal 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lfs_paypal/__init__.py +2 -0
- lfs_paypal/admin.py +28 -0
- lfs_paypal/apps.py +5 -0
- lfs_paypal/migrations/0001_initial.py +102 -0
- lfs_paypal/migrations/0002_alter_paypalpaymententry_status.py +28 -0
- lfs_paypal/migrations/__init__.py +0 -0
- lfs_paypal/models.py +43 -0
- lfs_paypal/processor.py +118 -0
- lfs_paypal/templates/lfs_paypal/payment_cancelled.html +7 -0
- lfs_paypal/templates/lfs_paypal/payment_error.html +7 -0
- lfs_paypal/urls.py +10 -0
- lfs_paypal/utils.py +37 -0
- lfs_paypal/views.py +150 -0
- lfs_paypal-2.0.0.dist-info/METADATA +69 -0
- lfs_paypal-2.0.0.dist-info/RECORD +18 -0
- lfs_paypal-2.0.0.dist-info/WHEEL +5 -0
- lfs_paypal-2.0.0.dist-info/licenses/LICENSE.txt +27 -0
- lfs_paypal-2.0.0.dist-info/top_level.txt +1 -0
lfs_paypal/__init__.py
ADDED
lfs_paypal/admin.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from django.contrib import admin
|
|
2
|
+
from .models import PayPalPayment, PayPalPaymentEntry
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class PayPalPaymentEntryInline(admin.TabularInline):
|
|
6
|
+
model = PayPalPaymentEntry
|
|
7
|
+
extra = 0
|
|
8
|
+
fields = ("status", "created_at_with_seconds")
|
|
9
|
+
readonly_fields = ("status", "created_at_with_seconds")
|
|
10
|
+
can_delete = False
|
|
11
|
+
|
|
12
|
+
def has_add_permission(self, request, obj=None):
|
|
13
|
+
return False
|
|
14
|
+
|
|
15
|
+
def created_at_with_seconds(self, obj):
|
|
16
|
+
return obj.created_at.strftime("%d.%m.%Y %H:%M:%S")
|
|
17
|
+
|
|
18
|
+
created_at_with_seconds.short_description = "Created At"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@admin.register(PayPalPayment)
|
|
22
|
+
class PayPalPaymentAdmin(admin.ModelAdmin):
|
|
23
|
+
list_display = ("payment_id", "order", "amount", "currency", "created_at", "updated_at")
|
|
24
|
+
list_filter = ("currency", "created_at")
|
|
25
|
+
search_fields = ("payment_id", "payer_id", "order__id")
|
|
26
|
+
date_hierarchy = "created_at"
|
|
27
|
+
fields = readonly_fields = ("payment_id", "order", "amount", "currency", "created_at", "updated_at")
|
|
28
|
+
inlines = [PayPalPaymentEntryInline]
|
lfs_paypal/apps.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Generated by Django 5.2.1 on 2025-05-26 08:37
|
|
2
|
+
|
|
3
|
+
import django.db.models.deletion
|
|
4
|
+
from django.db import migrations, models
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Migration(migrations.Migration):
|
|
8
|
+
|
|
9
|
+
initial = True
|
|
10
|
+
|
|
11
|
+
dependencies = [
|
|
12
|
+
("order", "0005_alter_order_state"),
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
operations = [
|
|
16
|
+
migrations.CreateModel(
|
|
17
|
+
name="PayPalPayment",
|
|
18
|
+
fields=[
|
|
19
|
+
(
|
|
20
|
+
"id",
|
|
21
|
+
models.AutoField(
|
|
22
|
+
auto_created=True,
|
|
23
|
+
primary_key=True,
|
|
24
|
+
serialize=False,
|
|
25
|
+
verbose_name="ID",
|
|
26
|
+
),
|
|
27
|
+
),
|
|
28
|
+
(
|
|
29
|
+
"temp_order_id",
|
|
30
|
+
models.CharField(
|
|
31
|
+
default="",
|
|
32
|
+
help_text="PayPal payment ID",
|
|
33
|
+
max_length=50,
|
|
34
|
+
unique=True,
|
|
35
|
+
),
|
|
36
|
+
),
|
|
37
|
+
(
|
|
38
|
+
"payment_id",
|
|
39
|
+
models.CharField(
|
|
40
|
+
help_text="PayPal payment ID", max_length=255, unique=True
|
|
41
|
+
),
|
|
42
|
+
),
|
|
43
|
+
(
|
|
44
|
+
"payer_id",
|
|
45
|
+
models.CharField(
|
|
46
|
+
blank=True,
|
|
47
|
+
help_text="PayPal payer ID",
|
|
48
|
+
max_length=255,
|
|
49
|
+
null=True,
|
|
50
|
+
),
|
|
51
|
+
),
|
|
52
|
+
("amount", models.DecimalField(decimal_places=2, max_digits=10)),
|
|
53
|
+
("currency", models.CharField(default="EUR", max_length=3)),
|
|
54
|
+
("created_at", models.DateTimeField(auto_now_add=True)),
|
|
55
|
+
("updated_at", models.DateTimeField(auto_now=True)),
|
|
56
|
+
(
|
|
57
|
+
"order",
|
|
58
|
+
models.ForeignKey(
|
|
59
|
+
blank=True,
|
|
60
|
+
null=True,
|
|
61
|
+
on_delete=django.db.models.deletion.CASCADE,
|
|
62
|
+
to="order.order",
|
|
63
|
+
),
|
|
64
|
+
),
|
|
65
|
+
],
|
|
66
|
+
),
|
|
67
|
+
migrations.CreateModel(
|
|
68
|
+
name="PayPalPaymentEntry",
|
|
69
|
+
fields=[
|
|
70
|
+
(
|
|
71
|
+
"id",
|
|
72
|
+
models.AutoField(
|
|
73
|
+
auto_created=True,
|
|
74
|
+
primary_key=True,
|
|
75
|
+
serialize=False,
|
|
76
|
+
verbose_name="ID",
|
|
77
|
+
),
|
|
78
|
+
),
|
|
79
|
+
(
|
|
80
|
+
"status",
|
|
81
|
+
models.CharField(
|
|
82
|
+
choices=[
|
|
83
|
+
("pending", "Pending"),
|
|
84
|
+
("completed", "Completed"),
|
|
85
|
+
("failed", "Failed"),
|
|
86
|
+
("cancelled", "Cancelled"),
|
|
87
|
+
],
|
|
88
|
+
default="pending",
|
|
89
|
+
max_length=20,
|
|
90
|
+
),
|
|
91
|
+
),
|
|
92
|
+
("created_at", models.DateTimeField(auto_now_add=True)),
|
|
93
|
+
(
|
|
94
|
+
"payment",
|
|
95
|
+
models.ForeignKey(
|
|
96
|
+
on_delete=django.db.models.deletion.CASCADE,
|
|
97
|
+
to="lfs_paypal.paypalpayment",
|
|
98
|
+
),
|
|
99
|
+
),
|
|
100
|
+
],
|
|
101
|
+
),
|
|
102
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Generated by Django 5.1.5 on 2025-08-08 05:53
|
|
2
|
+
|
|
3
|
+
from django.db import migrations, models
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Migration(migrations.Migration):
|
|
7
|
+
|
|
8
|
+
dependencies = [
|
|
9
|
+
("lfs_paypal", "0001_initial"),
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
operations = [
|
|
13
|
+
migrations.AlterField(
|
|
14
|
+
model_name="paypalpaymententry",
|
|
15
|
+
name="status",
|
|
16
|
+
field=models.CharField(
|
|
17
|
+
choices=[
|
|
18
|
+
("pending", "Pending"),
|
|
19
|
+
("completed", "Completed"),
|
|
20
|
+
("approved", "Approved"),
|
|
21
|
+
("failed", "Failed"),
|
|
22
|
+
("cancelled", "Cancelled"),
|
|
23
|
+
],
|
|
24
|
+
default="pending",
|
|
25
|
+
max_length=20,
|
|
26
|
+
),
|
|
27
|
+
),
|
|
28
|
+
]
|
|
File without changes
|
lfs_paypal/models.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from django.db import models
|
|
2
|
+
|
|
3
|
+
from lfs.order.models import Order
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PayPalPayment(models.Model):
|
|
7
|
+
order = models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True)
|
|
8
|
+
temp_order_id = models.CharField(max_length=50, unique=True, help_text="PayPal payment ID", default="")
|
|
9
|
+
payment_id = models.CharField(max_length=255, unique=True, help_text="PayPal payment ID")
|
|
10
|
+
payer_id = models.CharField(max_length=255, null=True, blank=True, help_text="PayPal payer ID")
|
|
11
|
+
amount = models.DecimalField(max_digits=10, decimal_places=2)
|
|
12
|
+
currency = models.CharField(max_length=3, default="EUR")
|
|
13
|
+
created_at = models.DateTimeField(auto_now_add=True)
|
|
14
|
+
updated_at = models.DateTimeField(auto_now=True)
|
|
15
|
+
|
|
16
|
+
def __str__(self):
|
|
17
|
+
return f"Payment {self.payment_id} for Order {self.order_id}"
|
|
18
|
+
|
|
19
|
+
def add_entry(self, status):
|
|
20
|
+
PayPalPaymentEntry.objects.create(payment=self, status=status)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PayPalPaymentEntry(models.Model):
|
|
24
|
+
PENDING = "pending"
|
|
25
|
+
APPROVED = "approved"
|
|
26
|
+
COMPLETED = "completed"
|
|
27
|
+
FAILED = "failed"
|
|
28
|
+
CANCELLED = "cancelled"
|
|
29
|
+
|
|
30
|
+
STATUS_CHOICES = [
|
|
31
|
+
(PENDING, "Pending"),
|
|
32
|
+
(COMPLETED, "Completed"),
|
|
33
|
+
(APPROVED, "Approved"),
|
|
34
|
+
(FAILED, "Failed"),
|
|
35
|
+
(CANCELLED, "Cancelled"),
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
payment = models.ForeignKey(PayPalPayment, on_delete=models.CASCADE)
|
|
39
|
+
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=PENDING)
|
|
40
|
+
created_at = models.DateTimeField(auto_now_add=True)
|
|
41
|
+
|
|
42
|
+
def __str__(self):
|
|
43
|
+
return ""
|
lfs_paypal/processor.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import uuid
|
|
3
|
+
from decimal import Decimal, ROUND_HALF_UP
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
from django.shortcuts import redirect, render
|
|
7
|
+
from django.urls import reverse
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from lfs.customer import utils as customer_utils
|
|
12
|
+
from lfs.plugins import PaymentMethodProcessor
|
|
13
|
+
from lfs.plugins import PM_ORDER_ACCEPTED
|
|
14
|
+
from lfs_paypal.models import PayPalPayment, PayPalPaymentEntry
|
|
15
|
+
from lfs_paypal.utils import PAYPAL_ORDERS_API, get_paypal_auth_token
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# django paypal imports
|
|
19
|
+
logger = logging.getLogger("lfs.paypal")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PayPalProcessor(PaymentMethodProcessor):
|
|
23
|
+
|
|
24
|
+
def get_create_order_time(self):
|
|
25
|
+
return PM_ORDER_ACCEPTED
|
|
26
|
+
|
|
27
|
+
def process(self):
|
|
28
|
+
"""
|
|
29
|
+
Initialize the payment.
|
|
30
|
+
"""
|
|
31
|
+
customer = customer_utils.get_customer(self.request)
|
|
32
|
+
cart_price_gross = self.cart.get_total_price_gross(self.request)
|
|
33
|
+
|
|
34
|
+
order_amount = Decimal(cart_price_gross)
|
|
35
|
+
order_amount = order_amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
36
|
+
|
|
37
|
+
# Get access token
|
|
38
|
+
access_token = get_paypal_auth_token()
|
|
39
|
+
if not access_token:
|
|
40
|
+
return render(
|
|
41
|
+
self.request,
|
|
42
|
+
"lfs_paypal/payment_error.html",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
temp_order_id = str(uuid.uuid4())
|
|
46
|
+
|
|
47
|
+
headers = {
|
|
48
|
+
"Authorization": f"Bearer {access_token}",
|
|
49
|
+
"Content-Type": "application/json",
|
|
50
|
+
"Prefer": "return=representation",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
order_data = {
|
|
54
|
+
"intent": "CAPTURE",
|
|
55
|
+
"purchase_units": [
|
|
56
|
+
{
|
|
57
|
+
"reference_id": temp_order_id,
|
|
58
|
+
"description": f"Payment for Order #{temp_order_id}",
|
|
59
|
+
"amount": {
|
|
60
|
+
"currency_code": "EUR",
|
|
61
|
+
"value": str(order_amount),
|
|
62
|
+
"breakdown": {"item_total": {"currency_code": "EUR", "value": str(order_amount)}},
|
|
63
|
+
},
|
|
64
|
+
"items": [
|
|
65
|
+
{
|
|
66
|
+
"name": f"Order #{temp_order_id}",
|
|
67
|
+
"unit_amount": {"currency_code": "EUR", "value": str(order_amount)},
|
|
68
|
+
"quantity": "1",
|
|
69
|
+
"category": "PHYSICAL_GOODS",
|
|
70
|
+
}
|
|
71
|
+
],
|
|
72
|
+
"shipping": {
|
|
73
|
+
"name": {
|
|
74
|
+
"full_name": f"{customer.selected_shipping_address.firstname} {customer.selected_shipping_address.lastname}"
|
|
75
|
+
},
|
|
76
|
+
"address": {
|
|
77
|
+
"address_line_1": customer.selected_shipping_address.line1,
|
|
78
|
+
"admin_area_2": customer.selected_shipping_address.city,
|
|
79
|
+
"country_code": customer.selected_shipping_address.country.code,
|
|
80
|
+
"postal_code": customer.selected_shipping_address.zip_code,
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
],
|
|
85
|
+
"application_context": {
|
|
86
|
+
"shipping_preference": "SET_PROVIDED_ADDRESS",
|
|
87
|
+
"return_url": self.request.build_absolute_uri(reverse("paypal:capture_payment")),
|
|
88
|
+
"cancel_url": self.request.build_absolute_uri(reverse("paypal:payment_cancelled")),
|
|
89
|
+
"user_action": "PAY_NOW",
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
response = requests.post(PAYPAL_ORDERS_API, headers=headers, json=order_data)
|
|
94
|
+
|
|
95
|
+
if response.status_code == 201:
|
|
96
|
+
order_response = response.json()
|
|
97
|
+
order_id_paypal = order_response["id"]
|
|
98
|
+
|
|
99
|
+
# Save payment info to database
|
|
100
|
+
paypal_payment = PayPalPayment.objects.create(
|
|
101
|
+
temp_order_id=temp_order_id,
|
|
102
|
+
payment_id=order_id_paypal,
|
|
103
|
+
amount=order_amount,
|
|
104
|
+
currency="EUR",
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
paypal_payment.add_entry(status=PayPalPaymentEntry.PENDING)
|
|
108
|
+
# Find approval URL and redirect
|
|
109
|
+
for link in order_response["links"]:
|
|
110
|
+
if link["rel"] == "approve":
|
|
111
|
+
return redirect(link["href"])
|
|
112
|
+
|
|
113
|
+
# Order creation failed
|
|
114
|
+
logger.error(f"PayPal order creation failed: {response.text}")
|
|
115
|
+
return render(
|
|
116
|
+
self.request,
|
|
117
|
+
"lfs_paypal/payment_error.html",
|
|
118
|
+
)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{% extends "lfs/base.html" %}
|
|
2
|
+
|
|
3
|
+
{% block content %}
|
|
4
|
+
<h1>Zahlung abgebrochen</h1>
|
|
5
|
+
<p>Sie haben die Zahlung abgebrochen. Wenn Sie weitere Fragen haben, wenden Sie sich bitte an uns.</p>
|
|
6
|
+
<p><a href="{% url 'lfs_checkout' %}" class="btn">Zurück zur Kasse</a></p>
|
|
7
|
+
{% endblock %}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{% extends "lfs/base.html" %}
|
|
2
|
+
|
|
3
|
+
{% block content %}
|
|
4
|
+
<h1>Es ist ein Fehler aufgetreten</h1>
|
|
5
|
+
<p>Bei der Verarbeitung Ihrer Zahlung ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.</p>
|
|
6
|
+
<p><a href="{% url 'lfs_checkout' %}" class="btn">Zurück zur Kasse</a></p>
|
|
7
|
+
{% endblock %}
|
lfs_paypal/urls.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from django.urls import path
|
|
2
|
+
from . import views
|
|
3
|
+
|
|
4
|
+
app_name = "paypal"
|
|
5
|
+
|
|
6
|
+
urlpatterns = [
|
|
7
|
+
path("capture-payment/", views.capture_payment, name="capture_payment"),
|
|
8
|
+
path("payment-cancelled/", views.payment_cancelled, name="payment_cancelled"),
|
|
9
|
+
path("webhook/", views.paypal_webhook, name="paypal_webhook"),
|
|
10
|
+
]
|
lfs_paypal/utils.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import logging
|
|
3
|
+
from django.conf import settings
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
PAYPAL_API_BASE = (
|
|
7
|
+
"https://api-m.sandbox.paypal.com" if settings.PAYPAL_MODE == "sandbox" else "https://api-m.paypal.com"
|
|
8
|
+
)
|
|
9
|
+
PAYPAL_OAUTH_API = f"{PAYPAL_API_BASE}/v1/oauth2/token"
|
|
10
|
+
PAYPAL_ORDERS_API = f"{PAYPAL_API_BASE}/v2/checkout/orders"
|
|
11
|
+
PAYPAL_ORDER_CAPTURE_API = f"{PAYPAL_API_BASE}/v2/checkout/orders/{{}}/capture"
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("lfs.paypal")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_paypal_auth_token():
|
|
17
|
+
"""
|
|
18
|
+
Get PayPal OAuth access token
|
|
19
|
+
"""
|
|
20
|
+
auth_string = f"{settings.PAYPAL_CLIENT_ID}:{settings.PAYPAL_CLIENT_SECRET}"
|
|
21
|
+
auth_bytes = auth_string.encode("ascii")
|
|
22
|
+
auth_base64 = base64.b64encode(auth_bytes).decode("ascii")
|
|
23
|
+
|
|
24
|
+
headers = {
|
|
25
|
+
"Authorization": f"Basic {auth_base64}",
|
|
26
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
data = {"grant_type": "client_credentials"}
|
|
30
|
+
|
|
31
|
+
response = requests.post(PAYPAL_OAUTH_API, headers=headers, data=data)
|
|
32
|
+
|
|
33
|
+
if response.status_code == 200:
|
|
34
|
+
return response.json().get("access_token")
|
|
35
|
+
else:
|
|
36
|
+
logger.error(f"Failed to get PayPal auth token: {response.text}")
|
|
37
|
+
return None
|
lfs_paypal/views.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from django.http import HttpResponse
|
|
5
|
+
from django.shortcuts import redirect, render
|
|
6
|
+
from django.urls import reverse
|
|
7
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
from lfs.cart import utils as cart_utils
|
|
11
|
+
from lfs.core.signals import order_paid, order_submitted
|
|
12
|
+
from lfs.order.settings import PAID
|
|
13
|
+
from lfs.order.utils import add_order
|
|
14
|
+
from lfs_paypal.models import PayPalPayment, PayPalPaymentEntry
|
|
15
|
+
from lfs_paypal.utils import PAYPAL_ORDER_CAPTURE_API, get_paypal_auth_token
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("lfs.paypal")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@csrf_exempt
|
|
21
|
+
def capture_payment(request):
|
|
22
|
+
"""
|
|
23
|
+
Capture the PayPal payment after user approval using v2 API. This is where PayPal redirects after the user
|
|
24
|
+
approves the payment.
|
|
25
|
+
|
|
26
|
+
The url vor this view is passed in the return_url parameter of the order creation request, see processor.py
|
|
27
|
+
-> application_context
|
|
28
|
+
"""
|
|
29
|
+
token = request.GET.get("token")
|
|
30
|
+
|
|
31
|
+
# Get the payment from database - still using payment_id field to store the order ID
|
|
32
|
+
try:
|
|
33
|
+
paypal_payment = PayPalPayment.objects.get(payment_id=token)
|
|
34
|
+
except PayPalPayment.DoesNotExist:
|
|
35
|
+
logger.error(f"Payment not found for token: {token}")
|
|
36
|
+
return render(request, "lfs_paypal/payment_error.html", {"error": "Payment not found."})
|
|
37
|
+
|
|
38
|
+
# Get access token
|
|
39
|
+
access_token = get_paypal_auth_token()
|
|
40
|
+
if not access_token:
|
|
41
|
+
return render(
|
|
42
|
+
request, "lfs_paypal/payment_error.html", {"error": "Could not authenticate with PayPal. Please try again."}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# Capture payment using v2 API
|
|
46
|
+
headers = {
|
|
47
|
+
"Authorization": f"Bearer {access_token}",
|
|
48
|
+
"Content-Type": "application/json",
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
capture_url = PAYPAL_ORDER_CAPTURE_API.format(token)
|
|
52
|
+
response = requests.post(capture_url, headers=headers, json={})
|
|
53
|
+
|
|
54
|
+
if response.status_code == 201:
|
|
55
|
+
# For any reasons paypal calls this view two times
|
|
56
|
+
cart = cart_utils.get_cart(request)
|
|
57
|
+
if cart is None:
|
|
58
|
+
return redirect(reverse("lfs_thank_you"))
|
|
59
|
+
|
|
60
|
+
capture_response = response.json()
|
|
61
|
+
if capture_response["status"] == "COMPLETED":
|
|
62
|
+
logger.info(f"Creating order for payment {token}")
|
|
63
|
+
order = add_order(request)
|
|
64
|
+
logger.info(f"Order created: {order.id}")
|
|
65
|
+
order.state = PAID
|
|
66
|
+
order.save()
|
|
67
|
+
|
|
68
|
+
# Notify the system
|
|
69
|
+
order_submitted.send(sender=order, request=request)
|
|
70
|
+
order_paid.send(sender=order, request=request)
|
|
71
|
+
|
|
72
|
+
# Save payment info to database
|
|
73
|
+
paypal_payment.order = order
|
|
74
|
+
payer_id = capture_response.get("payer", {}).get("payer_id", "")
|
|
75
|
+
if payer_id:
|
|
76
|
+
paypal_payment.payer_id = payer_id
|
|
77
|
+
paypal_payment.save()
|
|
78
|
+
paypal_payment.add_entry(PayPalPaymentEntry.COMPLETED)
|
|
79
|
+
|
|
80
|
+
return redirect(reverse("lfs_thank_you"))
|
|
81
|
+
|
|
82
|
+
# Payment capture failed
|
|
83
|
+
paypal_payment.add_entry(PayPalPaymentEntry.FAILED)
|
|
84
|
+
|
|
85
|
+
logger.error(f"PayPal payment capture failed: {response.text}")
|
|
86
|
+
return render(request, "lfs_paypal/payment_error.html", {"error": "Payment failed. Please try again."})
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def payment_cancelled(request):
|
|
90
|
+
"""
|
|
91
|
+
Display payment cancelled page.
|
|
92
|
+
This is designed to be shown in a popup window that will
|
|
93
|
+
communicate with the parent window and close itself.
|
|
94
|
+
"""
|
|
95
|
+
return render(request, "lfs_paypal/payment_cancelled.html")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@csrf_exempt
|
|
99
|
+
def paypal_webhook(request):
|
|
100
|
+
"""
|
|
101
|
+
Webhook for PayPal notifications.
|
|
102
|
+
Updated to support both v1 and v2 event types.
|
|
103
|
+
"""
|
|
104
|
+
logger.info(f"PayPal webhook received: {request.body}")
|
|
105
|
+
if request.method == "POST":
|
|
106
|
+
try:
|
|
107
|
+
# Verify webhook
|
|
108
|
+
webhook_data = json.loads(request.body.decode("utf-8"))
|
|
109
|
+
event_type = webhook_data.get("event_type")
|
|
110
|
+
resource = webhook_data.get("resource", {})
|
|
111
|
+
|
|
112
|
+
# Process based on event type
|
|
113
|
+
# v1 API event
|
|
114
|
+
if event_type == "PAYMENT.SALE.COMPLETED":
|
|
115
|
+
payment_id = resource.get("parent_payment")
|
|
116
|
+
if payment_id:
|
|
117
|
+
try:
|
|
118
|
+
payment = PayPalPayment.objects.get(payment_id=payment_id)
|
|
119
|
+
payment.add_entry(PayPalPaymentEntry.COMPLETED)
|
|
120
|
+
logger.info(f"Payment {payment_id} confirmed via webhook (v1)")
|
|
121
|
+
except PayPalPayment.DoesNotExist:
|
|
122
|
+
logger.error(f"Payment not found in webhook: {payment_id}")
|
|
123
|
+
|
|
124
|
+
# v2 API events
|
|
125
|
+
elif event_type == "CHECKOUT.ORDER.APPROVED":
|
|
126
|
+
order_id = resource.get("id")
|
|
127
|
+
if order_id:
|
|
128
|
+
try:
|
|
129
|
+
payment = PayPalPayment.objects.get(payment_id=order_id)
|
|
130
|
+
payment.add_entry(PayPalPaymentEntry.APPROVED)
|
|
131
|
+
logger.info(f"Order {order_id} approved via webhook (v2)")
|
|
132
|
+
except PayPalPayment.DoesNotExist:
|
|
133
|
+
logger.error(f"Order not found in webhook: {order_id}")
|
|
134
|
+
|
|
135
|
+
elif event_type == "CHECKOUT.ORDER.COMPLETED":
|
|
136
|
+
order_id = resource.get("id")
|
|
137
|
+
if order_id:
|
|
138
|
+
try:
|
|
139
|
+
payment = PayPalPayment.objects.get(payment_id=order_id)
|
|
140
|
+
payment.add_entry(PayPalPaymentEntry.COMPLETED)
|
|
141
|
+
logger.info(f"Order {order_id} completed via webhook (v2)")
|
|
142
|
+
except PayPalPayment.DoesNotExist:
|
|
143
|
+
logger.error(f"Order not found in webhook: {order_id}")
|
|
144
|
+
|
|
145
|
+
return HttpResponse(status=200)
|
|
146
|
+
except Exception as e:
|
|
147
|
+
logger.error(f"Webhook error: {str(e)}")
|
|
148
|
+
return HttpResponse(status=500)
|
|
149
|
+
|
|
150
|
+
return HttpResponse(status=400)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lfs-paypal
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Integration of PayPal into LFS
|
|
5
|
+
Author: Kai Diefenbach
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Project-URL: Source, https://github.com/diefenbach/lfs-paypal
|
|
8
|
+
Keywords: django,e-commerce,online-shop,paypal
|
|
9
|
+
Classifier: Environment :: Web Environment
|
|
10
|
+
Classifier: Framework :: Django
|
|
11
|
+
Classifier: Framework :: Django :: 5.2
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Requires-Python: >=3.12
|
|
15
|
+
Description-Content-Type: text/plain
|
|
16
|
+
License-File: LICENSE.txt
|
|
17
|
+
Requires-Dist: Django<6,>=5.2
|
|
18
|
+
Requires-Dist: requests<3,>=2.32
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
What is it?
|
|
22
|
+
===========
|
|
23
|
+
|
|
24
|
+
lfs_paypal is the integration of PayPal into `LFS`_. `LFS`_ is an online shop
|
|
25
|
+
based on Django.
|
|
26
|
+
|
|
27
|
+
1.4.1 (2017-03-09)
|
|
28
|
+
==================
|
|
29
|
+
* Add data migrations for new processor place
|
|
30
|
+
|
|
31
|
+
1.4 (2017-02-19)
|
|
32
|
+
================
|
|
33
|
+
* Add Django 1.10 support
|
|
34
|
+
|
|
35
|
+
1.3 (2015-04-24)
|
|
36
|
+
================
|
|
37
|
+
* Fixes tests
|
|
38
|
+
* Changes order field to OneToOneField
|
|
39
|
+
* Removes app_label
|
|
40
|
+
* Adds initial migrations
|
|
41
|
+
|
|
42
|
+
1.2 (2014-06-11)
|
|
43
|
+
================
|
|
44
|
+
* Removes django-paypal from install_requires
|
|
45
|
+
|
|
46
|
+
1.1 (2014-06-08)
|
|
47
|
+
================
|
|
48
|
+
* Adds Django 1.6 suppport
|
|
49
|
+
|
|
50
|
+
1.0
|
|
51
|
+
===
|
|
52
|
+
Initial release
|
|
53
|
+
|
|
54
|
+
.. _`LFS`: http://pypi.python.org/pypi/django-lfs
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
How it works
|
|
58
|
+
############
|
|
59
|
+
|
|
60
|
+
1. When PayPal is selected as the payment method, the `PayPalProcessor.process()` method is invoked
|
|
61
|
+
2. This method obtains an OAuth access token from the PayPal API via `get_paypal_auth_token()`
|
|
62
|
+
3. Using this access token, a payment order is created by sending a POST request to `PAYPAL_ORDERS_API`
|
|
63
|
+
4. Upon receiving a 201 (Created) HTTP status code, a `PayPalPayment` object is persisted in the database with the PayPal order ID
|
|
64
|
+
5. The user is then redirected to the PayPal approval URL to authenticate and authorize the payment
|
|
65
|
+
6. After successful authorization, PayPal redirects the user to the `capture_payment` view (specified in the `return_url` parameter during order creation, see 3. above)
|
|
66
|
+
7. The `capture_payment` view retrieves the PayPal order ID from the request parameters, fetches the corresponding `PayPalPayment` record, and generates a new OAuth token
|
|
67
|
+
8. The payment is then captured by sending a POST request to `PAYPAL_ORDER_CAPTURE_API`
|
|
68
|
+
9. If the response status is "COMPLETED", an order is created in the LFS system, associated with the PayPal payment, and the user is redirected to the thank you page
|
|
69
|
+
10. After successful payment capture, PayPal sends a webhook event to the URL configured in the PayPal Developer Dashboard.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
lfs_paypal/__init__.py,sha256=YEGeOlfT0V4UMqczhsZX_J-9K_lpmy0iCFgJizu29g4,80
|
|
2
|
+
lfs_paypal/admin.py,sha256=LNvbbokl2wCJlwDHqOZOhJWZn-7vz6497vNqe4Wmo10,1018
|
|
3
|
+
lfs_paypal/apps.py,sha256=u6J9iPUPeuIQdCLFNT_W8qT7xtiDFBGgX4Intj6j-4M,97
|
|
4
|
+
lfs_paypal/models.py,sha256=bVzFro4YkuzCWEv7eW6iJLmyu9-6GtsXpmNpwSoQscs,1543
|
|
5
|
+
lfs_paypal/processor.py,sha256=NKm40MstK97qR7PfSborfkZyIYpFZ1Lfa3NhKjWRX_U,4329
|
|
6
|
+
lfs_paypal/urls.py,sha256=hAy-GYX2n2BVv_JZJapydA_ZpPEYu83oM6HKzkdSEBI,316
|
|
7
|
+
lfs_paypal/utils.py,sha256=fuQHcj3zvaCugqA-tt0J3uN6PTpB6BcKnJgIjpBPATM,1167
|
|
8
|
+
lfs_paypal/views.py,sha256=0jMOERX6INNUyyze1d6fk2cihZd2KVBuDo2T8wmP0SI,5831
|
|
9
|
+
lfs_paypal/migrations/0001_initial.py,sha256=cAmbsp10cAZ5d3TSDfsnFOmalNmnLatJwKFYspeWjOo,3334
|
|
10
|
+
lfs_paypal/migrations/0002_alter_paypalpaymententry_status.py,sha256=DKnA_dhDp6WnX2YZS1n93NvgtGfscU8vsUrtacJdBAo,729
|
|
11
|
+
lfs_paypal/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
lfs_paypal/templates/lfs_paypal/payment_cancelled.html,sha256=_34rWg9fn9suivM24ppbj-0sRkY2U0kNgdcOcbCXybk,286
|
|
13
|
+
lfs_paypal/templates/lfs_paypal/payment_error.html,sha256=LcKXiR2I-ULwoFYMk12B8bytpWQ8Y9b9K8FlSlJdywE,294
|
|
14
|
+
lfs_paypal-2.0.0.dist-info/licenses/LICENSE.txt,sha256=tWN6g6ZG_bOuUf3uE59p2wEFJJlR889CYAX4PqImFyY,1523
|
|
15
|
+
lfs_paypal-2.0.0.dist-info/METADATA,sha256=Pr99N9dLH8jZZPRKkGbjpI5HVJ12dZMGO3kDwff4FRU,2537
|
|
16
|
+
lfs_paypal-2.0.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
|
17
|
+
lfs_paypal-2.0.0.dist-info/top_level.txt,sha256=U3gskxKdsxvKlM0Lkcr6J08PnKBQijO-J9m8twCR1bE,11
|
|
18
|
+
lfs_paypal-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright (c) 2012, Kai Diefenbach - IQ++
|
|
2
|
+
All rights reserved.
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without
|
|
5
|
+
modification, are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
8
|
+
this list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
* Redistributions in binary form must reproduce the above copyright
|
|
11
|
+
notice, this list of conditions and the following disclaimer in the
|
|
12
|
+
documentation and/or other materials provided with the distribution.
|
|
13
|
+
|
|
14
|
+
* Neither the name of the author nor the names of other contributors may
|
|
15
|
+
be used to endorse or promote products derived from this software
|
|
16
|
+
without specific prior written permission.
|
|
17
|
+
|
|
18
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
19
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
20
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
22
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
23
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
24
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
25
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
26
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
lfs_paypal
|