def get(self, request, *args, **kwargs): if request.session.get('order'): order_id = request.session['order'][0] order_price = str(request.session['order'][1]) if Order.objects.filter(pk=int(order_id)).exists(): liqpay = LiqPay(os.getenv('LIQPAY_PUBLIC_KEY'), os.getenv('LIQPAY_PRIVATE_KEY')) params = { 'action': 'pay', 'amount': str(order_price), 'currency': 'UAH', 'description': f'Payment for order № {order_id}', 'order_id': str(order_id), 'version': '3', 'sandbox': 1, # sandbox mode, set to 1 to enable it 'server_url': 'https://localhost:8008/payback/', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_form(params) st = data.find('value=') + 7 data2 = data[st:] end = data2.find('/>') - 1 data = data2[:end] signature = data2[end:] st = signature.find('value=') + 7 signature = signature[st:] end = signature.find('/>') - 1 signature = signature[:end] return render(request, self.template_name, { 'signature': signature, 'data': data }) raise Http404
def get(self, request, id, *args, **kwargs): booking = Booking.objects.get(pk=id) liq_pay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'pay', 'amount': booking.price, 'currency': 'UAH', 'description': 'Оплата за проживання {}'.format(booking.pib), 'order_id': booking.id, 'version': '3', 'sandbox': 1, # sandbox mode, set to 1 to enable it 'server_url': 'http://127.0.0.1:8000/pay-callback/{}'.format( booking.id), # url to callback view } signature = liq_pay.cnb_signature(params) data = liq_pay.cnb_data(params) return render(request, self.template_name, { 'signature': signature, 'data': data })
def get_context_data(self, **kwargs): context = super(ConfirmLiqpay, self).get_context_data(**kwargs) days = self.kwargs.get('days') context['price'] = getattr(SettingsFranchise.get_solo(), 'price_{0}'.format(days)) context['currency'] = SettingsFranchise.get_solo().currency context['method'] = 'LiqPay' context['title'] = 'Оплата через LiqPay' site = Site.objects.get_current() liqpay = LiqPay(get_liqpay_public_key(), get_liqpay_signature()) result_url = site.domain + str(reverse_lazy('liqpay:done_liqpay')) server_url = site.domain + str(reverse_lazy('liqpay:callback_liqpay')) context['html'] = liqpay.cnb_form({ "action": "pay", "amount": context['price'], "currency": context['currency'], "description": "Продление франшизы " + site.name, "order_id": self.get_order_count(), "version": "3", # "sandbox": "yes", "server_url": server_url, 'result_url': result_url, 'info': days, }) return context
def get_liqpay_form(self, cart): liqpay = LiqPay(LIQPAY_PUBLIC, LIQPAY_PRIVATE) liqpay_data = { "action": "pay", "amount": str(cart.ticket_type.cost), "currency": "UAH", "description": "{} ticket for {}".format(cart.ticket_type.type, cart.ticket_type.campaign.title), "order_id": cart.uid, "language": "ru", "sandbox": cart.ticket_type.campaign.sandbox, "server_url": self.request.build_absolute_uri(reverse('api-liqpay')), "result_url": self.request.build_absolute_uri(cart.get_absolute_url()) } logger.info(liqpay_data) html = liqpay.cnb_form(liqpay_data) return html
def checkout(request): session_key = request.session.session_key products_in_basket = ProductInBasket.objects.filter( session_key=session_key, is_active=True, order__isnull=True) print(products_in_basket) for item in products_in_basket: print(item.order) form = CheckoutContactForm(request.POST or None) liqpay = LiqPay("sandbox_i26660223217", "sandbox_u3BM9ppkXfPn0Phd5ZNhpkzieRiVWHmq12iJUJYb") html1 = liqpay.cnb_form({ 'action': 'pay', 'amount': '5', 'currency': 'USD', 'description': 'description text', 'order_id': 'order_id_52', 'version': '3', 'result_url': 'http://127.0.0.1:8000/' }) if request.POST: print(request.POST) if form.is_valid(): print("yes") data = request.POST name = data.get("name", "3423453") phone = data["phone"] user, created = User.objects.get_or_create( username=phone, defaults={"first_name": name}) order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, customer_address=address, status_id=1) for name, value in data.items(): if name.startswith("product_in_basket_"): product_in_basket_id = name.split("product_in_basket_")[1] product_in_basket = ProductInBasket.objects.get( id=product_in_basket_id) print(type(value)) product_in_basket.nmb = value product_in_basket.order = order product_in_basket.save(force_update=True) ProductInOrder.objects.create( product=product_in_basket.product, nmb=product_in_basket.nmb, price_per_item=product_in_basket.price_per_item, total_price=product_in_basket.total_price, order=order) return HttpResponseRedirect(request.META['HTTP_REFERER']) else: print("no") return render(request, 'orders/checkout.html', locals())
def __init__(self): if settings.DEBUG: key_1, key_2 = '', '' else: key_1, key_2 = '', '' self.sign_str = ''.format(key_1, key_2) self.liqpay = LiqPay(key_1, key_2) self.data = ''
def payment(request, sum): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) html = liqpay.cnb_form({ 'action': 'p2p', 'amount': '1000', 'currency': 'UAH', 'description': 'Заказ недвижимости через DOMUM', 'order_id': OrderId.objects.first().next(), 'version': '3', 'sandbox': 0, 'server_url': 'http://127.0.0.1:8000/pay-callback/', }) return HttpResponse(html)
def post(self, request, id, *args, **kwargs): booking = Booking.objects.get(pk=id) liq_pay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) data = request.POST.get('data') signature = request.POST.get('signature') sign = liq_pay.str_to_sign(settings.LIQPAY_PRIVATE_KEY + data + settings.LIQPAY_PRIVATE_KEY) if sign == signature: booking.is_paid = True booking.save() response = liq_pay.decode_data_from_str(data) print('callback data', response) return HttpResponse()
def post(self, request, *args, **kwargs): liqpay = LiqPay(os.getenv('LIQPAY_PUBLIC_KEY'), os.getenv('LIQPAY_PRIVATE_KEY')) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign( os.getenv('LIQPAY_PRIVATE_KEY') + data + os.getenv('LIQPAY_PRIVATE_KEY')) if sign == signature: print('callback is valid') response = '' base64.b64decode(data, response) print('callback data', response) if request.session.get('order'): request.session.pop('order') return HttpResponse()
def get_pay_form(self): lq = LiqPay(settings.LIQPAY_MERCHANT_ID, settings.LIQPAY_SIGNATURE) payment_params = { 'version': '3', 'amount': str(self.amount), 'currency': 'UAH', 'description': self.description, 'order_id': self.order_id, 'result_url': 'http://ci.ua/accounts/profile/', 'server_url': 'http://ci.ua/accounts/liqpay/result', 'type': 'buy', } # 'sandbox': '1',} # tesst payment lq_form = lq.cnb_form(payment_params) self.save() return lq_form
def get_liqpay_form(self, cart): liqpay = LiqPay(LIQPAY_PUBLIC, LIQPAY_PRIVATE) liqpay_data = { "action": "pay", "amount": str(cart.ticket_type.cost), "currency": "UAH", "description": "{} ticket for {}".format(cart.ticket_type.type, cart.ticket_type.campaign.title), "order_id": cart.uid, "language": "ru", "sandbox": cart.ticket_type.campaign.sandbox, "server_url": self.request.build_absolute_uri(reverse('api-liqpay')), "result_url": self.request.build_absolute_uri(cart.get_absolute_url()) } logger.info(liqpay_data) html = liqpay.cnb_form(liqpay_data) return html
async def get_new_postal_data(session, remittance): apikey = '5c91a4239f54889de26a9a4a29698f16' request_url = "https://api.novaposhta.ua/v2.0/json/" json_req = { "apiKey": "{}".format(apikey), "modelName": "TrackingDocument", "calledMethod": "getStatusDocuments", "methodProperties": { "Documents":[ { "DocumentNumber": "{}".format(remittance.postal_code), }] } } async with session.get(request_url, data=json.dumps(json_req)) as response: data = await response.read() data = json.loads(data) if time.time() - float(remittance.date_payed) > 1874880: if data['data'][0]['StatusCode'] == '9' or data['data'][0]['StatusCode'] == '3': liqpay = LiqPay(public_key, private_key) res = liqpay.api("request", { "action" : "hold_completion", "version" : "3", "order_id" : remittance.liqpay_order_id, "amount" : str(float(remittance.amount * 0.01)), }) res = liqpay.api("request", { "action" : "p2p", "version" : "3", "phone" : remittance.remittance_customer.usercard.phone_number, "amount" : remittance.amount, "currency" : "UAH", "description" : remittance.payment_desciption, "order_id" : str(gen_link()), "receiver_card" : remittance.remittance_seller.usercard.card_number, "card" : remittance.remittance_customer.usercard.card_number, "card_exp_month" : remittance.remittance_customer.usercard.month_card, "card_exp_year" : remittance.remittance_customer.usercard.year_card, "card_cvv" : remittance.remittance_customer.usercard.cvv_card })
def buy(request,id): lesson = get_object_or_404(Vlesson, pk=id) l = Liqpay() l.user = request.user l.lesson = lesson l.amount = lesson.price l.save() liqpay = LiqPay(LIQPAY_PUBLIC_KEY, LIQPAY_PRIVATE_KEY) form = liqpay.cnb_form({"amount" : lesson.price, "currency" : "UAH", "description" : u"Покупка видеоурока", "order_id" : l.id, "result_url": LIQPAY_RESULT_URL, "server_url": LIQPAY_SERVER_URL, "type" : "buy", "sandbox" : "1"}) context = {'lesson': lesson, 'button': form} return render_to_response('buy.html', context, RequestContext(request))
def buy(request,id): issue = get_object_or_404(Issue, pk=id) from liqpay.models import Liqpay l = Liqpay() l.issue = issue l.user = request.user l.amount = issue.journal.price l.save() liqpay = LiqPay(LIQPAY_PUBLIC_KEY, LIQPAY_PRIVATE_KEY) form = liqpay.cnb_form({"amount" : "3", "currency" : "RUB", "description" : "Покупка прессы", "order_id" : l.id, "result_url": LIQPAY_RESULT_URL, "server_url": LIQPAY_SERVER_URL, "type" : "buy", "sandbox" : "1"}) context = {"issue": issue, 'button': form} return render_to_response('catalog/buy.html', context, RequestContext(request))
def pay(self, paid, unique_link): remittance = Remittance.objects.filter(unique_link=unique_link) date_credit = self.gen_date() liqpay = LiqPay(public_key, private_key) amount = '0' if remittance[0].payment_by_installments == True: amount = str( math.ceil(remittance[0].amount / remittance[0].installments_count)) else: amount = str(remittance[0].amount) res = liqpay.api( "request", { "action": "hold", "version": "3", "phone": '38' + paid["phone"], "amount": amount, "currency": 'UAH', "description": str(remittance[0].payment_desciption), "order_id": str(gen_link()), "card": str(paid["card"]), "card_exp_month": str(paid["card_exp_month"]), "card_exp_year": str(paid["card_exp_year"]), "card_cvv": str(paid["card_cvv"]), }) if res['status'] == 'hold_wait': remittance.update(paid=True, liqpay_order_id=res['order_id'], date_payed=str(time.time())) return { 'pay-status': { 'success': 'OK', 'user_id': remittance[0].remittance_customer.id } } else: return { 'pay-status': { 'error': 'Помилка платежу можливо не вірно введені дані', 'user_id': remittance[0].remittance_customer.id } }
def send_test(self, data, private_key, request): name_shop = auth.get_user(request).id user = CustomUser.objects.get(id=name_shop) card = validgetdata(data.get('card'), private_key) cvv = validgetdata(data.get('cvv'), private_key) mm = validgetdata(data.get('mm'), private_key) yy = validgetdata(data.get('yy'), private_key) phone = validgetdata(data.get('phone'), private_key) liqpay = LiqPay("sandbox_i22708126141", b"sandbox_DRE62ozXPO4UyfUU8jUGlUls2F7LV8SGussS1jxE") res = liqpay.api( "request", { "action": "auth", "version": "3", "phone": '38' + phone, "amount": '1', "currency": 'USD', "description": 'test', "order_id": gen_link(), "card": card, "card_exp_month": mm, "card_exp_year": yy, "card_cvv": cvv, }) if res['result'] == 'error': return {'result': 'Введенні вами данні невірні'} else: if res['status'] == 'error': return {'result': 'Введенні вами данні невірні'} elif res['status'] == 'success': return { 'result': 'OK', 'data': { 'phone_number': phone, 'card': card, 'cvv': cvv, 'yy': yy, 'mm': mm } }
def get(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'pay', 'amount': '1', 'currency': 'USD', 'description': 'Payment for clothes', 'order_id': 'order_id_12', 'version': '3', 'sandbox': 0, # sandbox mode, set to 1 to enable it 'server_url': 'http://127.0.0.1:8000/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 pay_callback(request): liqpay = LiqPay(get_liqpay_public_key(), get_liqpay_signature()) data = request.POST.get('data') signature = request.POST.get('signature') sign = liqpay.str_to_sign(get_liqpay_signature() + data + get_liqpay_signature()) if sign == str(signature): qdict = QueryDict('', mutable=True) qdict.update(json.loads(base64.b64decode(data))) form = LiqPayTransactionForm(qdict) if form.is_valid(): form.save() day = qdict.get('info') if isinstance(day, unicode): day = int(day) active_franchise = ActiveFranchise.get_solo() active_franchise.active_franchise += datetime.timedelta(days=day) active_franchise.save() else: print(form.errors) return HttpResponse(status=200) return HttpResponse(status=500)
def liqpay(request): pay_result = json.loads(base64.decodestring(request.POST['data'])) lq = LiqPay(LIQPAY_MERCHANT_ID, LIQPAY_SIGNATURE) signature = lq.str_to_sign(LIQPAY_SIGNATURE + request.POST['data'] + LIQPAY_SIGNATURE) payment = UserPayment.objects.get(order_id=pay_result['order_id']) payment.status = pay_result['status'] payment.transaction_id = pay_result['transaction_id'] if 'sender_phone' in pay_result: payment.sender_phone = pay_result['sender_phone'][-10:] if request.POST['signature'] != signature: payment.status = payment.status + ' signature missmatch' elif payment.status == 'success': user = payment.user if payment.service: if 'base_' in payment.service.name: payment.useroperation_set.add( user.set_ab_status(payment.service, payment.duration, info=u'оплата liqpay')) elif 'adv_' in payment.service.name: payment.useroperation_set.add( payment.advert.activate_service(service=payment.service, term=payment.duration)) elif 'balance' in payment.description: user.current_balance += payment.amount user.save() UserWalletHistory.objects.create(user=user, new_sum=user.current_balance, deposit=payment, info=payment.pay_way) elif payment.status == 'sandbox': payment.annotation = 'test payment' payment.save() response = HttpResponse('ok') return response
def lipay_send(self, remittance, res='yes'): if res == 'yes': liqpay = LiqPay(public_key, private_key) res = liqpay.api( "request", { "action": "hold_completion", "version": "3", "order_id": remittance.liqpay_order_id, "amount": str(float(remittance.amount * 0.01)), }) res = liqpay.api( "request", { "action": "p2p", "version": "3", "phone": '38' + remittance.remittance_customer.usercard.phone_number, "amount": remittance.amount, "currency": "UAH", "description": remittance.payment_desciption, "order_id": str(gen_link()), "receiver_card": remittance.remittance_seller.usercard.card_number, "card": remittance.remittance_customer.usercard.card_number, "card_exp_month": remittance.remittance_customer.usercard.month_card, "card_exp_year": remittance.remittance_customer.usercard.year_card, "card_cvv": remittance.remittance_customer.usercard.cvv_card }) else: liqpay = LiqPay(public_key, private_key) res = liqpay.api( "request", { "action": "hold_completion", "version": "3", "order_id": remittance.liqpay_order_id, "amount": "1", }) return res
def update_payment_status(ptype, task, request, data=None): data = data or {} status = co.IN_PROCESS if ptype == co.LIQPAY: from liqpay.liqpay import LiqPay liq = LiqPay(co.LIQ_PUB_KEY, co.LIQ_PRIV_KEY) liq = liq.api("payment/status", {"order_id": task.id}) try: values = json.dumps(liq) except: values = '{}' if liq.get('result') == 'ok' and liq.get('status') in [ 'success', 'sandbox' ]: fraud = float(task.get_price()) - float(liq.get('amount', 0.00)) > 0.03 status = co.PAID if fraud: status = co.UNDERPAID elif ptype == co.TWOCHECKOUT: import twocheckout # mode: production, mode:sandbox twocheckout.Api.auth_credentials({ 'private_key': co.TWO_PRIV_KEY, 'seller_id': co.TWOSID }) twocheckout.Api.credentials({ 'username': co.TWO_USERNAME, 'password': co.TWO_PASSWORD }) sale_id = data.get('sale_id') try: sale_status = twocheckout.Sale.find({'sale_id': sale_id })['invoices'][0]['status'] amount = twocheckout.Sale.find({'sale_id': sale_id })['invoices'][0]['usd_total'] except (twocheckout.error.TwocheckoutError, KeyError, IndexError): return if sale_status in ['deposited']: fraud = float(task.get_price()) - float(amount) > 0.03 status = co.PAID if fraud: status = co.UNDERPAID payment = Payment(powner=task.owner, ptask=task, values=json.dumps(data), payment_status=status, payment_type=ptype) payment.save()
from liqpay.liqpay import LiqPay liqpay = LiqPay(public_key, private_key) res = liqpay.api("request", { "action" : "invoice_bot", "version" : "3", "amount" : "1", "currency" : "USD", "order_id" : "order_id_1", "phone" : "380950000001" }) print(res)
def calculate_signature(self, data): liqpay = LiqPay(LIQPAY_PUBLIC, LIQPAY_PRIVATE) calc_sign = liqpay.str_to_sign(LIQPAY_PRIVATE.encode() + data.encode() + LIQPAY_PRIVATE.encode()).decode() return calc_sign
from flask import Flask from flask_login import LoginManager from flask_compress import Compress from flask_mail import Mail from models import db from liqpay.liqpay import LiqPay PUBLIC_KEY = 'i18183574422' PRIVATE_KEY = 'DWHmS0mwLkNTIUJJhP6bTmAN4WpKshVJomDSdeZ3' app = Flask(__name__) app.config.from_pyfile('app.cfg') db.init_app(app) compress = Compress(app) login_manager = LoginManager() mail = Mail(app) liqpay = LiqPay(PUBLIC_KEY, PRIVATE_KEY) login_manager.init_app(app) login_manager.session_protection = "strong" login_manager.login_view = "login" login_manager.login_message = "Please LOG IN" login_manager.login_message_category = "info" import views
def calculate_signature(self, data): liqpay = LiqPay(LIQPAY_PUBLIC, LIQPAY_PRIVATE) calc_sign = liqpay.str_to_sign(LIQPAY_PRIVATE.encode() + data.encode() + LIQPAY_PRIVATE.encode()).decode() return calc_sign
def liqpay_subscribe_pay(self, remittances, mode, new_count=''): remittance = remittances[0] now = datetime.now() unique_id = str(gen_link()) if mode == 'update': new_count = new_count['smash'] new_count = new_count[new_count.find('на') + 3:new_count.find(' місяців')] new_count = int(new_count) i_count = remittance.installments_count cop_parts = remittance.count_of_paid_parts amount = remittance.amount first_pay = math.ceil(amount / i_count) if new_count > 12 - cop_parts: return {'smash_data': {'error': 'error'}} elif new_count < 0: return {'smash_data': {'error': 'error'}} else: new_amount = amount - (cop_parts * first_pay) new_amount = math.ceil(new_amount / new_count) liqpay = LiqPay(public_key, private_key) res = liqpay.api( "request", { "action": "subscribe_update", "phone": '38' + str(remittance.remittance_customer.usercard. phone_number), "version": "3", "order_id": str(remittance.liqpay_order_id), "amount": str(new_amount), "currency": "UAH", "description": remittance.payment_desciption, "card": remittance.remittance_customer.usercard.card_number, "card_exp_month": remittance.remittance_customer.usercard.month_card, "card_exp_year": remittance.remittance_customer.usercard.year_card, "card_cvv": remittance.remittance_customer.usercard.cvv_card }) if res['status'] == 'subscribed': remittances.update(liqpay_order_id=res['order_id'], installments_count=cop_parts + new_count) return {'smash_data': {'success': 'success'}} else: return {'smash_data': {'error': 'error'}} elif mode == 'subscribe': if remittance.count_of_paid_parts == None: liqpay = LiqPay(public_key, private_key) res = liqpay.api( "request", { "action": "subscribe", "version": "3", "phone": '38' + str(remittance.remittance_customer.usercard. phone_number), "amount": str( math.ceil(remittance.amount / remittance.installments_count)), "currency": "UAH", "description": remittance.payment_desciption, "order_id": unique_id, "subscribe": "1", "subscribe_date_start": now.strftime("%Y-%m-%d %H:%M:%S"), "subscribe_periodicity": "month", "card": remittance.remittance_customer.usercard.card_number, "card_exp_month": remittance.remittance_customer.usercard.month_card, "card_exp_year": remittance.remittance_customer.usercard.year_card, "card_cvv": remittance.remittance_customer.usercard.cvv_card }) if res['status'] == 'subscribed': remittances.update(liqpay_order_id=unique_id, count_of_paid_parts=1) return {'smash_data': {'success': 'success'}} else: return {'smash_data': {'error': 'error'}} else: return {'smash_data': {'error': 'error'}}
class Pay: def __init__(self): if settings.DEBUG: key_1, key_2 = '', '' else: key_1, key_2 = '', '' self.sign_str = ''.format(key_1, key_2) self.liqpay = LiqPay(key_1, key_2) self.data = '' def font(self, type_font, message): font_array = { 'bold': '<b>' + str(message) + '</b>', 'light': '<i>' + str(message) + '</i>' } return font_array[type_font] def create_pay(self, amount, order_id, type_tr): res = self.liqpay.api( "request", { "action": "invoice_bot", "version": "3", "amount": amount, "currency": "UAH", "order_id": '_'.join([order_id, type_tr]), "phone": "", "server_url": '{}/liqpay'.format(settings.URL_HOST) }) self.data = res['token'] def pay(self, json_data): data = base64.b64decode(json_data['data']).decode('utf-8') sign = self.liqpay.str_to_sign(self.sign_str.format(json_data['data'])) json_string = json.loads(data) print(json_data['signature']) print(sign) self.state = False if (json_data['signature'] == sign and json_string['status'] == 'success'): order = json_string['order_id'].split('_') pay_liq_id = order[0] type_tr = order[1] transactions = Payliq.objects.filter(id=pay_liq_id).first() if (not transactions.state): transactions.state = True transactions.json = str(json_string) transactions.save(update_fields=['state', 'json']) self.client = Clients.objects.filter( id=transactions.client.id).first() self.client.balance += transactions.amount_one self.client.save(update_fields=['balance']) Transactions_log.objects.create(client=self.client, amount=transactions.amount_one, type_transactions='payliq') if type_tr == 'balance': pass elif type_tr == 'task': pass self.state = True