def create(image_id): nonce_from_the_client = request.form["payment_method_nonce"] amount = request.form["amount"] result = gateway.transaction.sale({ "amount": amount, "payment_method_nonce": nonce_from_the_client, "options": { "submit_for_settlement": True } }) if result.is_success or result.transaction: payment = Payment(user_id=current_user.id, image_id=image_id, amount=amount) payment.save() mg_key = os.environ.get('MAILGUN_API_KEY') result = requests.post( "https://api.mailgun.net/v3/sandboxdb0c2cd1760a44d08240d1f87633eeab.mailgun.org/messages", auth=("api", "'{}'.format(mg_key)"), data={ "from": "Excited User <*****@*****.**>", "to": ["*****@*****.**"], "subject": "Hello", "text": "Testing some Mailgun awesomeness!" }) return redirect(url_for('images.show', id=image_id)) else: flash("Failed to donate!", "danger") return redirect(url_for("payments.new", image_id=image_id))
def new(): student = Student.get_by_id(get_jwt_identity()) params = request.json if student: student_tutor_session = Student_tutor_session.get_by_id(params.get("student_tutor_session")) tutor_session = Tutor_session.get_by_id(student_tutor_session.tutor_session_id) # duration = tutor_session.duration # amount = tutor_session.price * duration # price per hour * hrs amount = tutor_session.price new_payment = Payment( student_tutor_session_id = student_tutor_session.id, amount = amount, status = 'complete', status_timestamp = datetime.now() ) if new_payment.save(): responseObject = ( { "message" : "Payment completed." , "status" : "success!", "payment" : { "id" : new_payment.id, "amount" : new_payment.amount, "status" : new_payment.status, "status_timestamp" : new_payment.status_timestamp, "student_tutor_session" : new_payment.student_tutor_session_id } } ) return make_response(jsonify(responseObject)), 201 else: return make_response(jsonify([err for err in new_payment.errors])), 400
def test_appends_a_status_to_a_new_payment(self): # given one_second = timedelta(seconds=1) now = datetime.utcnow() payment = Payment() # when payment.setStatus(TransactionStatus.PENDING) # then assert len(payment.statuses) == 1 assert payment.statuses[0].status == TransactionStatus.PENDING assert payment.statuses[0].detail is None assert now - one_second < payment.statuses[0].date < now + one_second
def pay_special_payments(): email = request.form['email'] cardname = request.form['cardname'] cardnumber = request.form['cardnumber'] cardcode = request.form['cardcode'] zipcode = request.form['zipcode'] cardinfo = { 'cardname': cardname, 'cardnumber': cardnumber, 'cardcode': cardcode, 'zipcode': zipcode } payment = Payment(email=email, cardinfo=cardinfo) payment.save_to_mongo() return make_response(back_to_profile())
def update(): student = Student.get_by_id(get_jwt_identity()) params = request.json if student: payment = Payment.get_by_id(params.get("payment_id")) payment.status = 'complete' payment.status_timestamp = datetime.now() if payment.save(): responseObject = ( { "message" : "Payment received." , "status" : "success!", "payment" : { "id" : payment.id, "amount" : payment.amount, "status" : payment.status, "status_timestamp" : payment.status_timestamp, "student_tutor_session" : payment.student_tutor_session_id } } ) return make_response(jsonify(responseObject)), 200 else: return make_response(jsonify([err for err in payment.errors])), 400
def new(): data = request.form subscription_amount = 5 target_user = User.get_or_none(User.id == data['user_id']) payment_nonce = request.form['payment_method_nonce'] payment_succeeded = False new_subscription = None if (target_user): transaction = transact({ "amount": subscription_amount, "payment_method_nonce": payment_nonce, "options": { "submit_for_settlement": True } }) print(transaction) if transaction: new_payment = Payment.create(amount=subscription_amount, payment_nonce=payment_nonce) new_subscription = Subscription.create(payment=new_payment.id, for_user=target_user.id) payment_succeeded = True return_data = None if new_subscription: return_data = new_subscription.as_dict() result = jsonify({'status': payment_succeeded, 'data': return_data}) return result
def create(): result = gateway.transaction.sale({ # this code then sends the nonce to brain tree's server # to check out the data you receive use: "request.form" "amount": request.form.get("amount"), "payment_method_nonce": request.form.get("paymentMethodNonce"), "options": { "submit_for_settlement": True } }) transaction_id = result.transaction.id amount = result.transaction.amount payment = Payment( amount=amount, transaction_id=transaction_id, user=current_user.id) payment.save() flash('Payment Sent!') return "temp"
def create_purchase(img_id): nonce = request.form.get("nonce") amount = request.form.get("dollar") message = request.form.get("message") result = gateway.transaction.sale({ "amount": amount, "payment_method_nonce": nonce, "options": { "submit_for_settlement": True } }) if result.is_success: payment = Payment(payment=amount, donator_id=current_user.id, image_id=img_id, message=message) if payment.save(): image = Image.get_or_none(id=img_id) image_owner = User.get_or_none(id=image.user_id) message = Mail( from_email="*****@*****.**", to_emails=image_owner.email, subject=f"Donation from {current_user.username}", html_content= f'<strong>A donation of RM{amount} is made on your image{img_id} from {current_user.username}</strong>' ) try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(str(e)) flash( f"Transaction successful! Thanks on the behalf of Nextagram and {image_owner.username}!", 'success') return redirect(url_for('home')) else: return render_template('payment/new.html') else: flash('Transaction failed', 'danger') return render_template('payment/new.html')
def create(): student_tutor_session = Student_tutor_session.get_by_id(1) tutor_session = Tutor_session.get_by_id(student_tutor_session.tutor_session) duration = tutor_session.duration amount = tutor_session.price*duration/60 # hourly rate * hrs print(f"the amount is {amount}") new_payment = Payment( student_tutor_session=student_tutor_session, amount=amount, ) if new_payment.save(): flash("transaction saved") else: flash("transaction failed") return render_template('home.html', errors = new_payment.errors)
def test_it_returns_an_empty_list_if_everything_has_been_reimbursed(self): # Given booking_paid1 = Booking() booking_paid1.payments = [Payment()] booking_reimbursement1 = BookingReimbursement( booking_paid1, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) booking_paid2 = Booking() booking_paid2.payments = [Payment()] booking_reimbursement2 = BookingReimbursement( booking_paid2, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) # When bookings_not_paid = filter_out_already_paid_for_bookings( [booking_reimbursement1, booking_reimbursement2]) # Then assert bookings_not_paid == []
def test_appends_a_status_to_a_payment_with_existing_status(self): # given one_second = timedelta(seconds=1) now = datetime.utcnow() payment = Payment() payment_status = PaymentStatus() payment_status.status = TransactionStatus.PENDING payment_status.date = datetime.utcnow() payment.statuses = [payment_status] # when payment.setStatus(TransactionStatus.SENT) # then assert len(payment.statuses) == 2 assert payment.statuses[1].status == TransactionStatus.SENT assert payment.statuses[1].detail is None assert now - one_second < payment.statuses[1].date < now + one_second
def checkout(): current_id = User.get_by_id(get_jwt_identity()) not_enough_items = Cart.select().join(Item).where( Cart.user == current_id, Cart.payment_status == False, Cart.amount > Item.stock) if len(not_enough_items) > 0: return jsonify("Message: There are not enough of these items in stock", [{ "item": { "id": item.item.id, "stock": item.item.stock, "color": item.item.color, "name": item.item.name, "product_type": item.item.product_type, "image": item.item.image_url, "price": item.item.price, "size": item.item.size } } for item in not_enough_items], "Please reduce amount", {"Status": "Failed"}), 400 else: print(request.form.get('paymentMethodNonce')) data = request.get_json() amount_input = data['amount'] pmNonce_input = data['paymentMethod'] result = gateway.transaction.sale({ "amount": amount_input, "payment_method_nonce": pmNonce_input, "options": { "submit_for_settlement": True } }) Payment(user=current_id, Braintree_Transaction_id=result.transaction.id, Total_amount=result.transaction.amount).save() cart_amount = Cart.select(Cart.amount).where(Cart.item_id == Item.id) item = (Item.update(stock=Item.stock - cart_amount).where( Item.id.in_( Cart.select( Cart.item_id).where((Cart.user == current_id) & (Cart.payment_status == False))))) item.execute() Cart.update(payment_status=True).where( Cart.user == current_id, Cart.payment_status == False).execute() print(result.transaction) print(result.transaction.id) print(result.transaction.amount) send_after_payment(current_id.email) return jsonify({'message': 'Success', 'status': 'success'}), 200
def create(image_id): nonce = request.form.get('nonce') moneyleft = request.form.get('money-left') moneyright = request.form.get('money-right') image = Image.get_by_id(image_id) recipient = User.get_by_id(image.user_id) try: if int(moneyleft) > -1 and int(moneyright) > -1 and int( moneyright) < 100: amount = f'{moneyleft}.{moneyright}' result = gateway.transaction.sale({ "amount": amount, "payment_method_nonce": nonce, "options": { "submit_for_settlement": True } }) if result.is_success: payment = Payment(user_id=current_user.id, image_id=image_id, amount=amount) payment.save() message = Mail( from_email='*****@*****.**', to_emails=recipient.email, subject='Donation Received', html_content=f'Donation received for {image.id}') sg = SendGridAPIClient( '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' ) sg.send(message) flash('Donation Success') return redirect(url_for('users.show', username=recipient.name)) except: flash('Payment failed. Try again', "Danger") return redirect(url_for('payments.new', image_id=image_id)) return f'{nonce}'
def convert_to_payment_from(order_form, user_id): new_payment = Payment(name=order_form.payment_name.data, year=order_form.year.data, month=order_form.month.data, card_no=order_form.card_number.data, payment_type=order_form.payment_type.data, payment_user_id=user_id, name_on_card=order_form.name_on_card.data) return new_payment
def create_purchase(picture_id): donation_amount = request.form.get('donation-amount') donation_message = request.form.get('donation-message') nonce = request.form.get('nonce') result = gateway.transaction.sale({ "amount": donation_amount, "payment_method_nonce": nonce, "options": { "submit_for_settlement": True } }) if result: new_payment_instance = Payment(donor_id=current_user.id, payment_amount=donation_amount, message=donation_message, picture_id=picture_id) new_payment_instance.save() picture = Picture.get_by_id(picture_id) user = User.get_by_id(picture.user_id) message = Mail( from_email=current_user.email, to_emails=user.email, subject= f"Nextagram: New Donation from {current_user.name.capitalize()}", html_content= f"<p>Dear {user.name.capitalize()},</p><br><p>{current_user.name.capitalize()} has just donated ${donation_amount} to you!</p><br><p>{current_user.name.capitalize()}\'s message: {donation_message}</p><br><p>With love,</p><br><p>Nextagram</p>" ) try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) flash('Payment successful') except Exception as e: print(str(e)) return redirect(url_for('users.show', username=user.name)) else: flash('Payment unsuccessful. Please try again.') return render_template('home.html')
def payment(): if request.method == 'POST': client_id = session['client_id'] buyer_name = request.form['buyer_name'] buyer_email = Utils.validate_email(request.form['buyer_email']) buyer_cpf = Utils.validate_cpf(request.form['buyer_cpf']) try: buyer = Buyer.check_buyers(buyer_name, buyer_email, buyer_cpf) except Errors.Error as e: return e.message payment_amount = request.form['payment_amount'] payment_type = request.form['payment_type'] if payment_type == 'Boleto': return redirect(url_for(".boleto_payment")) elif payment_type == 'Card': card_holder_name = request.form['card_holder_name'] card_number = CardValidators.validate_card( request.form['card_number']) card_expiration_date = request.form['card_expiration_date'] card_cvv = request.form['card_cvv'] try: card = Card.check_cards(card_holder_name, card_number, card_expiration_date, card_cvv) except Errors.Error as e: return e.message payment = Payment(client_id, payment_type, payment_amount, buyer, card) payment_status = Payment.register(payment) card_issuer = CardValidators.get_card_issuer(card_number) return redirect( url_for(".card_payment", status=payment_status, issuer=card_issuer))
def post(self): """ Create new payment. """ parsed_args = parser.parse_args() payment = Payment( price=parsed_args["price"], tax=parsed_args["tax"], sale_date=parsed_args["sale_date"], ) return self.finalize_post_req(payment)
def create_purchase(image_id): nonce_from_the_client = request.form["payment_nonce"] amount = request.form["amount"] print(nonce_from_the_client) print("0000000000000000000000000") print(amount) result = gateway.transaction.sale({ "amount": amount, "payment_method_nonce": nonce_from_the_client, "options": { "submit_for_settlement": True } }) if result.is_success: payment = Payment(sender=User.get_by_id(current_user.id), image_id=image_id, amount=amount) payment.save() return redirect(url_for("images.show", id=image_id)) else: flash("Failed to donate! Please try again!") return redirect(url_for("payments.new", image_id=image_id))
def delete_image(img_id): image = Image.get_or_none(id=img_id) user = User.get_or_none(id=image.user_id) for i in image.donation: query = Payment.get_or_none(id=i) if query: query.delete_instance() else: if image.delete_instance(): flash(f"Image ({img_id}) has successfully been removed!", "success") return redirect(url_for('users.show', username=user.username)) if image.delete_instance(): flash(f"Image ({img_id}) has successfully been removed!", "success") return redirect(url_for('users.show', username=user.username)) else: flash("Removing image failed", 'danger') return redirect(url_for('users.show', username=user.username))
def test_it_returns_reimbursements_on_bookings_with_no_existing_payments( self): # Given booking_paid = Booking() booking_paid.payments = [Payment()] booking_reimbursement1 = BookingReimbursement( booking_paid, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) booking_not_paid = Booking() booking_reimbursement2 = BookingReimbursement( booking_not_paid, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) booking_reimbursements = [ booking_reimbursement1, booking_reimbursement2 ] # When bookings_not_paid = filter_out_already_paid_for_bookings( booking_reimbursements) # Then assert len(bookings_not_paid) == 1 assert not bookings_not_paid[0].booking.payments
def post(self): """ Create new subscription. """ # Checks parsed_args = parser.parse_args() client = session.query(Client).filter( Client.user_id == auth.user.id).first() if not client: abort(404, message="Client doesn't exist") car = session.query(Car).filter( Car.id == parsed_args["car_id"]).first() if not car or car.client_id != client.id: abort(400, message="Not client's car.") place = session.query(Place).filter( Place.id == parsed_args["place_id"]).first() if not place or place.occupied: abort(400, message="Place not allowed.") if parsed_args["end"] <= datetime.utcnow().replace(tzinfo=pytz.UTC): abort(400, message="End date in past.") subscription = Subscription( end=parsed_args["end"], type=parsed_args["type"], place_id=place.id, car_id=car.id, ) session.add(subscription) self.try_session_commit() # make new payment for subscription payment = Payment( sale_date=datetime.utcnow().replace(tzinfo=pytz.UTC), price=calc_price(subscription.start, subscription.end), tax=calc_tax(), subscription_id=subscription.id, ) session.add(payment) return self.finalize_post_req(subscription)
def post(self): logging.info("arguments:{}".format(self.request.arguments)) payment_id = self.valid("trade_no") trade_id = self.valid("out_trade_no") fee = self.valid("total_amount", force_type=float) seller_id = self.valid("seller_id") trade_status = self.valid("trade_status", required=False) payor_id = self.valid("buyer_id", required=False) or "" created_at = self.valid("gmt_create", required=False) or "" payment_at = self.valid("gmt_payment", required=False) or "" # Add log. kwargs = { "trade_id": trade_id, "component": "wap_notify", "payload": self.request.arguments } LogTradeMgr.add(self.db, **kwargs) if self.errors: reason=self.errors.values()[0] raise HTTPError(422, "Arguments invalid", reason=reason) # Validate trade ID and total fee. trade = self.db.query(Trade).filter_by(trade_id=trade_id).first() if trade is None or float(fee) != float(trade.fee): # Notice is an exception notification, should be ignore. logging.exception("exception notificaton, trade_id:{}".format(trade_id)) return self.finish("success") # Validate seller ID. if seller_id is not None and seller_id != config.ali_seller_id: # Notice is an exception notification, should be ignore. logging.exception("exception notificaton, trade_id:{}".format(trade_id)) return self.finish("success") utcnow = util.utcnow() if trade_status in ["TRADE_SUCCESS", "TRADE_FINISHED"]: kwargs = { "payor_id": payor_id, "status": trade_status, "created_at": created_at, "payment_at": payment_at, "trade": trade, "inserted_at": utcnow, "updated_at": utcnow, "payment_id": payment_id } payment = Payment(**kwargs) if trade_status == "TRADE_SUCCESS": trade.status = TradeStatus.SUCCESS else: # Trade finished, No refundable trade.status = TradeStatus.FINISHED self.db.add(payment) self.db.commit() elif trade_status == "TRADE_CLOSED": # TODO pass else: # TODO pass self.finish("success")
}, { 'parent_event': TripEvent.select().first().id + 4, 'url': 'photoplace.com/files/some_photo.jpg' }, { 'parent_event': TripEvent.select().first().id + 4, 'url': 'photoplace.com/files/last_photo.jpg' }] for pa in photo_list: if PhotoAttachment.get_or_none(PhotoAttachment.url == pa['url']) == None: PhotoAttachment.create(parent_event=pa['parent_event'], url=pa['url']) # Payments from models.payment import Payment import decimal payment_list = [{'amount': 50, 'payment_nonce': 'abcde'}] for py in payment_list: Payment.create(amount=py['amount'], payment_nonce=py['payment_nonce']) # Subscriptions from models.subscription import Subscription subscription_list = [{ 'for_user': User.select().first().id + 1, 'payment': Payment.select().first().id }] for sb in subscription_list: Subscription.create(for_user=sb['for_user'], payment=sb['payment'])
session = Session() iters = 10000 faker = Faker() faker.add_provider(internet) faker.add_provider(person) faker.add_provider(lorem) with tqdm(total=iters) as progress_bar: for _ in range(iters): user = session.query(User).order_by(func.random()).first() product = session.query(Product).order_by(func.random()).first() dice = [faker.random_int(min=0, max=99, step=1), product.price] session.add( Payment(user_id=user.id, product_id=product.id, ammount=random.choice(dice))) progress_bar.update(1) session.commit() with tqdm(total=iters) as progress_bar: for payment in session.query(Payment).all(): payment_task = PaymentTask(user_id=payment.user_id, payment_id=payment.id, tries_left=5, processing=False) session.add(payment_task) progress_bar.update(1) session.commit()
def view_special_payments(): payments = Payment.get_payment_by_email(session['email']) return render_template('view-payments.html', payments=payments)
def delete_payment(payment_id): Payment.delete_payment(payment_id) return make_response(back_to_profile())
def edit_payment(payment_id): payment = Payment.get_by_id(payment_id) return make_response(back_to_profile())
def boleto_payment(): boleto_number = Payment.boleto_payment() return boleto_number
from models.user import User from models.trip import Trip from models.trip_event import TripEvent from models.file_attachment import FileAttachment from models.photo_attachment import PhotoAttachment from models.payment import Payment from models.subscription import Subscription FileAttachment.delete().execute() PhotoAttachment.delete().execute() Subscription.delete().execute() Payment.delete().execute() User.delete().execute() Trip.delete().execute() TripEvent.delete().execute()
def create_payment_for_booking( booking_reimbursement: BookingReimbursement) -> Payment: venue = booking_reimbursement.booking.stock.resolvedOffer.venue payment = Payment() payment.booking = booking_reimbursement.booking payment.amount = booking_reimbursement.reimbursed_amount payment.reimbursementRule = booking_reimbursement.reimbursement.value.description payment.reimbursementRate = booking_reimbursement.reimbursement.value.rate payment.author = 'batch' payment.transactionLabel = make_transaction_label(datetime.utcnow()) if venue.iban: payment.iban = format_raw_iban_or_bic(venue.iban) payment.bic = format_raw_iban_or_bic(venue.bic) else: offerer = venue.managingOfferer payment.iban = format_raw_iban_or_bic(offerer.iban) payment.bic = format_raw_iban_or_bic(offerer.bic) payment.recipientName = venue.managingOfferer.name payment.recipientSiren = venue.managingOfferer.siren if payment.iban: payment.setStatus(TransactionStatus.PENDING) else: payment.setStatus(TransactionStatus.NOT_PROCESSABLE, detail='IBAN et BIC manquants sur l\'offreur') return payment