· 5 years ago · Jul 29, 2020, 01:08 PM
1import requests
2from urllib import parse
3import json
4import uuid
5from datetime import datetime, date
6
7from django.http import HttpResponseRedirect
8from django.utils.translation import ugettext_lazy as _
9from django.shortcuts import redirect
10from django.db import transaction
11from django.urls import reverse
12
13from rest_framework.views import APIView
14from rest_framework.response import Response
15from rest_framework import permissions
16
17from apps.paypal_r.models import Configurations
18from apps.products.utils import get_or_create_basket_by_user_or_by_session
19from apps.orders.utils import (
20 create_order_from_cart, send_emails_about_new_order
21)
22from apps.orders.models import PaymentStatus, OrderStatus
23from apps.coupons.utils import complete_using_of_coupon
24from apps.orders.models import Order
25
26__all__ = (
27 'DoDirectPaymentApiView',
28 'SetExpressCheckoutApiView',
29 'GetExpressCheckoutApiView'
30)
31
32
33def paypal_response_to_dict(resp_content):
34
35 new_dict = parse.parse_qs(resp_content.decode("utf-8"), keep_blank_values=True)
36 for key in new_dict.keys():
37 new_dict[key] = new_dict[key][0]
38 return new_dict
39
40
41def test_paypal():
42
43 print('test_paypal')
44
45 charge = {
46 'VERSION': '1.12.0',
47 'SIGNATURE': 'AOYJVCgMkBJR7EqSlv-PcHK6.-umAtykpT3xSaE4PqW-me.1SWD2OkZI',
48 'USER': 'sb-gzt1i753360_api1.business.example.com',
49 'PWD': 'PAVR9WZH97V53D8D',
50 'METHOD': 'DoDirectPayment',
51 'PAYMENTACTION': 'Sale',
52 'IPADDRESS': '192.168.0.1',
53 'amt': '10.00',
54 'creditcardtype': 'Visa',
55 'acct': '4032031175808137',
56 'expdate': '012025',
57 'cvv2': '962',
58 'firstname': 'Jack',
59 'lastname': 'Daniels',
60 'street': '1 Main St',
61 'city': 'San Jose',
62 'state': 'CA',
63 'zip': '95131',
64 'countrycode': 'US',
65 'currencycode': 'USD',
66 'business': ''
67 }
68
69 print('start response to paypal api')
70
71 response = requests.post(url='https://api-3t.sandbox.paypal.com/nvp', data=charge, timeout=10)
72 pp_resp = paypal_response_to_dict(response.content)
73
74 print(f'response -> {pp_resp}')
75
76 return True
77
78
79class DoDirectPaymentApiView(APIView):
80
81 permission_classes = (permissions.AllowAny,)
82
83 def post(self, request, *args, **kwargs):
84
85 print(request.data)
86
87 # serializer = IdeaCreateSerializer(data=request.data)
88 # serializer.is_valid(raise_exception=True)
89 # idea = serializer.save()
90 #
91 # send_mail_to_admin_about_new_idea(request, idea)
92
93 print('DoDirectPaymentApiView')
94
95 charge = {
96 'VERSION': '1.12.0',
97 'SIGNATURE': 'AOYJVCgMkBJR7EqSlv-PcHK6.-umAtykpT3xSaE4PqW-me.1SWD2OkZI',
98 'USER': 'sb-gzt1i753360_api1.business.example.com',
99 'PWD': 'PAVR9WZH97V53D8D',
100 'METHOD': 'DoDirectPayment',
101 'PAYMENTACTION': 'Sale',
102 'IPADDRESS': '192.168.0.1',
103 'amt': '10.00',
104 'creditcardtype': 'Visa',
105 'acct': '4032031175808137',
106 'expdate': '012025',
107 'cvv2': '962',
108 'firstname': 'Jack',
109 'lastname': 'Daniels',
110 'street': '1 Main St',
111 'city': 'San Jose',
112 'state': 'CA',
113 'zip': '95131',
114 'countrycode': 'US',
115 'currencycode': 'USD',
116 }
117
118 response = requests.post(url='https://api-3t.sandbox.paypal.com/nvp', data=charge)
119
120 print(f'response -> {response.__dict__}')
121
122 return Response(status=201, data={'response': 'Idea is successfully created and waiting for moderation'})
123
124
125def generate_unique_number_of_order_long(total_cost):
126 unique_time = str(datetime.now().timestamp())
127 date_ = str(date.today().strftime('%Y%m%d'))
128 return date_ + '.' + total_cost + '.' + unique_time
129
130
131def generate_unique_number_of_order(length):
132 code = uuid.uuid4().hex[:length].upper()
133 while Order.objects.filter(id_of_order=code):
134 code = uuid.uuid4().hex[:length].upper()
135 return code
136
137
138class SetExpressCheckoutApiView(APIView):
139
140 def get(self, request):
141
142 print('SetExpressCheckoutApiView')
143 print(request.GET)
144
145 # url_live = 'https://payflowpro.paypal.com'
146 # url_sandbox = 'https://pilot-payflowpro.paypal.com'
147 # api_endpoint = 'https://api-3t.sandbox.paypal.com/nvp'
148 # data = {
149 # 'USER': 'paradoxttestsoft1',
150 # 'VENDOR': 'gearheartpayflowtest',
151 # 'PARTNER': 'PayPal',
152 # 'PWD': 'softTesting@2019',
153 # 'TRXTYPE': 'S',
154 # 'TENDER': 'P',
155 # 'ACTION': 'S',
156 # 'AMT': '0.01',
157 # 'CURRENCY': 'USD',
158 # 'RETURNURL': 'http://localhost:8540/paypal_test/',
159 # 'CANCELURL': 'http://localhost:8540/paypal_test/',
160 # 'ORDERDESC': 'test order',
161 # 'INVNUM': 'I NX123',
162 # 'METHOD': 'SetExpressCheckout'
163 # }
164
165 conf = Configurations.objects.first()
166 api_endpoint = conf.api_endpoint
167 cart = get_or_create_basket_by_user_or_by_session(request)
168 INVNUM = generate_unique_number_of_order(8)
169 cart.id_of_order = INVNUM
170 cart.save()
171 print(cart.__dict__)
172
173 data = {
174 'VERSION': '1.12.0',
175 'SIGNATURE': conf.signature,
176 'USER': conf.username,
177 'PWD': conf.password,
178 'METHOD': "SetExpressCheckout",
179 'NOSHIPPING': 1,
180 'PAYMENTACTION': 'Authorization',
181 'AMT': cart.total_cost,
182 'CURRENCY': 'USD',
183 'RETURNURL': 'http://localhost:8540/paypal_test/',
184 'CANCELURL': 'http://localhost:8540/paypal_test/',
185 'ORDERDESC': 'Gear Heart Industry. Payment for order.',
186 'INVNUM': INVNUM
187 }
188 headers = {
189 "Content-Type": "application/json",
190 "Authorization": "Bearer Access-Token"
191 }
192
193 print(data)
194 response = requests.post(api_endpoint, headers=headers, data=data)
195 response = paypal_response_to_dict(response.content)
196 print(response)
197 return Response(status=200, data=json.dumps(response))
198
199
200class GetExpressCheckoutApiView(APIView):
201
202 permission_classes = (permissions.AllowAny,)
203
204 def post(self, request):
205
206 # url_live = 'https://payflowpro.paypal.com'
207 # url_sandbox = 'https://pilot-payflowpro.paypal.com'
208 # api_endpoint = 'https://api-3t.sandbox.paypal.com/nvp'
209
210 print('GetExpressCheckoutApiView')
211 print(request.data)
212
213 with transaction.atomic():
214 conf = Configurations.objects.first()
215 api_endpoint = conf.api_endpoint
216 cart = get_or_create_basket_by_user_or_by_session(request)
217 print(cart.__dict__)
218
219 """
220 Вот тут уже нужно создать Заказ из Корзины.
221 Присвоить ему статус оплачено/ждёт оплаты в зависимости от ответа апи PayPal.
222 Но Заказ так или иначе будет создан, а Корзина - очищена.
223 """
224 user = cart.user
225 order = create_order_from_cart(cart, request.data['orderID'])
226
227 data = {
228 'VERSION': '1.12.0',
229 'SIGNATURE': conf.signature,
230 'USER': conf.username,
231 'PWD': conf.password,
232 'METHOD': "GetExpressCheckoutDetails",
233 'RETURNURL': 'http://localhost:8540/',
234 'CANCELURL': 'http://localhost:8540/',
235 'TOKEN': request.data['orderID']
236 }
237
238 response = requests.post(api_endpoint, data=data)
239 response = paypal_response_to_dict(response.content)
240 print(response)
241
242 params = {
243 'VERSION': '1.12.0',
244 'SIGNATURE': conf.signature,
245 'USER': conf.username,
246 'PWD': conf.password,
247 'METHOD': "DoExpressCheckoutPayment",
248 'PAYMENTACTION': 'Sale',
249 'RETURNURL': 'http://localhost:8540/paypal_test/',
250 'CANCELURL': 'http://localhost:8540/paypal_test/',
251 'TOKEN': request.data['orderID'],
252 'AMT': order.total_cost,
253 'PAYERID': request.data['payerID'],
254 }
255
256 response = requests.post(api_endpoint, data=params)
257
258 if response.status_code == 200:
259 order.payment_status = PaymentStatus.objects.filter(name='paid').first()
260 message = _("Order successfully paid. A manager will contact you shortly.")
261 else:
262 order.payment_status = PaymentStatus.objects.filter(name='wait').first()
263 message = _("Payment for the order was unsuccessful. Do not worry, in the near future a manager will contact you and help to resolve all issues.")
264 # order.status = OrderStatus.objects.filter(name='accepted').first()
265 order.save()
266
267 if user.is_authenticated:
268 complete_using_of_coupon(user)
269
270 send_emails_about_new_order(request, order)
271
272 response = paypal_response_to_dict(response.content)
273 print(response)
274
275 # return HttpResponseRedirect(reverse('order-complete') + f'?message={message}')
276
277 return Response(status=200, data={'redirect_to': reverse('order-complete') + f'?message={message}'})
278