def get(self, request, *args, **kwargs): if request.user.is_authenticated: customer = Customer.objects.get(user=request.user) else: session_key=request.session.session_key name=str(session_key) user= User.objects.filter(username=name).first() customer = Customer.objects.filter(user=user).first() orders = Order.objects.filter(customer=customer).order_by('-id')[:1].first() # / if orders: liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'pay', 'amount': int(orders.cart.final_price) , 'currency': 'UAH', 'description': 'Payment for clothes', 'version': '3', 'order_id': orders.id , 'sandbox': 0, # sandbox mode, set to 1 to enable it 'result_url':'https://mysite123456.herokuapp.com/', 'server_url': 'https://mysite123456.herokuapp.com/pay-callback/', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, {'signature': signature, 'data': data}) else: return HttpResponseRedirect('/')
class TestLiqPaySimple(unittest.TestCase): def setUp(self): self.liqpay = LiqPay('', '') self.maxDiff = None def test_api(self): self.assertTrue(self.liqpay.api("payment/status", {"payment_id": "3940"})) def test_gen_form(self): expected_form_out = ( u'<form method="post" action="https://www.liqpay.com/api/3/checkout/" accept-charset="utf-8">\n' u'\t<input type="hidden" name="data" value="eyJwdWJsaWNfa2V5IjogIiIsICJkZXNjcmlwdGlvbiI6ICJcdTA0NDJcdTA0MzVcdTA0NDFcdTA0NDIiLCAibGFuZ3VhZ2UiOiAicnUiLCAic2FuZGJveCI6IDAsICJjdXJyZW5jeSI6ICJVQUgiLCAiYW1vdW50IjogIjM5NDAiLCAidGVzdCI6ICJjY2NjIn0="/>\n' u'\t<input type="hidden" name="signature" value="Zdm/xbS30v9ZTNXrLXeW9QFVxHQ="/>\n' u' <input type="image" src="//static.liqpay.com/buttons/p1ru.radius.png" name="btn_text" />\n' u'</form>' ) # test unicode issue with ru symbols params = dict( amount="3940", currency="UAH", description="тест", test="cccc" ) self.assertEqual(self.liqpay.cnb_form(params), expected_form_out) # ru symbols in unicode params.update(description=u'тест') self.assertEqual(self.liqpay.cnb_form(params), expected_form_out) # test gen_form without required param del params['amount'] self.assertRaises(ParamValidationError, self.liqpay.cnb_form, params)
def post(self, request): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) data = request.POST.get('data') signature = request.POST.get('signature') if not data or not signature: return Response({'POST data is not provided'}, status=status.HTTP_412_PRECONDITION_FAILED) sign = liqpay.str_to_sign(settings.LIQPAY_PRIVATE_KEY + data + settings.LIQPAY_PRIVATE_KEY) if sign == signature: response = liqpay.decode_data_from_str(data) end_date = datetime.fromtimestamp(int(response['end_date']) / 1e3) Payment.objects.create(payment_type=Payment.LiqPay, date=end_date, value=response['amount'], description=response['description'], liqpay_responce=response) return Response({'check': 'callback is valid'}, status=status.HTTP_200_OK) else: News.objects.create(title="Failed payment", text=data + ' ' + signature) return Response({'check': 'callback is not valid'}, status=status.HTTP_412_PRECONDITION_FAILED)
def PayLoadView(request, picture_id, org_id): try: picture = Picture.objects.get(pk=picture_id) #p_author = User.objects.get(username=request.user.username) organization = Organization.objects.get(pk=org_id) lang = "ru" if translation.get_language() == "en": lang = "en" if request.user.is_authenticated(): user = User.objects.get(username=request.user.username) user_id = user.email else: user_id = get_client_ip(request) order = Download.create(0, picture, organization, user_id, "web-liqpay") order.save() liqpay = LiqPay(settings.LIQPAY_PUBLIC, settings.LIQPAY_PRIVAT) html_f = liqpay.cnb_form({ "version" : "3", "amount" : "1", "currency" : "USD", "description" : "Donate for "+organization.name, "order_id" : order.id, "result_url" : "http://pics.ato.care/care/donload/"+picture_id+"/"+org_id+"/"+str(order.id), "language" : lang, #"sandbox": 1, }) return HttpResponse(simplejson.dumps({'success': "true", 'message': "", 'form':html_f}), content_type="application/json") except Exception, e: return HttpResponse(simplejson.dumps({'success': "false", 'message': "Wrong request..."}), content_type="application/json")
class TestLiqPaySimple(unittest.TestCase): def setUp(self): self.liqpay = LiqPay('', '') self.maxDiff = None def test_api(self): self.assertTrue( self.liqpay.api("payment/status", {"payment_id": "3940"})) def test_gen_form(self): expected_form_out = ( u'<form method="post" action="https://www.liqpay.com/api/3/checkout/" accept-charset="utf-8">\n' u'\t<input type="hidden" name="data" value="eyJwdWJsaWNfa2V5IjogIiIsICJkZXNjcmlwdGlvbiI6ICJcdTA0NDJcdTA0MzVcdTA0NDFcdTA0NDIiLCAibGFuZ3VhZ2UiOiAicnUiLCAic2FuZGJveCI6IDAsICJjdXJyZW5jeSI6ICJVQUgiLCAiYW1vdW50IjogIjM5NDAiLCAidGVzdCI6ICJjY2NjIn0="/>\n' u'\t<input type="hidden" name="signature" value="Zdm/xbS30v9ZTNXrLXeW9QFVxHQ="/>\n' u' <input type="image" src="//static.liqpay.com/buttons/p1ru.radius.png" name="btn_text" />\n' u'</form>') # test unicode issue with ru symbols params = { "amount": "3940", "currency": "UAH", "description": "тест", "test": "cccc" } self.assertEqual(self.liqpay.cnb_form(params), expected_form_out) # ru symbols in unicode params.update(description=u'тест') self.assertEqual(self.liqpay.cnb_form(params), expected_form_out) # test gen_form without required param del params['amount'] self.assertRaises(ParamValidationError, self.liqpay.cnb_form, params)
def hold_complete(self, id, amount): liqpay = LiqPay(public_key, private_key) res = liqpay.api( "request", { "action": "hold_completion", "version": "3", "amount": amount * 0.01, "order_id": id })
def post(self, request, *args, **kwargs): liqpay = LiqPay(settings.sandbox_i26660223217, settings.sandbox_u3BM9ppkXfPn0Phd5ZNhpkzieRiVWHmq12iJUJYb) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign(settings.sandbox_i26660223217 + data + settings.sandbox_u3BM9ppkXfPn0Phd5ZNhpkzieRiVWHmq12iJUJYb) if sign == signature: print('callback is valid') response = liqpay.decode_data_from_str(data) print('callback data', response) return HttpResponse()
def pay(self, price, token): liqpay = LiqPay(public_key, private_key) res = liqpay.api( "request", { "action": "p2pcredit", "version": "3", "amount": price, "currency": "UAH", "description": "description text", "order_id": "order_id_1", "receiver_card_token": token, })
def post(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign(settings.LIQPAY_PRIVATE_KEY + data + settings.LIQPAY_PRIVATE_KEY) if sign == signature: print('callback is valid') response = liqpay.decode_data_from_str(data) print('callback data', response) return HttpResponse()
class LiqPayTestCase(unittest.TestCase): def setUp(self): self.maxDiff = None self.liqpay = LiqPay('publicKey', 'privateKey') def test_api(self): url = 'payment/status' params = dict(payment_id=3940) self.assertRaises(ParamRequired, self.liqpay.api, url, params) params.update(version=3) res = self.liqpay.api(url, params) self.assertEqual(res['err_code'], 'public_key_not_found') def test_form(self): params = { 'amount': '3940', 'currency': 'UAH', 'description': 'test', 'action': 'pay', 'version': 3, 'order_id': 1, } expected_form_out = ( '<form method="post" action="https://www.liqpay.com/api/checkout/" accept-charset="utf-8">\n' '\t<input type="hidden" name="data" value="{data}"/>\n' '\t<input type="hidden" name="signature" value="{signature}"/>\n' '\t<input type="image" src="//static.liqpay.com/buttons/p1ru.radius.png" name="btn_text"/>\n' '</form>' ).format( data='eyJhY3Rpb24iOiAicGF5IiwgImFtb3VudCI6ICIzOTQwIiwgImN1cnJlbmN5IjogIlVBSCIsICJkZXNjcmlwdGlvbiI6ICJ0ZXN0IiwgIm9yZGVyX2lkIjogMSwgInB1YmxpY19rZXkiOiAicHVibGljS2V5IiwgInNhbmRib3giOiAxLCAidmVyc2lvbiI6IDN9', signature='nELNtiwxyaLzvj1hmCrxt78W/qE=' ) form = self.liqpay.get_form(sandbox=True, params=params) self.assertEqual(form.render(), expected_form_out) # test form without required param del params['amount'] with self.assertRaises(ParamRequired): form.params = params # test params validation params['language'] = 'uk' # unsupported language with self.assertRaises(ParamValidationError): form.params = params del params['language'] params['currency'] = 'MXN' # unsupported currency with self.assertRaises(ParamValidationError): form.params = params
class LiqPayTestCase(unittest.TestCase): def setUp(self): self.maxDiff = None self.liqpay = LiqPay('publicKey', 'privateKey') def test_api(self): url = 'payment/status' params = dict(payment_id=3940) self.assertRaises(ParamRequired, self.liqpay.api, url, params) params.update(version=3) res = self.liqpay.api(url, params) self.assertEqual(res['err_code'], 'public_key_not_found') def test_form(self): params = { 'amount': '3940', 'currency': 'UAH', 'description': 'test', 'action': 'pay', 'version': 3, 'order_id': 1, } expected_form_out = ( '<form method="post" action="https://www.liqpay.ua/api/checkout/" accept-charset="utf-8">\n' ' <input type="hidden" name="data" value="{data}"/>\n' ' <input type="hidden" name="signature" value="{signature}"/>\n' ' <input type="image" src="//static.liqpay.com/buttons/p1ru.radius.png" name="btn_text"/>\n' '</form>' ).format( data= 'eyJhY3Rpb24iOiAicGF5IiwgImFtb3VudCI6ICIzOTQwIiwgImN1cnJlbmN5IjogIlVBSCIsICJkZXNjcmlwdGlvbiI6ICJ0ZXN0IiwgIm9yZGVyX2lkIjogMSwgInB1YmxpY19rZXkiOiAicHVibGljS2V5IiwgInNhbmRib3giOiAxLCAidmVyc2lvbiI6IDN9', signature='nELNtiwxyaLzvj1hmCrxt78W/qE=') form = self.liqpay.get_form(sandbox=True, params=params) self.assertEqual(form.render(), expected_form_out) # test form without required param del params['amount'] with self.assertRaises(ParamRequired): form.params = params # test params validation params['language'] = 'uk' # unsupported language with self.assertRaises(ParamValidationError): form.params = params del params['language'] params['currency'] = 'MXN' # unsupported currency with self.assertRaises(ParamValidationError): form.params = params
def __init__(self, params, *args, **kwargs): self.params = {} if params is None else deepcopy(params) self.liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) self.action_url = urljoin(self.liqpay._host, constants.CHECKOUT_URL) self.params.update( version=constants.API_VERSION, sandbox=str( int(bool(params.get('sandbox', settings.LIQPAY_SANDBOX)))), ) initial = { 'data': self.liqpay.cnb_data(self.params), 'signature': self.liqpay.cnb_signature(self.params), } super().__init__(initial=initial, *args, **kwargs)
def get(self, request, *args, **kwargs): liqpay = LiqPay(settings.sandbox_i26660223217, settings.sandbox_u3BM9ppkXfPn0Phd5ZNhpkzieRiVWHmq12iJUJYb) params = { 'action': 'pay', 'amount': '100', 'currency': 'USD', 'description': 'Payment for medicines', 'order_id': 'order_id_1', 'version': '3', 'sandbox': 1, # sandbox mode, set to 1 to enable it 'server_url': 'https://test.com/billing/pay-callback/', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, {'signature': signature, 'data': data})
def get(self, request, *args, **kwargs): liqpay = LiqPay(LIQPAY_PUBLIC_KEY, LIQPAY_PRIVATE_KEY) amount = Replanishment.objects.get(id=request.session['payment_id']).ammount print request.user params = { 'action': 'pay', 'amount': amount, 'currency': 'UAH', 'description': 'Пополнение аккаунта', 'order_id': request.session['payment_id'], 'version': '3', 'sandbox': '1', 'server_url': 'https://%s/pay-callback/' % DOMAIN_NAME, } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, {'signature': signature, 'data': data})
def liqpay_callback(request): form = CallbackForm(request.POST or None) if not form.is_valid(): logger.warning('Invalid callback form, POST: {}'.format(request.POST)) return HttpResponse(status=400) data = form.cleaned_data['data'] signature = form.cleaned_data['signature'] liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) our_sign = liqpay.str_to_sign(settings.LIQPAY_PRIVATE_KEY + data + settings.LIQPAY_PRIVATE_KEY) if signature != our_sign: logger.warning('Invalid signature: our {}!={}'.format( our_sign, signature)) return HttpResponse(status=400) data = liqpay.decode_data_from_str(data) status = data.get('status') if status not in ('success', 'sandbox'): logger.warning('Status is not success: {} {} {} {}'.format( status, data.get('err_code'), data.get('err_description'), data)) return HttpResponse(status=400) try: order = LiqPayOrder.objects.get(order_id=data['order_id']) except LiqPayOrder.DoesNotExist: logger.warning('Wrong order_id: {}'.format(data['order_id'])) return HttpResponse(status=400) logger.info('Payment status={}: id={} amount={} {}'.format( status, order.order_id, data['amount'], data['currency'])) result_received.send( sender=order, order_id=order.order_id, amount=data['amount'], currency=data['currency'], ) return HttpResponse('OK', status=200)
def get(self, request, *args, **kwargs): task = Task.objects.get(pk=kwargs['pk']) liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'p2p', 'amount': str(task.estimated_price), 'order_id': str(task.pk), 'currency': 'UAH', 'description': 'Оплата за завдання #{}'.format(task.pk), 'version': '3', 'sandbox': settings.LIQPAY_SANDBOX_MODE, 'receiver_card': task.executor.worker_profile.card_number, 'server_url': settings.LIQPAY_SERVER_URL, } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, {'signature': signature, 'data': data, 'task': task})
def get(self, request, bill: int): bill_pk = self.kwargs['bill'] # get the apartment try: bill = Bill.objects.get(pk=bill_pk) # return error HTTP_400_BAD_REQUEST if apartment does not exist except Bill.DoesNotExist: return Response(_('Bill with such id does not exist'), status=status.HTTP_400_BAD_REQUEST) # prepearing Liqpay data liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': settings.LIQPAY_DEFAULT_ACTION, 'currency': settings.LIQPAY_DEFAULT_CURRENCY, 'language': settings.LIQPAY_DEFAULT_LANGUAGE, 'amount': str(bill.total_value), 'description': f'Payment for bill {bill.number}', 'order_id': bill_pk, 'version': '3', 'sandbox': 1, # sandbox mode, set to 1 to enable it 'server_url': 'https://dimonline.pp.ua:8443/payments/api/v1/pay_callback/', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return Response({ 'signature': signature, 'data': data }, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs): liqpay = LiqPay(LIQPAY_PUBLIC_KEY, LIQPAY_PRIVATE_KEY) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign(LIQPAY_PRIVATE_KEY + data + LIQPAY_PRIVATE_KEY) if sign == signature: print('callback is valid') response = liqpay.decode_data_from_str(data) if len(response) != 0: oreder_id = response['order_id'] status = response['status'] rep = Replanishment.objects.get(id=oreder_id) rep.status = status rep.save() if status == 'sandbox': profile = Profile.objects.get(user_id=rep.user_replanishment_id) profile.account = profile.account + decimal.Decimal(rep.ammount) profile.save() print('callback data', response) return HttpResponse()
def get(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'pay', 'amount': self.kwargs['price'], # 'amount': '0.01', 'currency': 'UAH', 'description': 'Оплата обуви, отправка с магазина Kicks Industry, г. Ужгород, ул. Льва Толстого, 5', 'order_id': 'order_id_1', 'version': '3', 'sandbox': 0, # sandbox mode, set to 1 to enable it 'server_url': 'https://test.com/billing/pay-callback/', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, { 'signature': signature, 'data': data })
def post(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign(settings.LIQPAY_PRIVATE_KEY + data + settings.LIQPAY_PRIVATE_KEY) # if sign == signature: response =liqpay.decode_data_from_str(data) try: phone = response['sender_phone'] except: phone = '0' if phone != '0' and signature == sign: orders = Order.objects.get(id=response['order_id']) if response['status'] == 'success': orders.status_pay = 'pay' orders.save() x ='сумма платежа'+str(response['amount'])+ '... response order id==='+response['order_id']+'--status----'+response['status'] +'--phone'+phone +'Остальное -------'+str(response) send_mail('Платеж удачен!',x, "Yasoob",['*****@*****.**'], fail_silently=False) if response['status'] == 'failed': orders.status_pay='not_pay' orders.save() # x = '... response order id==='+response['order_id']+'--status----'+response['status'] +'--phone'+phone +'Остальное -------'+str(response) send_mail('Платеж отклонен!', "Yasoob",['*****@*****.**'], fail_silently=False) if response['status'] == 'reversed': orders.status_pay='reversed' orders.save() # x = '... response order id==='+response['order_id']+'--status----'+response['status'] +'--phone'+phone +'Остальное -------'+str(response) send_mail('Платеж возвращн', "Yasoob",['*****@*****.**'], fail_silently=False) if response['status'] == 'error': orders.status_pay = 'miss' orders.save() #написать если ошибка при оплате # x = ' ошибка при оплате '+' .order id==='+response['order_id']+'--status----'+response['status'] +'--phone'+phone +'Остальное -------'+str(response) send_mail('Платеж ошибка!', "Yasoob",['*****@*****.**'], fail_silently=False) result_url = 'https://mysite123456.herokuapp.com/' return HttpResponse()
def post(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign(settings.LIQPAY_PRIVATE_KEY + data + settings.LIQPAY_PRIVATE_KEY) if sign == signature: response = liqpay.decode_data_from_str(data) if settings.LIQPAY_SANDBOX_MODE: expected_status = 'sandbox' else: expected_status = 'success' if response['status'] == expected_status: task = Task.objects.get(pk=int(response['order_id'])) task.status = Task.DONE task.save() create_notification_task.delay( task.executor.id, task.id, 'Оплата завдання', 'Завдання #{} було оплачено.'.format(task.id) ) return HttpResponse("OK") return HttpResponse("Oops! Something went wrong.")
def get_payment(order_id): ukraine = timezone(timedelta(hours=2)) data = CafeOrder.find_one({"order_id": str(order_id)}) if data is None: return "Замовлення не знайдено" data_to_send = { "version": 3, "public_key": UNIT_PUB_KEY, "action": "pay", "amount": str(data.price), "currency": "UAH", "description": "{order_id} від {datetime} За замовлення в UNIT.cafe".format( order_id=order_id, datetime=datetime.now( tz=ukraine).strftime("%Y-%m-%dT%H:%M:%S.%f")), "server_url": "https://unit.cafe/index.php?route=extension/payment/liqpay/callback", "result_url": "https://www.facebook.com/FriendlyFoodBot/", "order_id": order_id } liqpay = LiqPay(UNIT_PUB_KEY, UNIT_PRIV_KEY) try: html = liqpay.cnb_form(data_to_send) except: return "Замовлення не знайдено" return html
import json from flask import Flask from liqpay import LiqPay app = Flask(__name__) app.config.update( SECRET_KEY='paymentApp', public_key='sandbox_i31321528342', private_key='sandbox_4E2WdIDxDV4KzdXeUkPlfqGwzt6ufXxsqqOaXpyz' ) lp = LiqPay( app.config.get('public_key'), app.config.get('private_key') ) payments = {} with open('./app/rooms.json', 'r') as f: rooms = json.load(f) from app import routes
def setUp(self): self.liqpay = LiqPay('', '') self.maxDiff = None
def setUp(self): self.liqpay = LiqPay("", "") self.maxDiff = None
def setUp(self): self.maxDiff = None self.liqpay = LiqPay('publicKey', 'privateKey')