def post(self, request): # Create order body = parse_body(request) user = User.objects.get(id=body['user']) products = [{ "instance": Product.objects.get(id=product["id"]), "options": product["options"], } for product in body["products"]] order = Order(user=user, ) order.save() for product in products: order.products.add(product["instance"]) payment = Payment( order=order, method='Credit card', value=self.sum_products_prices(products), ) payment.save() charge = stripe.Charge.create( amount=self.format_price(self.sum_products_prices(products)), currency='usd', description='Order #' + str(order.id), customer=user.creditcard.customer_id, ) response = {"id": order.id, "total": payment.value} return JsonResponse(response, status=201)
def free_subscription(uid): """ Function to make free sunscription for user""" user_detail = User.by_id(uid) dash_redirect = url_for('userbp.dashboard') if int(uid) != int(current_user.id): dash_redirect = url_for('userbp.customers') if user_detail.payment_status == 1: configure_paypal() pay_info = Payment.byuser_id(uid) billing_agreement_detail = BillingAgreement.find( pay_info.PaymentDetail.billing_aggrement_id) cancel_note = {"note": "Canceling the agreement"} cancel_states = ['Active', 'Suspended'] if billing_agreement_detail.state in cancel_states: if billing_agreement_detail.cancel(cancel_note): user_detail.payment_status = 2 flash(MAKE_FREE_USER, 'success') flash(CANCEL_PLAN, 'success') else: errorlog.error('Cancel Current Plan Error', details=str(billing_agreement_detail.error)) flash(CANCEL_PLAN_ERROR, 'danger') else: errorlog.error('Cancel Current Plan Error', details=str(billing_agreement_detail.error)) flash(PLAN_NOT_ACTIVE, 'danger') else: user_detail.payment_status = 2 flash(MAKE_FREE_USER, 'success') db.session.commit() return redirect(dash_redirect)
def create_order(): data = request.get_json(force=True) user_id = data.get("user_id") item_id = data.get("item_id") shipping_addr = date.get("shipping_addr") total_amt = data.get("total_amt") pdate = datetime.now() user = User.query.filter_by(user_id=user_id).first() if user is None: abort(404, "No user found with specified ID") if ( user_id is None or item_id is None or shipping_addr == "" or total_amt is None or pdate is None ): abort(400, "Cannot have empty fields for payment") new_payment = Payment( user_id=user_id, item_id=item_id, shipping_addr=shipping_addr, total_amt=total_amt, pdate=pdate, ) db.session.add(new_item) db.session.commit() return jsonify(new_item.serialize)
def upload(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) filepath = os.path.join(UPLOAD_FOLDER, filename) file.save(filepath) # if not process_bank_statement(filepath): # return "Are you sure you uploaded a bank statement? SpendAnalyzer was not able to parse it." messages = filepath df = parser.parse_bank_statement(filepath) categorize.categorize(df) for index, row in df.iterrows(): p = Payment(date=row.Date, desc=row.Desc, amount=row.Amount, balance=row.Balance, category=row.Category) db.session.add(p) db.session.commit() return redirect(url_for('.dashboard')) # return redirect(request.url) return render_template("start.html")
def processPayment(id): order = Order.query.get_or_404(request.form.get("id")) if order.entry != current_user.entry: abort(403) if order.status != OrderStatus.incomplete: flash( "You can't modify an order that has been completed, or has a payment pending", "danger", ) return redirect(url_for("orders.viewOrder", id=order.id)) payment = order.payment if order.payment else Payment(order=order) method = request.form.get("method") if method == "online": payment.method = PaymentMethod.stripe payment.fee = math.ceil(((order.subtotal * 0.014) + 0.20) * 100) / 100 elif method == "bank": payment.method = PaymentMethod.BACS payment.fee = 0 elif method == "cheque": payment.method = PaymentMethod.cheque payment.fee = 0 else: flash("Invalid payment method selected", "danger") return redirect(url_for("orders.addPaymentToOrder", id=order.id)) db.session.add(payment) db.session.commit() return redirect(url_for("orders.completePayment", id=order.id))
def order(): if (request.form.get('pay')): if not request.form.getlist('productlist'): error = "Please select the product!" contexts = dict(cid=request.form.get('pay')) return render_template("products.html", error=error, **contexts) else: global totalprice totalprice = 0 cid = request.form.get('pay') value = request.form.getlist('productlist') ename = [] global price price = [] for i in range(len(value)): totalprice = totalprice + float(value[i]) print "totalprice", totalprice newcid = json.loads(cid) pay = Payment(newcid, totalprice) db.session.add(pay) db.session.commit() payments = Payment.query.all() print payments context = dict(totalprice=totalprice) return render_template("members.html", key=stripe_keys['publishable_key'], **context)
def save_credit_card_response(billing_agreement_response, payment_id): """ Function to save credit card response """ try: payment_token = payment_id plans = Subscription.get_all() if 'id' in billing_agreement_response: pdobj = PaymentDetail( amount=plans.subscription_price, subscription_id=plans.id, payment_status='Success', payment_date=func.now(), billing_aggrement_id=billing_agreement_response.id, payment_token=payment_token, payment_mode='credit_card') db.session.add(pdobj) db.session.commit() pobj = Payment(user_id=current_user.id, payment_detail_id=pdobj.id, created_at=func.now(), updated_at=func.now()) db.session.add(pobj) current_user.payment_status = True db.session.commit() return True except Exception as err: errorlog.error('Credit Card response Error', details=str(err)) return render_template('error.html', message="Error!")
def cancel_subscription(): json_dict = request.json user_id = json_dict['user_id'] userSub = UserSubscription.get_subscription(user_id=user_id) userSubscription = {} if len(userSub) > 0: userSubscription = userSub[0] subscriptionId = userSubscription.subscription_id user = User.query.get(user_id) stripe.api_key = ConfigValues.get_config_value('STRIPE_SK') try: # Cancel the subscription by deleting it deletedSubscription = stripe.Subscription.delete(subscriptionId) print(deletedSubscription) user_subscription_dict = {} user_subscription_dict['user_id'] = user.id user_subscription_dict['subscription_id'] = deletedSubscription['id'] user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id s_date = datetime.fromtimestamp(deletedSubscription['current_period_start']) user_subscription_dict['current_start_date'] = s_date e_date = datetime.fromtimestamp(deletedSubscription['current_period_end']) user_subscription_dict['current_end_date'] = e_date user_subscription_dict['application_fee_percent'] = deletedSubscription['application_fee_percent'] user_subscription_dict['billing_cycle_anchor'] = deletedSubscription['billing_cycle_anchor'] user_subscription_dict['billing_thresholds'] = deletedSubscription['billing_thresholds'] user_subscription_dict['cancel_at'] = deletedSubscription['cancel_at'] user_subscription_dict['cancel_at_period_end'] = deletedSubscription['cancel_at_period_end'] ca_date = datetime.fromtimestamp(deletedSubscription['canceled_at']) user_subscription_dict['canceled_at'] = ca_date user_subscription_dict['collection_method'] = deletedSubscription['collection_method'] userSubscription.update(user_subscription_dict) Payment.send_subscription_cancelled_email(user_email=user.email) if datetime.now() > userSubscription.current_end_date: # else, there is another check when user makes an order and sets to 0 if it fails this validation user.update({'subscribed':0}) return jsonify(deletedSubscription).json except Exception as e: return jsonify(error=str(e)), 403
def payments_in_group(group_id): group = Group.query.get_or_404(group_id) can_confirm = current_user.is_master if 'submit' in request.form: for month_number in range(group.start_month, group.end_month + 1): ps = group.payments_in_month(month_number) payments = dict() for p in ps: payments[p.student_in_group_id] = p for student_in_group in group.students_in_group_in_month(month_number): new_value = request.form.get('p_{}_{}'.format(month_number, student_in_group.id), 0, type=int) if new_value < 0: new_value = 0 max_value = group.section.price - student_in_group.discount if new_value > max_value: new_value = max_value payment = payments.get(student_in_group.id) is_cash = 'cash_{}_{}'.format(month_number, student_in_group.id) in request.form is_confirmed = 'conf_{}_{}'.format(month_number, student_in_group.id) in request.form comment = request.form.get('comment_{}_{}'.format(month_number, student_in_group.id), '') if payment is not None: if not payment.confirmed: payment.value = new_value payment.cash = is_cash payment.comment = comment if can_confirm: payment.confirmed = is_confirmed else: db.session.add(Payment(student_in_group=student_in_group, month=month_number, value=new_value, cash=is_cash, confirmed=can_confirm and is_confirmed, comment=comment)) flash('оплата в группе {} сохранена.'.format(group.name)) return redirect(url_for('payments.payments_in_group', group_id=group_id)) pd = payments_info(group) total_payments = 0 confirmed_payments = 0 non_zero_payments = 0 students_in_month = dict() for month_number in range(group.start_month, group.end_month + 1): students_count = group.students_in_group_in_month(month_number).count() total_payments += students_count confirmed_payments += pd.confirmed_count_months[month_number] non_zero_payments += pd.non_zero_count_months[month_number] students_in_month[month_number] = students_count if current_user.is_teacher: sum_not_confirmed_by_group = get_sum_not_confirmed_by_group(current_user.teacher.id) sum_not_confirmed_all = get_sum_not_confirmed_teacher(current_user.teacher.id) else: sum_not_confirmed_by_group = None sum_not_confirmed_all = None students_in_group = group.students_in_group_by_fio.all() return render_template('payments/payments_in_group.html', group=group, students_in_group=students_in_group, payments=pd.values, confirmed=pd.confirmed, cash=pd.cash, comments=pd.comments, confirmed_count_months=pd.confirmed_count_months, confirmed_count_students=pd.confirmed_count_students, non_zero_count_months=pd.non_zero_count_months, non_zero_count_students=pd.non_zero_count_students, total_payments=total_payments, confirmed_payments=confirmed_payments, non_zero_payments=non_zero_payments, students_in_month=students_in_month, can_confirm=can_confirm, sum_not_confirmed_by_group=sum_not_confirmed_by_group, sum_not_confirmed_all=sum_not_confirmed_all)
def db_add_order(amount, currency, description): """add order to database""" new_payment = Payment(description=description, amount=amount, currency=currency) db.session.add(new_payment) db.session.commit() shop_order_id = Payment.query.all()[-1].id return shop_order_id
def my_account(): """ Function to view my account having info abount subscription and payment history """ try: get_uid = request.args.get('userid', default=None, type=int) uid = current_user.id if get_uid is not None and current_user.user_type == 'admin': uid = get_uid userinfo = User.by_id(uid) trans_list = None billing_agreement = None account_detail = None if userinfo.payment_status == 1: account_detail = Payment.byuser_id(userinfo.id) get_date = datetime.strptime(str( userinfo.created_at), '%Y-%m-%d %H:%M:%S') - timedelta(days=1) start_date, end_date = get_date.strftime('%Y-%m-%d'), \ datetime.now().strftime("%Y-%m-%d") account_detail = Payment.byuser_id(userinfo.id) configure_paypal() billing_agreement = BillingAgreement.find( account_detail.PaymentDetail.billing_aggrement_id) transactions = billing_agreement.search_transactions( start_date, end_date) trans_list = transactions.agreement_transaction_list if trans_list is None: trans_list = [] credit_card_form = payment_form.credit_card() plan = Subscription.get_all(True) credit_card_form.payment_token.data = plan.subscription_id return render_template('payment/my_account.html', account_detail=account_detail, transactions=trans_list, agreement=billing_agreement, userinfo=userinfo, plan=plan, ccform=credit_card_form) except Exception as err: errorlog.error('My Account Error', details=str(err)) return render_template('error.html', message="Error!")
def payBillForm(): form = PayBillForm() allCards = Card.query.all() cards = [] for card in allCards: if card.cardHolderRef == current_user.id: cards.append(card) if form.validate_on_submit(): mycard = request.form.get('card') mycard = mycard.split(",") amount = float(form.amount.data) * 100 str(amount) payment = { "amount": form.amount.data, "description": form.description.data, "card": { "number": mycard[0], "cvv": mycard[1], "expMonth": mycard[2], "expYear": mycard[3] } } ###############Add payment to it's database here######### dbpayment = Payment(company="Utility", amount=form.amount.data, description=form.description.data, paymentMakerRef=current_user.id, paymentCardRef=mycard[0]) db.session.add(dbpayment) db.session.commit() ###############Add payment to it's database here######### payment = simplify.Payment.create(payment) # card = Card(addressState=form.addressState.data,expMonth=form.expMonth.data, expYear=form.expYear.data, # addressCity=form.addressCity.data,addressZip=form.addressZip.data,cvv=form.cvv.data, number=form.number.data) flash('Payment was succesfully!') amount = form.amount.data #sms(amount) user = Customer.query.get(current_user.id) email = user.email send_email('Payment Recieved', [email], render_template("payment_email.html", fname=user.fname)) return redirect(url_for('index')) return render_template('payBillForm.html', title='Pay Bill', form=form, cards=cards)
def add_payment(): persons = Person.objects.all() payments = PaymentType.objects.all() payers = Payer.objects.all() for person in persons: # С вероятностью 10% он ничего не получает if random.randint(0, 10) >= 9: continue # А тут получает for i in range(random.randint(10, 30)): pay = Payment() pay.person = person pay.payment_sum = random.randint(500, 10000) pay.payer = random.choice(payers) pay.payment_type = random.choice(payments) pay.payment_date = datetime.datetime(year=random.choice( (2015, 2016, 2017, 2018)), month=random.randint(1, 12), day=random.randint(1, 27)) pay.save()
def handle_payment(): """ Handle payment redirect from payment page """ logger.debug('Handling payment with request data {0}'.format(request.args)) request_id = request.args.get('cps_context_id', 'None') payment = db_session.query(Payment).get(request_id) if not payment: logger.error('Handling not existing payment! Aborting.') abort(404) if request.args.get('status') != 'success': logger.warning('Receive unsuccessfull payment {0}'.format(payment)) payment.status = PaymentStatus.refused db_session.add(payment) db_session.commit() Payment.notify(payment.payment_id) return redirect(REDIRECT_BOT_URL) logger.debug('Starting polling thread for payment {0}'.format(payment)) thread = threading.Thread(target=Payment.poll_payment, args=(INSTANCE_ID, request_id)) thread.start() return redirect(REDIRECT_BOT_URL)
def create_payment_checkout(bus_id): bus = Bus.query.filter_by(id=bus_id).first() create_passenger_booking_form = CreatePassengerBookingForm( data=request.form, bus=bus) profile = None if current_user.is_authenticated: profile = current_user.profile if create_passenger_booking_form.validate_on_submit(): # create payment checkout data = create_passenger_booking_form.data grid_id = data.get("grid_id") pricing_id = data.get("pricing_id") passenger_name = data.get("passenger_name") passenger_email = data.get("passenger_email") telephone_code = data.get("telephone_code") passenger_telephone = data.get("passenger_telephone") telephone = join_telephone(telephone_code, passenger_telephone) grid = Grid.query.filter_by(id=grid_id).first() pricing = Pricing.query.filter_by(id=pricing_id).first() app_charge = round(pricing.price * app.config.get("APP_CHARGE")) payment = Payment(amount=pricing.price, app_charge=app_charge, method="ONLINE", passenger_name=passenger_name, passenger_email=passenger_email, passenger_telephone=telephone, grid_number=grid.number, bus_number=bus.number, bus_id=bus.id, grid_id=grid.id, company=bus.company, profile=profile, journey=bus.journey, pricing=pricing) db.session.add(payment) db.session.commit() return redirect(url_for('payment.get_payment', payment_id=payment.id)) return render_template( "bus/passenger-bus.html", bus=bus, create_passenger_booking_form=create_passenger_booking_form)
def create_payments_for_all_students(group): for month_number in range(group.start_month, group.end_month + 1): payment_exist_student_in_group_ids = [ p.student_in_group_id for p in group.payments_in_month(month_number) ] for student_in_group in group.students_in_group_in_month(month_number): if student_in_group.id not in payment_exist_student_in_group_ids: db.session.add( Payment(student_in_group=student_in_group, month=month_number, value=0, cash=True, confirmed=False, comment="")) db.session.commit()
def execute(): """ Function to execute plan after redirecting from paypal site after customer agreement """ try: configure_paypal() payment_token = request.args.get('token', '') billing_agreement_response = BillingAgreement.execute(payment_token) plans = Subscription.get_all() action = url_for('userbp.dashboard') billing_action = url_for('paymentbp.billing') if 'id' in billing_agreement_response: pdobj = PaymentDetail( amount=plans.subscription_price, subscription_id=plans.id, payment_status='Success', payment_date=func.now(), billing_aggrement_id=billing_agreement_response.id, payment_token=payment_token, payment_mode='paypal') db.session.add(pdobj) db.session.commit() user_id = current_user.id if 'app_user_id' in session: user_id = session['app_user_id'] session.pop('app_user_id') action = url_for('userbp.dashboard', userid=user_id) billing_action = url_for('paymentbp.billing', userid=user_id) pobj = Payment(user_id=user_id, payment_detail_id=pdobj.id, created_at=func.now(), updated_at=func.now()) db.session.add(pobj) get_user = User.by_id(int(user_id)) get_user.payment_status = True db.session.commit() flash(PLAN_EXECUTED, 'success') return redirect(action) else: flash(PLAN_EXECUTED_ERROR, 'danger') return redirect(billing_action) except Exception as err: errorlog.error('Subscribe Error', details=str(err)) return render_template('error.html', message="Error!")
def create_payment(booking): grid = booking.booked_grid bus = grid.bus company = bus.company branch = get_current_branch() payment = Payment(reference=generate_reference(), amount=booking.fare, method="CASH", passenger_name=booking.passenger_name, passenger_telephone=booking.passenger_telephone, branch_name=branch.name, company_name=company.name, grid_number=grid.number, bus_number=bus.number, company=company, bus=bus, journey=bus.journey, pricing=booking.pricing, grid_id=grid.id) booking.payment = payment db.session.add(payment)
def cancel_current_plan(): """ Function to cancel the current plan """ try: get_uid = request.args.get('userid', default=None, type=int) uid = current_user.id profile_redirect = url_for('userbp.profile') dashboard_redirect = url_for('userbp.dashboard') if get_uid is not None and current_user.user_type == 'admin': uid = get_uid profile_redirect = url_for('userbp.profile', userid=uid) dashboard_redirect = url_for('userbp.dashboard', userid=uid) userinfo = User.by_id(uid) if userinfo.payment_status != 1: flash(PLAN_SUBSCRIPTION_ERROR, 'danger') return redirect(profile_redirect) configure_paypal() pay_info = Payment.byuser_id(uid) billing_agreement_detail = BillingAgreement.find( pay_info.PaymentDetail.billing_aggrement_id) cancel_note = {"note": "Canceling the agreement"} cancel_states = ['Active', 'Suspended'] if billing_agreement_detail.state in cancel_states: if billing_agreement_detail.cancel(cancel_note): userinfo.payment_status = 0 db.session.commit() flash(CANCEL_PLAN, 'success') return redirect(dashboard_redirect) else: errorlog.error('Cancel Current Plan Error', details=str(billing_agreement_detail.error)) flash(CANCEL_PLAN_ERROR, 'danger') else: flash(PLAN_NOT_ACTIVE, 'danger') except Exception as err: errorlog.error('Cancel Current Plan Error', details=str(err)) flash(CANCEL_PLAN_ERROR, 'danger') return redirect(profile_redirect)
def create_payment(): """ Create payment endpoint """ logger.debug('Request for paymnet creation') if not request.json or 'amount' not in request.json or 'merchant_id' not in request.json: logger.debug( 'Not enough data to serve the request! Request data: {0}'.format( request.json)) abort(400) amount = request.json['amount'] merchant_id = request.json['merchant_id'] payment = Payment.create_payment(merchant_id, amount, INSTANCE_ID, app.config['WALLET']) logger.debug('Payment {0} created'.format(payment)) if not payment: return jsonify({'error': 'Failed to create payment instance'}), 420 return jsonify({ 'payment_url': payment.payment_url, 'id': payment.payment_id }), 201
def balance(loan_id): if re.match(loan_id_re, loan_id) is None: response = jsonify({"error": "Specified loan id is not valid"}) response.status_code = 400 return response if len(request.args) != 1: return generate_error_message("Invalid number of arguments", 400) date = request.args.get('date') if date is None: return generate_error_message("Invalid query parameter", 400) transformed_date = ciso8601.parse_datetime(date) if transformed_date is None: return generate_error_message("Specified date doesn't follow the ISO8601 norm", 400) if transformed_date.tzinfo is None or transformed_date.tzinfo.utcoffset(transformed_date) is None: transformed_date = transformed_date.replace(tzinfo=pytz.UTC) db_loan = Loan.get_loan(loan_id) if db_loan is None: return generate_error_message("Specified loan id doesn't exist", 400) total_to_pay = db_loan.amount db_loan_payments = Payment.get_loan_payments(loan_id) for payment in db_loan_payments: if payment.payment == "made" and payment.date <= transformed_date: total_to_pay -= payment.amount response = jsonify({"balance": float(round(total_to_pay, 2))}) response.status_code = 200 return response
def pay(identifier): try: payment = Payment( main=request.form['main'], interest=request.form['interest'], payment_date=datetime.strptime(request.form['payment_date'], "%Y-%m-%d"), notes=request.form['notes'], debtor_id=identifier, ) db.session.add(payment) db.session.commit() response = jsonify({"success": True}) response.status_code = 200 except Exception as e: db.session.rollback() print(e) response = jsonify({"success": False}) response.status_code = 500 return response
def post(self): data = json.loads(request.data) if data.get('pay_amount') is None: return make_response( jsonify({"error": { "message": "BAD REQUEST" }}), 400) if data.get('pay_currency') not in CURRENCY: return make_response( jsonify({"error": { "message": "BAD REQUEST" }}), 400) pay = Payment(pay_amount=data.get('pay_amount'), pay_currency=data.get('pay_currency'), description=data.get('description')) db.session.add(pay) db.session.commit() # Required data set for sending send_data = dict() if pay.pay_currency == 'EUR': send_data['amount'] = str(pay.pay_amount) send_data['currency'] = str(CURRENCY_CODE.get(pay.pay_currency)) send_data['description'] = pay.description send_data['shop_id'] = str(SHOP_ID) send_data['shop_order_id'] = str(pay.id) send_data['sign'] = make_sign(EUR_PARAMS, send_data) send_data['url'] = URL_EN_PAY # Save logs pay_log_save(pay.id, json.dumps(send_data)) logging.info(f'EUR -- send_data: {send_data}') return make_response(jsonify(send_data), 200) if pay.pay_currency == 'USD': send_data['payer_currency'] = str( CURRENCY_CODE.get(pay.pay_currency)) send_data['shop_amount'] = str(pay.pay_amount) send_data['shop_currency'] = str( CURRENCY_CODE.get(pay.pay_currency)) send_data['shop_id'] = str(SHOP_ID) send_data['shop_order_id'] = str(pay.id) send_data['sign'] = make_sign(USD_PARAMS, send_data) # send data resp = sender(send_data, URL_BILL_CRATE) logging.info(f'USD -- sender: {send_data}') # Save logs pay_log_save(pay.id, json.dumps(send_data), json.dumps(resp)) logging.info(f'USD -- send_data: {send_data}') if resp.get('error'): return make_response(resp) return make_response(jsonify({"url": resp.get('url')}), 200) if pay.pay_currency == 'RUB': send_data['amount'] = str(pay.pay_amount) send_data['currency'] = str(CURRENCY_CODE.get(pay.pay_currency)) send_data['payway'] = PAYWAY send_data['shop_id'] = str(SHOP_ID) send_data['shop_order_id'] = str(pay.id) send_data['sign'] = make_sign(RUB_PARAMS, send_data) # send data resp = sender(send_data, URL_INVOICE_CRATE) logging.info(f'RUB -- sender: {send_data}') # save logs pay_log_save(pay.id, json.dumps(send_data), json.dumps(resp)) logging.info(f'RUB -- send_data: {send_data}') if resp.get('error'): return make_response(resp) response = jsonify({ "data": resp.get('data'), "method": resp.get('method'), "url": resp.get('url') }) return make_response(response, 200)
def payments(loan_id): request_data = request.get_json() if re.match(loan_id_re, loan_id) is None: response = jsonify({"error": "Specified loan id is not valid"}) response.status_code = 400 return response try: validate(request_data, schemas["payment"]) except ValidationError as validation_error: return generate_error_message(validation_error.message, 400) date = ciso8601.parse_datetime(request_data["date"]) if date is None: return generate_error_message("Specified date doesn't follow the ISO8601 norm", 400) if date.tzinfo is None or date.tzinfo.utcoffset(date) is None: date = date.replace(tzinfo=pytz.UTC) db_loan = Loan.get_loan(loan_id) if db_loan is None: return generate_error_message("Specified loan id doesn't exist", 400) db_loan_installment = Loan.calculate_loan_payment(db_loan.rate, db_loan.term, db_loan.amount) if request_data["amount"] != db_loan_installment: return generate_error_message( "Specified amount is not equal to monthly installment of {}".format(db_loan_installment), 400) db_loan_payments = Payment.get_loan_payments(loan_id) if len(db_loan_payments) != 0: made_payments = [] for payment in db_loan_payments: if payment.payment == "made": made_payments.append(payment) if len(made_payments) == db_loan.term: return generate_error_message("This loan has already been paid", 409) db_loan_last_payment = db_loan_payments[-1] months = relativedelta.relativedelta(date, db_loan_last_payment.date).months if abs(months) < 1: return generate_error_message( "Payments work in a monthly base. Since last payment {} one month hasn't passed".format( db_loan_last_payment.date), 409) request_data = request.get_json() payment = request_data["payment"] amount = request_data["amount"] payment = Payment(id=str(uuid.uuid4()), loan_id=loan_id, payment=payment, date=date, amount=amount) payment.save() response = jsonify({"message": "Payment successful"}) response.status_code = 201 return response
def get_new_payments(project_id): # Loop over all monetary accounts (i.e., all IBANs belonging to one # Bunq account) for monetary_account in get_all_monetary_account_active(project_id): new_payments_count = 0 new_payments = True payments = None # Use a while loop because of pagination; stop when we find a # payment that already exists in our database or if no new # payments are found or in case of an error while new_payments: # Retrieve payments from Bunq try: if payments: params = payments.pagination.url_params_previous_page else: params = {'count': 10} # Bunq allows max 3 requests per 3 seconds sleep(1) payments = endpoint.Payment.list( monetary_account_id=monetary_account._id_, params=params) except Exception as e: app.logger.error( "Getting Bunq payments resulted in an exception:\n" + repr(e)) new_payments = False continue if not payments.value: new_payments = False continue # Save payments to database for full_payment in payments.value: try: payment = _transform_payment(full_payment) except Exception as e: app.logger.error( "Transforming a Bunq payment resulted in an exception:\n" + repr(e)) new_payments = False continue try: existing_payment = Payment.query.filter_by( bank_payment_id=payment['bank_payment_id']).first() if existing_payment: new_payments = False else: project = Project.query.filter_by( iban=payment['alias_value']).first() if project: payment['project_id'] = project.id subproject = Subproject.query.filter_by( iban=payment['alias_value']).first() if subproject: payment['subproject_id'] = subproject.id # Remove these values that sometimes occur in Bunq # payments as we don't use them if 'scheduled_id' in payment: del payment['scheduled_id'] if 'batch_id' in payment: del payment['batch_id'] p = Payment(**payment) p.route = 'subsidie' db.session.add(p) db.session.commit() new_payments_count += 1 except Exception as e: app.logger.error( "Saving a Bunq payment resulted in an exception:\n" + repr(e)) new_payments = False continue if not payments.pagination.has_previous_page(): new_payments = False # Log the number of retrieved payments iban = '' iban_name = '' for alias in monetary_account._alias: if alias._type_ == 'IBAN': iban = alias._value iban_name = alias._name app.logger.info('Project %s: retrieved %s payments for %s (%s)' % (project_id, new_payments_count, iban, iban_name))
def get_payments_for_user(user_id): payments = Payment.query.filter_by(user_id=user_id).all() return jsonify(Payment.serialize_list(payment))
def lessons_in_month(group_id, month_number): group = Group.query.get_or_404(group_id) if month_number < group.start_month or month_number > group.end_month: abort(404) month_name = get_month_name(month_number) students_in_group = group.students_in_group_in_month(month_number) \ .join(Student, Student.id == StudentInGroup.student_id) \ .order_by(Student.fio) \ .all() if 'submit' in request.form: if not can_user_write_group(current_user, group): abort(403) ls = Lesson.lessons_in_group_in_month(group_id, month_number).all() ps = Payment.query \ .join(StudentInGroup, StudentInGroup.id == Payment.student_in_group_id) \ .filter(StudentInGroup.group_id == group_id, Payment.month == month_number) payments = dict() for p in ps: payments[p.student_in_group_id] = p for student_in_group in students_in_group: new_value = request.form.get('p_{}'.format(student_in_group.id), 0, type=int) if new_value < 0: new_value = 0 max_value = group.section.price - student_in_group.discount if new_value > max_value: new_value = max_value payment = payments.get(student_in_group.id) is_cash = 'c_{}'.format(student_in_group.id) in request.form comment = request.form.get( 'comment_{}'.format(student_in_group.id), '') if payment is not None: if not payment.confirmed: payment.value = new_value payment.cash = is_cash payment.comment = comment else: db.session.add( Payment(student_in_group=student_in_group, month=month_number, value=new_value, cash=is_cash, comment=comment)) attendings = dict() for l in ls: attendings[l.id] = dict() for a in l.attendings: attendings[l.id][a.student_id] = a for l in ls: attending = attendings[l.id].get(student_in_group.student_id) a_key = 'a_{}_{}'.format(l.id, student_in_group.student_id) new_state = request.form.get(a_key, attending_was_not, type=int) if attending is not None: attending.state = new_state else: db.session.add( Attending(lesson=l, student=student_in_group.student, state=new_state)) flash('посещения и оплата в группе {} за {} сохранены.'.format( group.name, month_name)) return redirect( url_for('lessons.lessons_in_month', group_id=group_id, month_number=month_number)) pd = payments_in_month_info(group_id, month_number) ll = lessons_lists(group_id, month_number) return render_template('lessons/lessons_in_month.html', group=group, month_number=month_number, month_name=month_name, students_in_group=students_in_group, payments=pd.values, confirmed=pd.confirmed, cash=pd.cash, comments=pd.comments, lessons=ll[0], attendings_states=ll[1], write_mode=can_user_write_group( current_user, group))
def ipn(): arg = '' request.parameter_storage_class = ImmutableOrderedMultiDict values = request.form for x, y in values.items(): arg += "&{x}={y}".format(x=x, y=y) validate_url = 'https://www.sandbox.paypal.com' \ '/cgi-bin/webscr?cmd=_notify-validate{arg}' \ .format(arg=arg) r = requests.get(validate_url) if r.text == 'VERIFIED': payer_email = request.form.get('payer_email') unix = ctime() payment_date = request.form.get('payment_date') username = request.form.get('first_name') last_name = request.form.get('last_name') payment_gross = request.form.get('mc_gross') payment_fee = request.form.get('mc_fee') payment_net = float(payment_gross) - float(payment_fee) payment_status = request.form.get('payment_status') txn_id = request.form.get('txn_id') payment = Payment(payer_email=payer_email, unix=unix, payment_date=payment_date, username=username, last_name=last_name, payment_gross=payment_gross, payment_fee=payment_fee, payment_net=payment_net, payment_status=payment_status, txn_id=txn_id) db.session.add(payment) db.session.commit() send_email( "Payment from the website", ['*****@*****.**', '*****@*****.**'], """ Divaexplorer Order Summary Dear %s, Thank you for choosing Divaexplorer. Here's a summary of your order. Order Details Order Date: %s Payment Source: Paypal Transaction ID: %s Initial Charge: %s Final Cost: %s Item Type: TOTAL: %s For any concern. Please Contact us via [email protected]. Regards, Team Divaexplorer https://www.divaexplorer-tvj.co.uk/ London, UK """ % (username + " " + last_name, unix, txn_id, "£" + payment_gross, "£" + payment_gross, "£" + payment_gross)) with open('/tmp/ipnout.txt', 'a') as f: data = 'SUCCESS\n' + str(values) + '\n' f.write(data) else: with open('/tmp/ipnout.txt', 'a') as f: data = 'FAILURE\n' + str(values) + '\n' f.write(data) return r.text
def webhook_received(): # You can use webhooks to receive information about asynchronous payment events. # For more about our webhook events check out https://stripe.com/docs/webhooks. webhook_secret = ConfigValues.get_config_value('STRIPE_WHS') #"whsec_Z5rqV5EyWqGAcsGVsf1id7kfCk8hQXkI" #os.getenv('STRIPE_WEBHOOK_SECRET') request_data = json.loads(request.data) if webhook_secret: # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured. signature = request.headers.get('stripe-signature') try: event = stripe.Webhook.construct_event( payload=request.data, sig_header=signature, secret=webhook_secret) data = event['data'] except Exception as e: return e # Get the type of webhook event sent - used to check the status of PaymentIntents. event_type = event['type'] else: data = request_data['data'] event_type = request_data['type'] data_object = data['object'] if event_type == 'invoice.payment_succeeded': # Used to provision services after the trial has ended. # The status of the invoice will show up as paid. Store the status in your # database to reference when a user accesses your service to avoid hitting rate # limits. print(data) sid = request_data['data']['object']['customer'] user = User.get_user_by_stripe_id(stripe_id=sid) email = user.email Payment.send_subscription_renewal_success_email(user_email=email) userSub = UserSubscription.get_subscription(user_id=user.id) userSubscription = {} if len(userSub > 0): userSubscription = userSub[0] user_subscription_dict = {} user_subscription_dict['user_id'] = user.id user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id s_date = datetime.fromtimestamp(data['object']['period_start']) user_subscription_dict['current_start_date'] = s_date e_date = datetime.fromtimestamp(data['object']['period_end']) user_subscription_dict['current_end_date'] = e_date userSubscription.update(user_subscription_dict) user.update({'subscribed': 1, 'number_of_items_ordered_this_month' : 0}) if event_type == 'invoice.payment_failed': # If the payment fails or the customer does not have a valid payment method, # an invoice.payment_failed event is sent, the subscription becomes past_due. # Use this webhook to notify your user that their payment has # failed and to retrieve new card details. print(data) sid = request_data['data']['object']['customer'] user = User.get_user_by_stripe_id(stripe_id=sid) email = user.email Payment.send_subscription_renewal_failure_email(user_email=email) userSub = UserSubscription.get_subscription(user_id=user.id) userSubscription = {} if len(userSub > 0): userSubscription = userSub[0] user_subscription_dict = {} user_subscription_dict['user_id'] = user.id user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id s_date = datetime.fromtimestamp(data['object']['period_start']) user_subscription_dict['current_start_date'] = s_date e_date = datetime.fromtimestamp(data['object']['period_end']) user_subscription_dict['current_end_date'] = e_date userSubscription.update(user_subscription_dict) user.update({'subscribed': 0, 'number_of_items_ordered_this_month' : 0}) if event_type == 'invoice.finalized': # If you want to manually send out invoices to your customers # or store them locally to reference to avoid hitting Stripe rate limits. print(data) if event_type == 'customer.subscription.deleted': # handle subscription cancelled automatically based # upon your subscription settings. Or if the user cancels it. print(data) sid = request_data['data']['object']['customer'] user = User.get_user_by_stripe_id(stripe_id=sid) email = user.email userSub = UserSubscription.get_subscription(user_id=user.id) userSubscription = {} if len(userSub > 0): userSubscription = userSub[0] user_subscription_dict = {} user_subscription_dict['user_id'] = user.id user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id s_date = datetime.fromtimestamp(data['object']['period_start']) user_subscription_dict['current_start_date'] = s_date e_date = datetime.fromtimestamp(data['object']['period_end']) user_subscription_dict['current_end_date'] = e_date userSubscription.update(user_subscription_dict) Payment.send_subscription_cancelled_email(user_email=email) if datetime.now() > userSubscription.current_end_date: # else, there is another check when user makes an order and sets to 0 if it fails this validation user.update({'subscribed': 0, 'number_of_items_ordered_this_month' : 0}) if event_type == 'customer.subscription.trial_will_end': # Send notification to your user that the trial will end print(data) return jsonify({'status': 'success'})
def payment_converter(arg): identifier = [item.value for item in Payment if item.value[0] == arg][0] return Payment(identifier).value[1]