Skip to content

Commit

Permalink
Merge branch 'master' of github.com:awesto/djangoshop-paypal
Browse files Browse the repository at this point in the history
# Conflicts:
#	README.md
  • Loading branch information
jrief committed Jan 10, 2020
2 parents b04e828 + a5cd252 commit f1c381b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 52 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ If a payment was rejected by PayPal, **djangoshop-paypal** redirects onto the CM

## Changes

### 1.0.1
* Fix #6: PayPal's create payment now is invoked by the server.

### 1.0

* Adopted for django-SHOP version 1.0.
* Adopted to django-SHOP version 1.0
2 changes: 1 addition & 1 deletion shop_paypal/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.0'
__version__ = '1.0.1'
88 changes: 38 additions & 50 deletions shop_paypal/payment.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import paypalrestsdk
import warnings
from decimal import Decimal

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
Expand Down Expand Up @@ -44,65 +42,55 @@ def get_paypal_api(cls):
})
return api

def get_payment_request(self, cart, request):
"""
From the given request, redirect onto the checkout view, hosted by PayPal.
"""
def build_absolute_url(self, request, endpoint):
shop_ns = resolve(request.path).namespace
return_url = reverse('{}:{}:return'.format(shop_ns, self.namespace))
cancel_url = reverse('{}:{}:cancel'.format(shop_ns, self.namespace))
paypal_api = self.get_paypal_api()
auth_token_hash = paypal_api.get_token_hash()
url = reverse('{}:{}:{}'.format(shop_ns, self.namespace, endpoint))
return request.build_absolute_uri(url)

def create_payment_payload(self, cart, request):
items = []
for cart_item in cart.items.all():
kwargs = dict(cart_item.extra, product_code=cart_item.product_code)
product = cart_item.product.get_product_variant(**kwargs)
items.append({
'name': cart_item.product.product_name,
'quantity': str(int(cart_item.quantity)),
'price': str(cart_item.product.unit_price.as_decimal()),
'currency': cart_item.product.unit_price.currency,
'price': str(product.unit_price.as_decimal()),
'currency': product.unit_price.currency,
})
payload = {
'url': '{API_ENDPOINT}/v1/payments/payment'.format(**settings.SHOP_PAYPAL),
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Authorization': '{token_type} {access_token}'.format(**auth_token_hash),
return {
'intent': 'sale',
'payer': {
'payment_method': 'paypal',
},
'redirect_urls': {
'return_url': self.build_absolute_url(request, 'return'),
'cancel_url': self.build_absolute_url(request, 'cancel'),
},
'data': {
'intent': 'sale',
'redirect_urls': {
'return_url': request.build_absolute_uri(return_url),
'cancel_url': request.build_absolute_uri(cancel_url),
'transactions': [{
'item_list': {
'items': items,
},
'payer': {
'payment_method': 'paypal',
'amount': {
'total': str(cart.total.as_decimal()),
'currency': cart.total.currency,
},
'transactions': [{
'item_list': {
'items': items,
},
'amount': {
'total': str(cart.total.as_decimal()),
'currency': cart.total.currency,
},
'description': settings.SHOP_PAYPAL['PURCHASE_DESCRIPTION']
}]
}
'description': settings.SHOP_PAYPAL['PURCHASE_DESCRIPTION']
}],
}
config = json.dumps(payload, cls=DjangoJSONEncoder)
success_handler = """
function successCallback(r) {
console.log(r);
$window.location.href=r.data.links.filter(function(e){
return e.rel==='approval_url';
})[0].href;
}""".replace(' ', '').replace('\n', '')
error_handler = """
function errorCallback(r) {
console.error(r);
}""".replace(' ', '').replace('\n', '')
js_expression = '$http({0}).then({1},{2})'.format(config, success_handler, error_handler)
return js_expression

def get_payment_request(self, cart, request):
"""
From the given request, redirect onto the checkout view, hosted by PayPal.
"""
paypal_api = self.get_paypal_api()
payload = self.create_payment_payload(cart, request)
payment = paypalrestsdk.Payment(payload, api=paypal_api)
if payment.create():
redirect_url = [link for link in payment.links if link.rel == 'approval_url'][0].href
else:
redirect_url = payload['redirect_urls']['cancel_url']
return '$window.location.href="{0}";'.format(redirect_url)

@classmethod
def return_view(cls, request):
Expand Down

0 comments on commit f1c381b

Please sign in to comment.