Skip to content

Commit

Permalink
Update payment.py
Browse files Browse the repository at this point in the history
added support to django-shop==0.11 and angular 2.0
(i find errors in the last pull request)
  • Loading branch information
SasoriOlkof authored Jan 29, 2018
1 parent 96524a6 commit c5fb166
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions shop_paypal/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,24 @@
import json
import paypalrestsdk
import warnings
from decimal import Decimal
from distutils.version import LooseVersion

from django.conf import settings
from django.conf.urls import url
from django.core.serializers.json import DjangoJSONEncoder
from django.core.urlresolvers import resolve, reverse
from django.core.exceptions import ImproperlyConfigured
from django.http.response import HttpResponseRedirect, HttpResponseBadRequest
from django.urls import resolve, reverse, NoReverseMatch
from django.utils.translation import ugettext_lazy as _

from cms.models import Page

from django_fsm import transition

from shop import __version__ as SHOP_VERSION
from shop.models.cart import CartModel
from shop.models.order import BaseOrder, OrderModel, OrderPayment
from shop.money import MoneyMaker
from shop.payment.base import PaymentProvider
from django_fsm import transition


class PayPalPayment(PaymentProvider):
Expand Down Expand Up @@ -79,17 +81,17 @@ def get_payment_request(self, cart, request):
}
config = json.dumps(payload, cls=DjangoJSONEncoder)
success_handler = """
function(r){
function successCallback(r) {
console.log(r);
$window.location.href=r.links.filter(function(e){
$window.location.href=r.data.links.filter(function(e){
return e.rel==='approval_url';
})[0].href;
}""".replace(' ', '').replace('\n', '')
error_handler = """
function(r){
function errorCallback(r) {
console.error(r);
}""".replace(' ', '').replace('\n', '')
js_expression = '$http({0}).success({1}).error({2})'.format(config, success_handler, error_handler)
js_expression = '$http({0}).then({1},{2})'.format(config, success_handler, error_handler)
return js_expression

@classmethod
Expand All @@ -107,11 +109,20 @@ def return_view(cls, request):
except Exception as err:
warnings.warn("An internal error occurred on the upstream server: {}".format(err.message))
return cls.cancel_view(request)

if approved:
cart = CartModel.objects.get_from_request(request)
order = OrderModel.objects.create_from_cart(cart, request)
order.add_paypal_payment(payment.to_dict())
order.save()
if LooseVersion(SHOP_VERSION) < LooseVersion('0.11'):
cart = CartModel.objects.get_from_request(request)
order = OrderModel.objects.create_from_cart(cart, request)
order.add_paypal_payment(payment.to_dict())
order.save()
else:
cart = CartModel.objects.get_from_request(request)
order = OrderModel.objects.create_from_cart(cart, request)
order.populate_from_cart(cart, request)
order.add_paypal_payment(payment.to_dict())
order.save()

thank_you_url = OrderModel.objects.get_latest_url()
return HttpResponseRedirect(thank_you_url)
return cls.cancel_view(request)
Expand Down Expand Up @@ -141,11 +152,11 @@ def __init__(self, *args, **kwargs):

@transition(field='status', source=['created'], target='paid_with_paypal')
def add_paypal_payment(self, charge):
payment = OrderPayment(order=self, transaction_id=charge['id'], payment_method=PayPalPayment.namespace)
transaction = charge['transactions'][0]
assert payment.amount.currency == transaction['amount']['currency'].upper(), "Currency mismatch"
payment.amount = payment.amount.__class__(transaction['amount']['total'])
payment.save()
assert self.currency == transaction['amount']['currency'].upper(), "Currency mismatch"
Money = MoneyMaker(self.currency)
amount = Money(Decimal(transaction['amount']['total']))
OrderPayment.objects.create(order=self, amount=amount, transaction_id=charge['id'], payment_method=PayPalPayment.namespace)

def is_fully_paid(self):
return super(OrderWorkflowMixin, self).is_fully_paid()
Expand Down

2 comments on commit c5fb166

@Aiky30
Copy link

@Aiky30 Aiky30 commented on c5fb166 Jan 30, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @jrief , @SasoriOlkof,

Would having the shop version check and saving the actual order here be repeated in all other payment plugins? I'm wondering if it would be better to have a CreateOrder class / interface in the shop project to deal with any checks and project dependencies i.e. having to specifically include the following dependencies which are not really the plugins dependencies:

from decimal import Decimal
from distutils.version import LooseVersion
from shop.money import MoneyMaker

The CreateOrder class in the Shop project that would contain a generic / core way of executing the tasks required. There would be nothing to stop a plugin aauthor writing their own way and repeating the code if the methods don't fit their use case. I would see this centralised method more stable than requiring every plugin package to keep a check of what the core shop project requires.

Class CreateOrder:
    save_order():
        if LooseVersion(SHOP_VERSION) < LooseVersion('0.11'):
        .....
    add_payment():
         ...

Please excuse me for adding my opinion here. As I have mentioned before I have an interest in this project but limited time to help.

@jrief
Copy link
Member

@jrief jrief commented on c5fb166 Jan 30, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Aiky30 agree.
In djangoshop-stripe I handle this by using different version numbers. Would be better to take the same approach in djangoshop-paypal.

Please sign in to comment.