Example #1
0
def dpn_asks_for_money(request):
    if request.method == 'GET':
        alipay_form = PaymentForm(auto_id=False)
        context = {
            "alipay_form": alipay_form,
        }
        return render(request, "pay/payment.html", context)
    # POST method
    site = Site.objects.get_current()
    pay_url = 'http://%s/' % (site.domain)
    form = PaymentForm(request.POST, auto_id=False)
    if not form.is_valid():
        context = {
            "alipay_form": form,
        }
        return render(request, "pay/payment.html", context)
    # alipay form
    item_name = ("Django Alipay example")
    alipay_dict = {
        # base
        "_input_charset":
        'utf-8',
        'notify_url':
        '%salipay/dpn/' % pay_url,
        'return_url':
        '%salipay/dpn/return/' % pay_url,
        # business
        #'seller_email': '',
        'out_trade_no':
        uuid.uuid4().hex,
        'subject':
        item_name,
        'price':
        form.cleaned_data['price'],
        'quantity':
        form.cleaned_data['quantity'],
        # direct pay
        #'extra_common_param': '%s|%d'% (form.cleaned_data['price'], form.cleaned_data['quantity']),
        # partner trade
        'body':
        '%s|%d' % (form.cleaned_data['price'], form.cleaned_data['quantity']),
    }
    alipay_form = AliPayDirectPayForm(auto_id=False, initial=alipay_dict)
    context = {
        'payment_title': ('AliPay Payment'),
        'item_name': item_name,
        'form': form,
        'action': alipay_form.get_action(),
        'paid_form': alipay_form,
    }
    data = get_form_data(alipay_form)
    alipay_form['sign'].field.initial = make_sign(data)
    return render(request, "pay/preview.html", context)
Example #2
0
 def get_form(self, payment):
     '''
     Converts *payment* into a form suitable for Django templates.
     '''
     from forms import PaymentForm
     return PaymentForm(self.get_hidden_fields(payment), self._action,
                        self._method)
Example #3
0
def paymenttest():
    form = PaymentForm()
    if request.method == 'POST' and form.validate_on_submit():

        name = request.form['name']

        credit_type = request.form['credit_type']
        credit_no = request.form['credit_no']
        expir_month = request.form['expir_month']
        expir_year = request.form['expir_year']
        cvv = request.form['cvv']
        money = request.form['money']
        animal_name = request.form['animal_name']

        cursor = db.cursor()
        try:
            #insert the payment data to the database
            cursor.execute(
                "INSERT INTO payment (name,username,credit_type,credit_no,expir_month,expir_year,cvv,money,animal_name) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                (name, session["username"], credit_type, credit_no,
                 expir_month, expir_year, cvv, money, animal_name))
            db.commit()
            cursor.close()
            flash(f'Payment succeed!', 'success')
        except:
            flash(f'Payment failed. Please try again.', 'danger')
        return redirect(url_for('paymenttest'))
    return render_template('paymenttest.html', form=form)
Example #4
0
def get_payment_page(ride_id):
    query = "SELECT r.ride_id, r.time_posted, r.driver_id, b.price" \
            " FROM Ride r INNER JOIN Bids b " \
            "ON r.driver_id = b.driver_id and r.time_posted = b.time_posted and r.passenger_id = b.passenger_id" \
            " WHERE r.ride_id = '{}' and r.passenger_id = '{}'".format(ride_id, current_user.username)

    payment_details = db.session.execute(query).fetchone()

    bid_price = payment_details[3]
    best_promo_query = "WITH MostDiscountedAndAvailablePromos AS (" \
                       "SELECT p.promo_code, p.discount, " \
                       "(p.max_quota - (SELECT COUNT(*) FROM Redeems r WHERE r.promo_code = p.promo_code)) AS amount_left" \
                       " FROM Promo p" \
                       " WHERE p.min_price <= {} AND p.max_quota > (SELECT COUNT(*) FROM Redeems r WHERE r.promo_code = p.promo_code) AND " \
                       "(p.discount = (SELECT MAX(p1.discount) FROM Promo p1) OR p.discount >= {})), " \
                       "PromoStatistics AS (SELECT *, CASE WHEN (discount = (SELECT MIN(discount) FROM MostDiscountedAndAvailablePromos)) THEN 1 ELSE 0 END AS is_least_discount" \
                       " FROM MostDiscountedAndAvailablePromos) " \
                       "SELECT PS1.promo_code, PS1.discount FROM PromoStatistics PS1 WHERE NOT EXISTS(" \
                       "    SELECT 1 FROM PromoStatistics PS2 WHERE (PS2.is_least_discount > PS1.is_least_discount) OR " \
                       "        (PS2.is_least_discount = PS1.is_least_discount AND PS2.amount_left > PS1.amount_left))" \
                       " ORDER BY PS1.promo_code".format(bid_price, bid_price)
    best_promo = db.session.execute(best_promo_query).fetchone()
    best_promo_message = ""
    if best_promo:
        best_promo_message = "Psst! Here's the best possible promo code (${} off) you could use: {}".format(
            best_promo[1], best_promo[0])
        print(best_promo_message)
    form = PaymentForm()

    return render_template("payment.html",
                           details=payment_details,
                           form=form,
                           best_promo_message=best_promo_message)
def confirm(request):
    # The view for payment confirmation
    page_title = "Confirmation"
    if request.method == 'POST':
        payment_form = PaymentForm(request.POST)
        if payment_form.is_valid():
            params_dict = get_posted_parameters(payment_form)
            signature = sign(params_dict)
            params_dict['signature'] = signature
            confirmation_form = ConfirmationForm(params_dict)
            return render_to_response('confirm.html', {
                'page_title': page_title,
                'confirmation_form': confirmation_form,
                'params_dict': params_dict,
                'signature': signature
            },
                                      context_instance=RequestContext(request))
        else:
            from configuration import *
            page_title = "Payment"
            return render_to_response('pay.html', {
                'page_title': page_title,
                'payment_form': payment_form
            },
                                      context_instance=RequestContext(request))
    else:
        return pay(request)
Example #6
0
def create_payment():
    form = PaymentForm()
    if form.validate_on_submit():
        payment = request.get_json()

        if not is_exists_invoices(invoice_list=[
                payment['number_invoice_provider'],
                payment['number_invoice_reciever']
        ]):
            return send_response(
                content={'message': 'Invoices does not exists'},
                status_code=404)

        key = get_payment_key()
        code_confirm = randint(100, 1000)

        db.session.add(
            Payment(key=key,
                    amount_money=payment['amount_money'],
                    number_invoice_provider=payment['number_invoice_provider'],
                    number_invoice_reciever=payment['number_invoice_reciever'],
                    code_confirm=code_confirm,
                    status_id=1))
        db.session.commit()

        send_code_confirm_payment_to_client(code=code_confirm)

        return send_response(content={'message': 'ok'}, status_code=200)

    return send_response(content=form.errors, status_code=400)
Example #7
0
 def payment_form( self ):    
     user    = self.request.user
     profile = self.request.user.get_profile()
     try:
         authorize = Authorize.objects.get( user = user )
     except:
         ready = False
     else:
         ready = True if authorize.payment_profile else False
     
     initial = dict( ready = ready )
     if profile.address:
         if '^' in profile.address:
             billing = profile.address.split('^')
         else:
             billing = profile.address.split(',')
              
         # Make sure there are no errant commas
         for i,bill in enumerate(billing):
             if ',' in bill:
                 billing[i] = bill.replace(',','')
         
         initial.update( dict (  address  = billing[0],
                                 city     = billing[1],
                                 state    = billing[2],
                                 zipcode  = billing[3]
                              )
                       )
 
     return PaymentForm( initial = initial )
def pay(request):
    # The view for submitting payment data
    page_title = "Payment"
    payment_form = PaymentForm()
    return render_to_response('pay.html', {
        'page_title': page_title,
        'payment_form': payment_form
    },
                              context_instance=RequestContext(request))
Example #9
0
def payment():
    form = PaymentForm()
    curr_user = current_user.last_name + ', ' + current_user.first_name + ' ' + current_user.mid_name
    tenant = Tenants.query.filter_by(tenant_status='1').all()
    return render_template('payment.html',
                           curr_user=curr_user,
                           form=form,
                           tenn=tenant,
                           result=search_panel(0)[0],
                           x=search_panel(0)[1],
                           result2=search_panel(1)[0],
                           y=search_panel(1)[1])
Example #10
0
def payment():
    global summ
    form = PaymentForm()
    if request.method == 'POST':
        db_sess = db_session.create_session()
        owner = db_sess.query(Cart.Id).filter(Cart.Owner == flask_login.current_user.id).first()
        res = db_sess.query(CartsProduct).filter(CartsProduct.OwnerCart == owner[0]).all()
        for product in res:
            db_sess.delete(product)
            db_sess.commit()
        summ = 0
        return redirect('/success')
    return render_template('payment.html', title='Оплата', form=form, summ=summ)
Example #11
0
def prepare_firstdatae4_form(request, payment):
    x_fp_timestamp = str(int(time.time()))
    x_amount = "%.2f" % payment.amount
    x_fp_hash = get_fingerprint(str(payment.id), x_fp_timestamp, x_amount)
    x_logo_URL = get_setting("site", "global", "MerchantLogo")

    params = {
        'x_fp_sequence': payment.id,
        'x_fp_timestamp': x_fp_timestamp,
        'x_fp_hash': x_fp_hash,
        'x_amount': x_amount,
        'x_version': '3.1',
        'x_login': settings.MERCHANT_LOGIN,
        'x_invoice_num': payment.invoice_num,
        'x_description': payment.description,
        'x_email_customer': "TRUE",
        'x_email': payment.email,
        'x_cust_id': payment.cust_id,
        'x_first_name': payment.first_name,
        'x_last_name': payment.last_name,
        'x_company': payment.company,
        'x_address': payment.address,
        'x_city': payment.city,
        'x_state': payment.state,
        'x_zip': payment.zip,
        'x_country': payment.country,
        'x_ship_to_first_name': payment.ship_to_first_name,
        'x_ship_to_last_name': payment.ship_to_last_name,
        'x_ship_to_company': payment.ship_to_company,
        'x_ship_to_address': payment.ship_to_address,
        'x_ship_to_city': payment.ship_to_city,
        'x_ship_to_state': payment.ship_to_state,
        'x_ship_to_zip': payment.ship_to_zip,
        'x_ship_to_country': payment.ship_to_country,
        'x_fax': payment.fax,
        'x_phone': payment.phone,
        'x_show_form': 'PAYMENT_FORM',
        'x_logo_URL': x_logo_URL,
    }
    if settings.FIRSTDATA_USE_RELAY_RESPONSE:
        params.update({
            'x_relay_response': 'TRUE',
            'x_relay_url': payment.response_page,
        })

    form = PaymentForm(initial=params)

    return form
Example #12
0
def paymenttable(id, s_id):
    pays = Pays.query.filter(and_(Pays.tenantID==id, Pays.stallID==s_id)).all()
    someNum = Stalls.query.filter_by(stallID=s_id).first()
    tenant_1 = Tenants.query.filter(and_(Tenants.tenantID==id, Tenants.stallID==someNum.stallID)).first()
    typee = Types.query.filter_by(typeID=someNum.typeID).first()
    form= PaymentForm()

    rate_='0'
    if str(datetime.datetime.now())[8]+str(datetime.datetime.now())[9]>='21':
        rate_= (float(someNum.stall_rate)*0.25)

    curr_user = current_user.last_name+', '+current_user.first_name+' '+current_user.mid_name
    print rate_

    remark_re=""
    if form.remark.data=='1':
        remark_re = 'Advance'
    elif form.remark.data=='2':
        remark_re = 'Full'
    elif form.remark.data=='3':
        remark_re = 'Partial'


    if request.method=='POST' and form.validate_on_submit():
        tenant_1.balance=0.0    
        if int(form.amount.data)<int(form.total.data):
            tenant_1.balance = float(form.total.data)-float(form.amount.data)
        dbase.session.add(tenant_1)
        dbase.session.commit()

        uForms = Pays(month=form.month.data,
                        amount=form.amount.data,
                        sCharge=form.sCharge.data,
                        total=form.total.data ,
                        or_no=form.or_no.data,
                        date_issued=now,
                        issued_by=form.issued_by.data,
                        tenantID = tenant_1.tenantID,
                        stallID = someNum.stallID,
                        remark = remark_re
                       )

        dbase.session.add(uForms)
        dbase.session.commit()
        return redirect(url_for("paymenttable", id=id, s_id=s_id))
    if current_user.roleID == 1:
        return render_template('paymenttable_admin.html', page_title='Payment Table', rate_2=someNum.stall_rate+int(rate_)+tenant_1.balance, curr_user=curr_user, rate_=rate_, form=form, pays=pays, id=id, s_id=s_id, stall=someNum, typee=typee, tenant=tenant_1, result=search_panel(0)[0], x=search_panel(0)[1], result2=search_panel(1)[0], y=search_panel(1)[1])
    return render_template('paymenttable.html', page_title='Payment Table', rate_2=someNum.stall_rate+int(rate_)+tenant_1.balance, curr_user=curr_user, rate_=rate_, form =form, pays=pays, id=id, s_id=s_id, stall=someNum, typee=typee, tenant=tenant_1, result=search_panel(0)[0], x=search_panel(0)[1], result2=search_panel(1)[0], y=search_panel(1)[1])
Example #13
0
def payment():
    if request.method == 'POST':
        return "PROBA"
    elif request.method == 'GET':
        orgClientId = "13IN060753"  # 08283439281 13IN060753
        orgOid = "489"
        orgAmount = "91.96"
        orgOkUrl = request.base_url.strip("payment") + "confirmation"
        print(orgOkUrl)
        orgFailUrl = request.base_url.strip("payment") + "confirmation"
        orgTransactionType = "Preauth"
        orgInstallment = ""
        orgRnd = microtime()
        orgCurrency = "941"

        clientId = orgClientId.replace("\\", "\\\\").replace("|", "\\|")
        oid = orgOid.replace("\\", "\\\\").replace("|", "\\|")
        amount = orgAmount.replace("\\", "\\\\").replace("|", "\\|")
        okUrl = orgOkUrl.replace("\\", "\\\\").replace("|", "\\|")
        failUrl = orgFailUrl.replace("\\", "\\\\").replace("|", "\\|")
        transactionType = orgTransactionType.replace("\\", "\\\\").replace(
            "|", "\\|")
        installment = orgInstallment.replace("\\", "\\\\").replace("|", "\\|")
        rnd = orgRnd.replace("\\", "\\\\").replace("|", "\\|")
        rnd = "N2855INH5EM5T7VYL9LA"
        currency = orgCurrency.replace("\\", "\\\\").replace("|", "\\|")
        storeKey = "018Irvas".replace("\\", "\\\\").replace("|", "\\|")

        plainText = clientId + "|" + oid + "|" + amount + "|" + okUrl + "|" + failUrl + "|" + transactionType + "||" + rnd + "||||" + currency + "|" + storeKey
        hashValue = hashlib.sha512(plainText.encode())
        hash = base64.b64encode(str(hashValue).encode())
        print(hash)

        form = PaymentForm(clientid=orgClientId,
                           amount=orgAmount,
                           oid=orgOid,
                           okurl=orgOkUrl,
                           failUrl=orgFailUrl,
                           TranType=orgTransactionType,
                           currency=orgCurrency,
                           rnd=rnd,
                           hash=hash,
                           storetype="3d_pay_hosting",
                           hashAlgorithm="ver2",
                           lang="sr",
                           encoding="utf-8")
        return render_template("payment.html", form=form)
Example #14
0
def payment():
    form = PaymentForm(request.form)
    users = User.query.filter(User.activated).order_by(User.email.asc())

    if request.method == 'POST' and form.validate():
        user = User.query.filter(User.id == request.form['user_id']).first()
        payment = Payment(user, form.value.data)
        dbs.add(payment)
        dbs.commit()
        flash('Payment added successfully.', 'alert alert-success')
        return redirect(url_for('payment'))
    else:
        data = {'nav_urls': get_urls(), 'active_url': url_for('payment')}
        return render_template('payment_add.html',
                               data=data,
                               form=form,
                               users=users)
Example #15
0
File: app.py Project: Twishar/Flask
def payments():

    form = PaymentForm()
    if form.validate_on_submit():

        currency = form.payment_currency.data
        currencies = {'USD': 'usd_api', 'EUR': 'eur_api', 'RUB': 'rub_api'}

        values = [
            request.form['payment_amount'],
            currency_code[request.form['payment_currency']],
            request.form['description']
        ]

        session['values'] = values
        return redirect(url_for('{}'.format(currencies[currency])))

    return render_template('payments.html', form=form)
Example #16
0
def checkout():

    paymentForm = PaymentForm(request.form)

    if request.method == 'POST' and paymentForm.validate():
        paymentDict = {}
        db = shelve.open('storage.db', 'c')
        try:
            paymentDict = db['Payment']
        except:
            print("Error in retrieving Items from storage.db.")
        payment = Payment.Payment(paymentForm.name.data,
                                  paymentForm.cardno.data,
                                  paymentForm.date.data, paymentForm.cvv.data)
        paymentDict[payment.get_name()] = payment
        db['Payment'] = paymentDict
        db.close()
        return redirect(url_for('invoice'))
    return render_template('checkout.html', form=paymentForm)
Example #17
0
 def test_payments_form_with_missing_last_name(self):
     form = PaymentForm({
         'first_name': 'eric',
         'address_line_1': '28201 E. Bonanza St.',
         'address_line_2': 'South Park',
         'address_line_3': '',
         'address_line_4': '',
         'post_code': 'er1 1ic',
         'email_address': '*****@*****.**',
         'credit_card_number': '4242424242424242',
         'cvv': '123',
         'expiry_month': 'Jan',
         'expiry_year': '2037',
         'stripe_id': 'test_stripe_id'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Please fill in this field",
                              form.full_clean())
def test(request):
    """
  Allows for testing the service without actually calling it from code. Aids in testing in
  understanding the parameters as well as testing the success, error, and cancel urls.
  """
    payment = {
        'pid': 'mytestsale',
        'sid': 'tester',
        'amount': 15,
        'success_url': 'http://localhost:8000/success',
        'error_url': 'http://localhost:8000/error',
        'cancel_url': 'http://localhost:8000/cancel'
    }
    token = get_secret_key(payment['sid'])
    checkstr = "pid=%s&sid=%s&amount=%s&token=%s" % (
        payment['pid'], payment['sid'], payment['amount'], token)
    from utils import md5hex
    payment['checksum'] = md5hex(checkstr)
    form = PaymentForm(payment)
    return render_to_response('payment/test.html', {'form': form},
                              context_instance=RequestContext(request))
def pay(request):
    """
  A view that handles a payment request. It checks the HTTP method and the payment
  checksum and in successful cases renders the payment "confirmation" page.
  """
    if request.method != 'POST':  # only HTTP POSTs are allowed
        return HttpResponse("%s Not Allowed" % request.method, status=405)
    try:
        checksum_ok = check_md5(request.POST)
    except:  # the md5 function can fail with non-ascii data
        checksum_ok = False
    if not checksum_ok:
        return HttpResponse("The checksum does not match the data", status=400)
    payment_form = PaymentForm(request.POST)
    if payment_form.is_valid():
        payment = payment_form.save()
        dev = True if 'dev' in request.POST else False
        return render_to_response('payment/pay.html', {
            'payment': payment,
            'dev': dev
        },
                                  context_instance=RequestContext(request))
    else:
        return HttpResponse("Invalid or missing data POSTed", status=400)
Example #20
0
def asks_for_money(request):
    if request.method == 'GET':
        alipay_form = PaymentForm(auto_id=False)
        context = {
            "alipay_form": alipay_form,
        }
        return render_to_response("pay/payment.html",
                                  context,
                                  context_instance=RequestContext(request))
    # POST method
    site = Site.objects.get_current()
    pay_url = 'http://%s/' % (site.domain)
    form = PaymentForm(request.POST, auto_id=False)
    if not form.is_valid():
        context = {
            "alipay_form": form,
        }
        return render_to_response("pay/payment.html",
                                  context,
                                  context_instance=RequestContext(request))
    # alipay form
    item_name = ("Django Alipay example")
    alipay_dict = {
        # base
        "_input_charset":
        'utf-8',
        'notify_url':
        '%salipay/dpn/' % pay_url,
        'return_url':
        '%salipay/return/' % pay_url,
        'service':
        SERVICE[0],
        # business
        #'seller_email': '',
        'out_trade_no':
        uuid.uuid4().hex,
        'subject':
        "xxx",
        'price':
        form.cleaned_data['price'],
        'quantity':
        form.cleaned_data['quantity'],
        'total_fee':
        form.cleaned_data['price'] * form.cleaned_data['quantity'],
        # direct pay
        #'extra_common_param': '%s|%d'% (form.cleaned_data['price'], form.cleaned_data['quantity']),
        # partner trade
        'body':
        '%s|%d' % (form.cleaned_data['price'], form.cleaned_data['quantity']),
    }
    alipay_form = AliPayPartnerTradeForm(auto_id=False, initial=alipay_dict)

    data = get_form_data(alipay_form)
    alipay_form['sign'].field.initial = make_sign(data)
    data = get_form_data(alipay_form)

    url = ALIPAY_GATEWAY + "?"
    for p in data:
        url = url + p + "=" + str(data[p]) + "&"
    url = url[:-1]

    context = {
        'payment_title': ('AliPay Payment'),
        'item_name': item_name,
        'form': form,
        'action': url,
        'paid_form': alipay_form,
    }
    return render_to_response("pay/preview.html",
                              context,
                              context_instance=RequestContext(request))
Example #21
0
def main_form():
    form = PaymentForm()
    if form.validate_on_submit():
        currency = BASE_CURRENCIES.get(form.currency.data)
        # eur/PAY
        if currency == 978:
            # create sign string
            data = {
                'amount': form.amount.data,
                'currency': currency,
                'shop_id': 5,
                'shop_order_id': 4126
            }
            sign = make_sign_string(data)
            data['description'] = form.description.data
            data['sign'] = sign
            session['data'] = data
            app.logger.info(
                CREATE_PAYMENT_LOG_MESSAGE.format('PAY', data['amount'],
                                                  data['currency'],
                                                  data['shop_order_id'],
                                                  datetime.now(),
                                                  data['description']))

            return redirect(url_for('accept_usd'))
        # usd/BILL
        elif currency == 840:
            # create sign string
            data = {
                'shop_amount': str(form.amount.data),
                'shop_currency': 840,
                'shop_id': '5',
                'shop_order_id': '123456',
                'payer_currency': currency,
            }
            sign = make_sign_string(data)
            # maybe i should create function for creating request. But I thought it was redundant
            data['description'] = form.description.data
            data['sign'] = sign

            app.logger.info(
                CREATE_PAYMENT_LOG_MESSAGE.format('BILL', data['shop_amount'],
                                                  data['payer_currency'],
                                                  data['shop_order_id'],
                                                  datetime.now(),
                                                  data['description']))

            data = json.dumps(data)
            headers = {'Content-type': 'application/json'}
            response = requests.post(CREATE_BILL_URL,
                                     data=data,
                                     headers=headers)
            response_data = json.loads(response.content.decode('utf-8'))
            if response_data['result']:
                url = response_data['data']['url']
                return redirect(url)
        # rub/INVOICE
        elif currency == 643:
            # create sign string
            data = {
                "amount": str(form.amount.data),
                "payway": PAYWAY_RUB,
                'shop_id': 5,
                'shop_order_id': 123456,
                "currency": str(currency)
            }
            sign = make_sign_string(data)
            data['description'] = form.description.data
            data['sign'] = sign

            app.logger.info(
                CREATE_PAYMENT_LOG_MESSAGE.format('BILL', data['amount'],
                                                  data['currency'],
                                                  data['shop_order_id'],
                                                  datetime.now(),
                                                  data['description']))

            data = json.dumps(data)
            headers = {'Content-type': 'application/json'}
            response = requests.post(CREATE_INVOICE_URL,
                                     data=data,
                                     headers=headers)
            response_data = json.loads(response.content.decode('utf-8'))
            if response_data['result']:
                session['data'] = response_data
                return redirect(url_for('accept_rub'))
    return render_template('base_form.html', form=form)
Example #22
0
def pay(ride_id):
    query = "SELECT r.ride_id, r.time_posted, r.driver_id, b.price" \
            " FROM Ride r INNER JOIN Bids b " \
            "ON r.driver_id = b.driver_id and r.time_posted = b.time_posted and r.passenger_id = b.passenger_id" \
            " WHERE r.ride_id = '{}' and r.passenger_id = '{}'".format(ride_id, current_user.username)
    update_ride_payment_status_query = "UPDATE Ride SET is_paid = TRUE WHERE ride_id = '{}'".format(
        ride_id)

    payment_details = db.session.execute(query).fetchone()
    form = PaymentForm()

    if form.is_submitted:
        promo_code = form.promo_code.data
        promo_query = "SELECT * from promo WHERE promo_code = '{}'".format(
            promo_code)
        exists_promo = db.session.execute(promo_query).fetchone()
        current_bid_price = payment_details[3]
        form.promo_code.errors = []
        is_paid_ride_query = "SELECT * FROM Ride WHERE is_paid=TRUE and ride_id = {}".format(
            ride_id)
        is_paid_ride = db.session.execute(is_paid_ride_query).fetchone()

        if is_paid_ride:
            form.message = "You already paid for the ride!"
        elif exists_promo:
            num_used_for_promo_query = "SELECT COUNT(*) FROM Redeems WHERE promo_code = '{}'".format(
                promo_code)
            num_used_for_promo = db.session.execute(
                num_used_for_promo_query).fetchone()[0]
            max_quota = exists_promo[1]
            min_price_to_use_promo = exists_promo[2]
            discount_amount = exists_promo[3]

            if num_used_for_promo >= max_quota:
                form.promo_code.errors.append(
                    "Promo code has been fully redeemed!")
            elif current_bid_price < min_price_to_use_promo:
                form.promo_code.errors.append(
                    "Your ride does not fulfill the minimum price of ${} "
                    "to use this promo!".format(min_price_to_use_promo))
            else:
                redeems_insertion_query = "INSERT INTO redeems(ride_id, promo_code, username) " \
                                          "VALUES ('{}', '{}', '{}')".format(ride_id, promo_code, current_user.username)
                db.session.execute(redeems_insertion_query)
                db.session.execute(update_ride_payment_status_query)
                db.session.commit()

                discounted_price = current_bid_price - discount_amount

                # handle discount that exceeds the bid_price
                if discounted_price < 0:
                    discount_amount += discounted_price
                    discounted_price = 0

                form.message = "Payment of ${} (Discount of ${}) Successful!".format(
                    discounted_price, discount_amount)

        elif not promo_code:  # user did not type promo code
            db.session.execute(update_ride_payment_status_query)
            db.session.commit()
            form.message = "Payment of ${} Successful!".format(
                current_bid_price)
        else:
            form.promo_code.errors.append('Promo code does not exists!')

    return render_template("payment.html", details=payment_details, form=form)
Example #23
0
def charge(request):
    if request.method == "POST":
        form = PaymentForm(request.POST)
 
        if form.is_valid(): # charges the card
Example #24
0
def submit():

    form = PaymentForm(request.form)

    log.info('Incoming payment. Details:')

    if form.validate():
        amount = str(round(form.data['amount'], 2))  # 100 -> 100.00
        c = form.data['currency']

        payment_data = {
            'amount': amount,
            'currency': c,
            'shop_id': get_shop_id(),
            'shop_order_id': get_shop_order_id(),
        }

        d = form.data.get('description')
        if d:
            payment_data['description'] = d

        log.critical(payment_data)

        if c == available_currencies['EUR']:

            payment_data['sign'] = generate_sign(**payment_data)

            log.info('Rendering "Pay method" form.')

            return render_template('payform_pay.html', **payment_data)

        elif c == available_currencies['RUB']:
            payment_data['payway'] = 'payeer_rub'
            payment_data['sign'] = generate_sign(**payment_data)

            log.info('Posting to Piastrix for confirmation')

            h = {'Content-Type': 'application/json'}
            r = requests.post('https://core.piastrix.com/invoice/create',
                              data=json.dumps(payment_data),
                              headers=h)
            res = r.json()
            data = res['data']

            if res['result'] is True and res['message'] == 'Ok':

                log.info(data)
                log.info('Request succeded. Rendering "Invoice method" button')
                return render_template('payform_invoice.html',
                                       data=data)

            else:
                log.error('Request failure. Details:')
                log.error(res)
                return 'Malformed request', 403

        elif c == available_currencies['USD']:

            payment_data['shop_amount'] = payment_data.pop('amount')
            payment_data['shop_currency'] = payment_data.pop('currency')
            payment_data['payer_currency'] = payment_data['shop_currency']

            payment_data['sign'] = generate_sign(**payment_data)

            log.info('Posting to Piastrix for confirmation')

            h = {'Content-Type': 'application/json'}
            r = requests.post('https://core.piastrix.com/bill/create',
                              data=json.dumps(payment_data),
                              headers=h)
            res = r.json()
            data = res['data']

            if res['result'] is True and res['message'] == 'Ok':

                log.info('Request succeeded. Redirecting via "Bill method"')
                return redirect(data['url'], code=302)

            else:
                log.error('Request failed. Details:')
                log.error(res)
                return f'Malformed request. Details:<br>{res}', 403

    else:
        errs = {}
        for f, e in form.errors.items():
            errs[f] = e

        log.error('Bad input:')
        log.error(errs)

        return f'Bad input<br>{errs}', 403